From ce83740bb087019b9dae7721924f90423e60f281 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Fri, 20 Nov 2026 00:21:04 -0500 Subject: [PATCH 01/11] fix(mobile): names and the Chats list settle before they paint Mobile kept participant names in each screen's own state and learned which threads an agent spawned only after Chats had painted. The Inbox showed "Unnamed participant" on every visit, a new sender read "Agent" first, and a cold start listed spawned threads for half a second before dropping them. J5 now remembers, per server and paired credential, the names it has heard and the spawned-children answers, in a small file in the app's cache. Chats leaves spawned threads out on its first paint and holds a new thread back while its answer is on its way. A name still on its way shows nothing rather than a stand-in. A re-pair drops what the last person heard at once, and the Open parent bar waits for the server to say who the new person is (#1082). A prompt's work-log row puts "answered by" right after its label (IN-29). Co-Authored-By: Claude Opus 5.5 --- FORK.md | 5 +- .../src/features/threads/thread-work-log.tsx | 3 +- .../src/features/threads/work-log-layout.tsx | 6 +- .../src/j5/a2a/participantIdentities.ts | 86 ++++--- apps/mobile/src/j5/a2a/timeline.tsx | 15 +- .../src/j5/a2a/timelinePresentation.test.ts | 1 + .../mobile/src/j5/a2a/timelinePresentation.ts | 2 + .../src/j5/connection/memory.logic.test.ts | 180 ++++++++++++++ apps/mobile/src/j5/connection/memory.logic.ts | 228 ++++++++++++++++++ apps/mobile/src/j5/connection/memory.ts | 223 +++++++++++++++++ apps/mobile/src/j5/crew/spawnedChildren.ts | 55 +++-- apps/mobile/src/j5/inbox/InboxScreen.tsx | 15 +- apps/mobile/src/j5/inbox/senderLabels.ts | 77 +++--- .../src/j5/sharing/sharedConversation.tsx | 15 +- .../mobile/src/j5/threads/J5OpenParentBar.tsx | 5 +- apps/mobile/src/j5/upstreamSeams.test.ts | 1 + 16 files changed, 815 insertions(+), 102 deletions(-) create mode 100644 apps/mobile/src/j5/connection/memory.logic.test.ts create mode 100644 apps/mobile/src/j5/connection/memory.logic.ts create mode 100644 apps/mobile/src/j5/connection/memory.ts diff --git a/FORK.md b/FORK.md index 3c0d06ce50f7a..3f6c711613a42 100644 --- a/FORK.md +++ b/FORK.md @@ -518,7 +518,7 @@ migrations after upstream migrations. 98. Mobile reads artifacts ([#833](https://github.com/Jacksondr5/j5code/issues/833)), landing two reserved mobile seams. Route registration: `apps/mobile/src/Stack.tsx` imports J5-owned `j5ThreadRoutes` (`apps/mobile/src/j5/threadRoutes.ts`) and spreads it after `ThreadFile`, adding the thread-scoped `ThreadArtifacts` list and `ThreadArtifact` viewer (`apps/mobile/src/j5/artifacts/ThreadArtifactsScreen.tsx`), read-only, with no delete; since case 114 it also registers the `ThreadCrewProposal` review screen. Link resolver: `onMarkdownLinkPress` in `apps/mobile/src/features/threads/ThreadFeed.tsx` makes one call to J5-owned `openArtifactLink` before its thread, media and file branches, so an `artifacts/…` link opens the viewer instead of a missing workspace file; its `fileContextMenu` and `onFileContextMenuAction` each make one call first (`artifactLinkContextMenu`, `onArtifactLinkMenuAction`), so an artifact link's long press offers Open artifact and Copy path instead of workspace-file actions. Links inside a Markdown artifact go through the same helpers in the J5 viewer. Recognition, preview kind and the HTTP read are shared with web in `packages/client-runtime/src/j5/artifacts.ts`. No upstream entry point reaches the list yet; it is one tap from any opened artifact. -99. Mobile's shared conversations show who wrote each message and who answered each prompt, the mobile half of case 80 ([#832](https://github.com/Jacksondr5/j5code/issues/832), register D33, Shared conversations AC9 to AC11, AC14 and AC16). The record and its change feed are `threadAuthors` and `threadAuthorsChanges` in `packages/client-runtime/src/j5/sharing.ts`, beside who reaches the thread (`scopePeople` and `scopePeopleChanges`), which says the thread is shared before any author is recorded (`mayBeSharedConversation`, [#871](https://github.com/Jacksondr5/j5code/issues/871)); and the reading of it (`sharedMessageView`, the typed text, the answers without their mark, the search label) is `packages/client-runtime/src/j5/sharedConversation.ts`, both shared with web. `apps/mobile/src/features/threads/ThreadRouteScreen.tsx` imports `useSharedConversationFeed` from J5-owned `apps/mobile/src/j5/sharing/sharedConversation.tsx` and passes its answer as `ThreadDetailScreen`'s `selectedThreadFeed` in place of `composer.selectedThreadFeed`: an authored message shows as typed, after its note to the agent as a muted line that opens (drawn by case 97's `renderJ5TimelineNotice`), a message whose author is not read yet is held back or shown as this client typed it, and a question's answers lose the platform's `[Answer from …]` mark. Case 97's `useJ5Timeline` also reads the record, so `resolveJ5FeedMessage` puts another person's message on the left and `J5MessageAuthorLine` names them, or says who edited the reader's own. `apps/mobile/src/features/threads/thread-work-log.tsx` mounts `PromptAnsweredBy` after a work row's label (" · answered by Priya", on an approval too), outside the label so the label truncates first. A folded answered question shows its trimmed question and who answered, or "· answered" where no one is recorded, as in an unshared thread ([#1028](https://github.com/Jacksondr5/j5code/issues/1028)); its answer is in the opened row ([#959](https://github.com/Jacksondr5/j5code/issues/959)). Opened, an answered question whose answer records its question text drops the trimmed question from the header for "answered by Priya", or "answered" where no one is recorded, and the row draws no raw item JSON beneath the question and answer, as web draws neither ([#891](https://github.com/Jacksondr5/j5code/issues/891)). `apps/mobile/src/features/threads/ThreadQueueControl.tsx` reads its rows through `useSharedQueuedRuns` where it builds `queuedRuns`, ahead of case 97's hook, so a queued message's row and the text an edit loads are the words typed. `apps/mobile/src/features/threads/thread-search-match.tsx` labels a hit with `threadSearchMatchLabel` instead of "You:" for every user-role hit. `apps/mobile/src/lib/filePreview.test.ts` mocks `sharedConversation.tsx` as it mocks case 97's `timelineState.ts`. Proofs: `apps/mobile/src/j5/sharing/sharedConversationFeed.test.ts`, `apps/mobile/src/j5/a2a/timelinePresentation.test.ts`, `packages/client-runtime/src/j5/sharedConversation.test.ts`, `packages/client-runtime/src/j5/threadSearchMatchLabel.test.ts`, and the four files' rows in `apps/mobile/src/j5/upstreamSeams.test.ts`. On every rebase, keep the calls that test lists. +99. Mobile's shared conversations show who wrote each message and who answered each prompt, the mobile half of case 80 ([#832](https://github.com/Jacksondr5/j5code/issues/832), register D33, Shared conversations AC9 to AC11, AC14 and AC16). The record and its change feed are `threadAuthors` and `threadAuthorsChanges` in `packages/client-runtime/src/j5/sharing.ts`, beside who reaches the thread (`scopePeople` and `scopePeopleChanges`), which says the thread is shared before any author is recorded (`mayBeSharedConversation`, [#871](https://github.com/Jacksondr5/j5code/issues/871)); and the reading of it (`sharedMessageView`, the typed text, the answers without their mark, the search label) is `packages/client-runtime/src/j5/sharedConversation.ts`, both shared with web. `apps/mobile/src/features/threads/ThreadRouteScreen.tsx` imports `useSharedConversationFeed` from J5-owned `apps/mobile/src/j5/sharing/sharedConversation.tsx` and passes its answer as `ThreadDetailScreen`'s `selectedThreadFeed` in place of `composer.selectedThreadFeed`: an authored message shows as typed, after its note to the agent as a muted line that opens (drawn by case 97's `renderJ5TimelineNotice`), a message whose author is not read yet is held back or shown as this client typed it, and a question's answers lose the platform's `[Answer from …]` mark. Case 97's `useJ5Timeline` also reads the record, so `resolveJ5FeedMessage` puts another person's message on the left and `J5MessageAuthorLine` names them, or says who edited the reader's own. `apps/mobile/src/features/threads/thread-work-log.tsx` mounts `PromptAnsweredBy` after a work row's label (" · answered by Priya", on an approval too), outside the label so the label truncates first. On a prompt's row (`answeredByFollowsLabel`) it passes upstream's `WorkLogLabel` (`work-log-layout.tsx`) a new optional `fitText`, so the label ends with its text and `PromptAnsweredBy` follows it and takes the spare width; with nothing to say there, it is an empty spacer that keeps the row's end in place. A folded answered question shows its trimmed question and who answered, or "· answered" where no one is recorded, as in an unshared thread ([#1028](https://github.com/Jacksondr5/j5code/issues/1028)); its answer is in the opened row ([#959](https://github.com/Jacksondr5/j5code/issues/959)). Opened, an answered question whose answer records its question text drops the trimmed question from the header for "answered by Priya", or "answered" where no one is recorded, and the row draws no raw item JSON beneath the question and answer, as web draws neither ([#891](https://github.com/Jacksondr5/j5code/issues/891)). `apps/mobile/src/features/threads/ThreadQueueControl.tsx` reads its rows through `useSharedQueuedRuns` where it builds `queuedRuns`, ahead of case 97's hook, so a queued message's row and the text an edit loads are the words typed. `apps/mobile/src/features/threads/thread-search-match.tsx` labels a hit with `threadSearchMatchLabel` instead of "You:" for every user-role hit. `apps/mobile/src/lib/filePreview.test.ts` mocks `sharedConversation.tsx` as it mocks case 97's `timelineState.ts`. Proofs: `apps/mobile/src/j5/sharing/sharedConversationFeed.test.ts`, `apps/mobile/src/j5/a2a/timelinePresentation.test.ts`, `packages/client-runtime/src/j5/sharedConversation.test.ts`, `packages/client-runtime/src/j5/threadSearchMatchLabel.test.ts`, and the four files' rows in `apps/mobile/src/j5/upstreamSeams.test.ts`. On every rebase, keep the calls that test lists. 100. The mobile new-task composer gives a saved agent its own row and lets the slash menu cover the draft rows ([#866](https://github.com/Jacksondr5/j5code/issues/866), Jackson's direction at Checkpoint 1, 2026-11-01; register entry in the wave-2 docs PR). Upstream's composer shows the model in its input row and opens the slash menu above everything stacked over the input. In `apps/mobile/src/features/threads/NewTaskDraftScreen.tsx`, the draft controls render J5-owned `j5/agents/DraftAgentRow.tsx` under the checkout row: the saved-agent picker, then the chosen agent's persona, route and remove action. `apps/mobile/src/features/threads/ThreadComposer.tsx` renders the persona lock control, which wraps upstream's `usesLargeControls` model control since v0.1.7, only when `!props.isDraft`, so a draft's input row stays the editor, and wraps `ComposerPopoverAnchor` in a zero-height `relative` view placed after `draftControls`. The anchor's `bottom-full` (and the Android anchor's measured frame) then starts at the top of the input, so the menu draws over the checkout and agent rows instead of above them. A started thread has no draft controls, so its menu opens where it did. @@ -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. Between them, `J5OpenParentBar` (`apps/mobile/src/j5/threads/`) gives a Crew member or Peer Agent upstream's Open parent button, leading to its Captain or spawner, read from the Fleet roster by web's Lineage logic, now `packages/client-runtime/src/j5/lineage.ts` (`./j5/lineage`) ([#1062](https://github.com/Jacksondr5/j5code/issues/1062)). Opened, the dock grows with the question up to the room above the composer, less one row for the playbook bar and the measured height of the rows above the dock. That room is upstream's `pendingUserInputMaxHeight`, which its own pending-question card gets in the composer's place, less the composer's height above its inset, plus that inset while the keyboard covers it (upstream's room takes it off even then), so `ThreadDetailScreen.tsx` passes `J5ComposerControls` `maxHeight`, `composerHeight` and `composerBottomInset` ([#1025](https://github.com/Jacksondr5/j5code/issues/1025)). As in the mobile Inbox, its answer carries photos and files ([#1041](https://github.com/Jacksondr5/j5code/issues/1041)), and an Owner sees the ask's Owner action ([#1040](https://github.com/Jacksondr5/j5code/issues/1040)). 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`, `./j5/crew-memberships` and `./j5/lineage` exports this case appends to upstream-owned `packages/client-runtime/package.json`. -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. +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. Each answer is remembered per server and paired credential (`apps/mobile/src/j5/connection/memory.ts`, saved in the app's cache), so a cold start's first paint already leaves them out, and a thread no answer covers yet waits while one is on its way; 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: `packages/client-runtime/src/j5/lineage.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. @@ -992,6 +992,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/work-log-layout.tsx` | N | 99 | | `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 | diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index 775e145a60078..7411d2b3cbe6e 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -59,7 +59,7 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState"; import { AppText as Text } from "../../components/ui/AppText"; import { J5Wordmark } from "../../j5/branding/J5Wordmark"; -import { PromptAnsweredBy } from "../../j5/sharing/sharedConversation"; +import { answeredByFollowsLabel, PromptAnsweredBy } from "../../j5/sharing/sharedConversation"; import { BrowserAppIcon } from "./BrowserAppIcon"; import { useAppActive, useReduceMotionEnabled } from "../../lib/appState"; import { cn } from "../../lib/cn"; @@ -1158,6 +1158,7 @@ const ThreadWorkLogRow = function ThreadWorkLogRow( {historyHasQuestion && expanded ? null : displayText} {answerPreview && !answered ? ( diff --git a/apps/mobile/src/features/threads/work-log-layout.tsx b/apps/mobile/src/features/threads/work-log-layout.tsx index 41b353b015593..cacfd7354d6d4 100644 --- a/apps/mobile/src/features/threads/work-log-layout.tsx +++ b/apps/mobile/src/features/threads/work-log-layout.tsx @@ -51,9 +51,12 @@ export function WorkLogPressable({ export function WorkLogLabel({ children, tone = "default", + fitText = false, }: { children: ReactNode; tone?: "default" | "danger" | "warning"; + /** J5 (case 99): the label ends with its text, and what follows it takes the spare width. */ + fitText?: boolean; }) { return ( = new Set(); + +export interface ScreenIdentities extends ParticipantIdentities { + /** Participants whose name is on its way: say nothing for them yet rather than a fallback. */ + readonly pending: ReadonlySet; +} + +/** Ids a connected server has not answered for yet and has no remembered name for. */ +export const pendingParticipants = ( + snapshot: MemorySnapshot, + environmentId: EnvironmentId, + participantIds: ReadonlyArray, + connected: boolean, +): ReadonlySet => { + if (!connected) return NO_ONE; + const heard = snapshot.heard.get(environmentId); + const labels = snapshot.memory.get(environmentId)?.names.labels; + const pending = participantIds.filter((id) => !heard?.has(id) && !labels?.has(id)); + return pending.length === 0 ? NO_ONE : new Set(pending); +}; + +export const useConnectedEnvironmentIds = (): ReadonlySet => { + const environments = useWorkspaceEnvironments(); + const key = environments + .flatMap((environment) => + environment.connectionState === "connected" ? [environment.environmentId] : [], + ) + .sort() + .join("\n"); + return useMemo(() => new Set(key === "" ? [] : (key.split("\n") as Array)), [key]); +}; /** - * One identity read for the ids on screen; unknowns stay absent and a failed read names nobody. - * A read sent before the environment connects fails, so it waits for the connection and runs - * again on each reconnect. + * Names for the ids on screen, kept per server and paired credential, so a revisit or a new + * sender never drops the names already shown. Each id is asked once a connection; a read sent + * before the environment connects fails, so it waits for the connection. */ export function useParticipantIdentities( environmentId: EnvironmentId, participantIds: ReadonlyArray, -): ParticipantIdentities { +): ScreenIdentities { const idsKey = Array.from(new Set(participantIds)).sort().join("\0"); - // A result answers one environment's ids; another environment's never stands in for it. - const key = `${environmentId}\n${idsKey}`; - const connected = useWorkspaceEnvironments().some( - (environment) => - environment.environmentId === environmentId && environment.connectionState === "connected", + const connected = useConnectedEnvironmentIds().has(environmentId); + const snapshot = useSyncExternalStore( + connectionMemory.subscribe, + connectionMemory.getSnapshot, + connectionMemory.getSnapshot, ); - const [result, setResult] = useState({ key: "", identities: NO_IDENTITIES }); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads identities from the server for the ids on screen, and drops a stale answer when they change. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the server for names of the ids on screen it has not named this connection. useEffect(() => { if (idsKey === "" || !connected) return; - let active = true; - void readParticipantIdentities( - j5Environment, - appAtomRegistry, + void connectionMemory.readNames(environmentId, idsKey.split("\0")); + }, [connected, environmentId, idsKey]); + const names = snapshot.memory.get(environmentId)?.names ?? NO_IDENTITIES; + const pendingKey = [ + ...pendingParticipants( + snapshot, environmentId, - idsKey.split("\0"), - ).then((identities) => { - if (active) setResult({ key, identities }); - }); - return () => { - active = false; - }; - }, [connected, environmentId, idsKey, key]); - return result.key === key ? result.identities : NO_IDENTITIES; + idsKey === "" ? [] : idsKey.split("\0"), + connected, + ), + ].join("\0"); + const pending = useMemo( + () => (pendingKey === "" ? NO_ONE : new Set(pendingKey.split("\0"))), + [pendingKey], + ); + return useMemo(() => ({ ...names, pending }), [names, pending]); } diff --git a/apps/mobile/src/j5/a2a/timeline.tsx b/apps/mobile/src/j5/a2a/timeline.tsx index f059af401ec90..fa671d97076c7 100644 --- a/apps/mobile/src/j5/a2a/timeline.tsx +++ b/apps/mobile/src/j5/a2a/timeline.tsx @@ -389,11 +389,16 @@ function ParticipantAuthorLine(props: { const { j5 } = props; const openLinkedThread = useOpenLinkedThread(); const sender = useSenderThread(props.message, props.presentation, props.timeline); - const name = j5MessageAuthorName({ - presentation: j5, - participantLabels: props.timeline.labels, - senderThreadTitle: sender.title, - }); + // A sender whose name is on its way keeps the line's height without a stand-in word. + const named = + j5.senderId === null || !props.timeline.pending.has(j5.senderId) || !!sender.title?.trim(); + const name = named + ? j5MessageAuthorName({ + presentation: j5, + participantLabels: props.timeline.labels, + senderThreadTitle: sender.title, + }) + : " "; const { ref } = sender; return ( diff --git a/apps/mobile/src/j5/a2a/timelinePresentation.test.ts b/apps/mobile/src/j5/a2a/timelinePresentation.test.ts index 6c632a47e847a..312841918a972 100644 --- a/apps/mobile/src/j5/a2a/timelinePresentation.test.ts +++ b/apps/mobile/src/j5/a2a/timelinePresentation.test.ts @@ -21,6 +21,7 @@ const timeline = (viewerParticipantId: string | null): J5Timeline => ({ viewerParticipantId, labels: new Map(), threads: new Map(), + pending: new Set(), sharedAuthors: new Map(), }); diff --git a/apps/mobile/src/j5/a2a/timelinePresentation.ts b/apps/mobile/src/j5/a2a/timelinePresentation.ts index b0a7a7ca2a281..9af497c610e53 100644 --- a/apps/mobile/src/j5/a2a/timelinePresentation.ts +++ b/apps/mobile/src/j5/a2a/timelinePresentation.ts @@ -23,6 +23,8 @@ import type { MessageAuthor } from "@t3tools/contracts/j5"; * who sent each message of a shared conversation. */ export interface J5Timeline extends ParticipantIdentities { + /** Senders whose name is still on its way. */ + readonly pending: ReadonlySet; readonly environmentId: EnvironmentId; readonly viewerParticipantId: string | null; readonly sharedAuthors: ReadonlyMap; diff --git a/apps/mobile/src/j5/connection/memory.logic.test.ts b/apps/mobile/src/j5/connection/memory.logic.test.ts new file mode 100644 index 0000000000000..e0bc271707582 --- /dev/null +++ b/apps/mobile/src/j5/connection/memory.logic.test.ts @@ -0,0 +1,180 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { AsyncResult } from "effect/reactivity"; +import { describe, expect, it } from "vite-plus/test"; + +import { + answeredSince, + credentialKey, + crewListedThreads, + decodeMemory, + encodeMemory, + observeCredential, + rememberIdentities, + rememberSpawned, + type ConnectionMemory, +} from "./memory.logic"; + +const server = EnvironmentId.make("server-1"); +const owner = "bearer:owner"; +const viewer = "bearer:viewer"; +const id = (value: string) => ThreadId.make(value); +const row = (threadId: string, pinnedAt: string | null = null) => ({ + environmentId: server, + id: id(threadId), + archivedAt: null, + pinnedAt, +}); +const titles = (threads: ReadonlyArray<{ readonly id: ThreadId }>) => + threads.map((thread) => thread.id); +const answering = new Set([server]); +const nobodyAnswering = new Set(); + +/** What a launch remembers after one spawned-children read answered for these threads. */ +const heard = (spawned: ReadonlyArray, notSpawned: ReadonlyArray) => + rememberSpawned( + observeCredential(new Map(), server, owner), + server, + owner, + [...spawned, ...notSpawned].map(id), + spawned.map(id), + ); + +describe("crewListedThreads", () => { + it("leaves spawned threads out of a cold start's first paint, from the saved answers", () => { + const saved = encodeMemory(heard(["seat", "peer"], ["captain", "human"])); + const threads = [row("captain"), row("seat"), row("human"), row("peer")]; + + expect(titles(crewListedThreads(threads, decodeMemory(saved), answering))).toEqual([ + id("captain"), + id("human"), + ]); + }); + + it("holds back a thread nobody has answered for while its server's answer is on its way", () => { + const memory = heard([], ["captain"]); + const threads = [row("captain"), row("new-peer")]; + + expect(titles(crewListedThreads(threads, memory, answering))).toEqual([id("captain")]); + // Offline, refused or failed: no answer is coming, so the thread shows. + expect(crewListedThreads(threads, memory, nobodyAnswering)).toBe(threads); + // A server never heard from (a first launch, a new pairing) lists everything, not nothing. + expect(crewListedThreads(threads, new Map(), answering)).toBe(threads); + }); + + it("keeps the Captain listed through a spawn, and the new agent never shows", () => { + const threads = [row("captain"), row("new-peer")]; + const before = heard([], ["captain"]); + const after = rememberSpawned( + before, + server, + owner, + [id("captain"), id("new-peer")], + [id("new-peer")], + ); + + expect(titles(crewListedThreads(threads, before, answering))).toEqual([id("captain")]); + expect(titles(crewListedThreads(threads, after, answering))).toEqual([id("captain")]); + }); + + it("lists a pinned spawned thread, even before anyone answers for it", () => { + const threads = [ + row("pinned-seat", "2026-11-19T00:00:00.000Z"), + row("seat"), + row("pinned-new-seat", "2026-11-19T00:00:00.000Z"), + ]; + const memory = heard(["seat", "pinned-seat"], []); + + expect(titles(crewListedThreads(threads, memory, answering))).toEqual([ + id("pinned-seat"), + id("pinned-new-seat"), + ]); + }); +}); + +describe("participant names", () => { + const names = (memory: ConnectionMemory) => memory.get(server)?.names.labels; + const named = (labels: ReadonlyArray) => ({ + labels: new Map(labels), + threads: new Map(), + }); + + it("keeps the names on screen when a new sender's name arrives", () => { + const first = rememberIdentities( + observeCredential(new Map(), server, owner), + server, + owner, + ["agent:a"], + named([["agent:a", "Sender A"]]), + ); + const second = rememberIdentities(first, server, owner, ["agent:b"], named([["agent:b", "B"]])); + + expect(names(second)).toEqual( + new Map([ + ["agent:a", "Sender A"], + ["agent:b", "B"], + ]), + ); + }); + + it("survives a reconnect and a cold start on the same credential", () => { + const memory = rememberIdentities( + heard(["seat"], []), + server, + owner, + ["agent:a"], + named([["agent:a", "Sender A"]]), + ); + + expect(observeCredential(memory, server, owner)).toBe(memory); + const restored = observeCredential(decodeMemory(encodeMemory(memory)), server, owner); + expect(names(restored)).toEqual(new Map([["agent:a", "Sender A"]])); + expect(restored.get(server)?.spawned.get(id("seat"))).toBe(true); + }); + + it("drops what the last person heard as soon as another person pairs, and their late answers", () => { + const memory = rememberIdentities( + heard(["seat"], []), + server, + owner, + ["agent:captain"], + named([["agent:captain", "Captain"]]), + ); + const repaired = observeCredential(memory, server, viewer); + + expect(names(repaired)).toEqual(new Map()); + expect(repaired.get(server)?.spawned.size).toBe(0); + const late = rememberIdentities( + repaired, + server, + owner, + ["agent:captain"], + named([["agent:captain", "Captain"]]), + ); + expect(late).toBe(repaired); + }); +}); + +describe("credentialKey", () => { + it("tells two pairings apart without keeping the token", () => { + const prepared = (token: string) => ({ + httpAuthorization: { _tag: "Bearer" as const, token }, + target: { environmentId: server }, + }); + const first = credentialKey(prepared("secret-token-one")); + + expect(first).toBe(credentialKey(prepared("secret-token-one"))); + expect(first).not.toBe(credentialKey(prepared("secret-token-two"))); + expect(first).not.toContain("secret"); + }); +}); + +describe("answeredSince", () => { + it("waits for the access answer the new connection settles, even when it reuses the value", () => { + const owner = { kind: "person", wide: true }; + const baseline = AsyncResult.success(owner); + + expect(answeredSince(baseline, baseline)).toBe(false); + expect(answeredSince(baseline, AsyncResult.success(owner, { waiting: true }))).toBe(false); + expect(answeredSince(baseline, AsyncResult.success(owner))).toBe(true); + }); +}); diff --git a/apps/mobile/src/j5/connection/memory.logic.ts b/apps/mobile/src/j5/connection/memory.logic.ts new file mode 100644 index 0000000000000..43a07788a440b --- /dev/null +++ b/apps/mobile/src/j5/connection/memory.logic.ts @@ -0,0 +1,228 @@ +import type { PreparedConnection } from "@t3tools/client-runtime/connection"; +import { isSidebarMember } from "@t3tools/client-runtime/j5/spawned-children"; +import type { ParticipantIdentities } from "@t3tools/client-runtime/j5/participant-identity"; +import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import type { AsyncResult } from "effect/reactivity"; +import * as Schema from "effect/Schema"; + +/** What this device last heard on one server under one paired credential. */ +export interface RememberedConnection { + readonly credential: string; + /** Threads the spawned-children read answered for: true when an agent spawned the thread. */ + readonly spawned: ReadonlyMap; + /** Kept apart from `spawned`, so a classification never re-renders a feed that reads names. */ + readonly names: ParticipantIdentities; +} + +export type ConnectionMemory = ReadonlyMap; + +const NO_NAMES: ParticipantIdentities = { labels: new Map(), threads: new Map() }; + +/** FNV-1a, so the saved file names a credential without holding its token. */ +const fingerprint = (text: string) => { + let hash = 0x811c9dc5; + for (let index = 0; index < text.length; index += 1) { + hash ^= text.charCodeAt(index); + hash = Math.imul(hash, 0x01000193) >>> 0; + } + return hash.toString(36); +}; + +/** + * The paired credential a connection uses: its bearer token, which re-pairing replaces and a + * reconnect keeps. A connection without one is known by its route. + */ +export const credentialKey = (prepared: { + readonly httpAuthorization: PreparedConnection["httpAuthorization"]; + readonly target: unknown; +}) => + prepared.httpAuthorization?._tag === "Bearer" + ? `bearer:${fingerprint(prepared.httpAuthorization.token)}` + : `route:${fingerprint(JSON.stringify(prepared.target))}`; + +const emptyConnection = (credential: string): RememberedConnection => ({ + credential, + spawned: new Map(), + names: NO_NAMES, +}); + +/** A different credential is a different person: nothing heard under the old one carries over. */ +export const observeCredential = ( + memory: ConnectionMemory, + environmentId: EnvironmentId, + credential: string, +): ConnectionMemory => + memory.get(environmentId)?.credential === credential + ? memory + : new Map(memory).set(environmentId, emptyConnection(credential)); + +/** An answer read under another credential than the remembered one is dropped. */ +const updateConnection = ( + memory: ConnectionMemory, + environmentId: EnvironmentId, + credential: string, + update: (connection: RememberedConnection) => RememberedConnection, +): ConnectionMemory => { + const connection = memory.get(environmentId) ?? emptyConnection(credential); + if (connection.credential !== credential) return memory; + return new Map(memory).set(environmentId, update(connection)); +}; + +/** The read's answer for the threads it was asked about; a thread it does not name was not spawned. */ +export const rememberSpawned = ( + memory: ConnectionMemory, + environmentId: EnvironmentId, + credential: string, + requested: ReadonlyArray, + spawnedByAgent: ReadonlyArray, +): ConnectionMemory => + updateConnection(memory, environmentId, credential, (connection) => { + const named = new Set(spawnedByAgent); + const spawned = new Map(connection.spawned); + for (const threadId of requested) spawned.set(threadId, named.has(threadId)); + return { ...connection, spawned }; + }); + +/** Names read for some participants join the known ones; one the server no longer names is dropped. */ +export const rememberIdentities = ( + memory: ConnectionMemory, + environmentId: EnvironmentId, + credential: string, + requested: ReadonlyArray, + identities: ParticipantIdentities, +): ConnectionMemory => + updateConnection(memory, environmentId, credential, (connection) => { + const labels = new Map(connection.names.labels); + const threads = new Map(connection.names.threads); + for (const participantId of requested) { + labels.delete(participantId); + threads.delete(participantId); + } + for (const [participantId, label] of identities.labels) labels.set(participantId, label); + for (const [participantId, thread] of identities.threads) threads.set(participantId, thread); + return { ...connection, names: { labels, threads } }; + }); + +/** Only the threads still listed keep their answer, so the saved file follows the lists. */ +export const retainSpawned = ( + memory: ConnectionMemory, + keep: ReadonlyMap>, +): ConnectionMemory => + new Map( + [...memory].map(([environmentId, connection]) => { + const listed = keep.get(environmentId); + if (listed === undefined) return [environmentId, connection]; + const spawned = new Map([...connection.spawned].filter(([threadId]) => listed.has(threadId))); + return [environmentId, { ...connection, spawned }]; + }), + ); + +const StoredMemory = Schema.fromJsonString( + Schema.Struct({ + version: Schema.Literal(1), + environments: Schema.Array( + Schema.Tuple([ + EnvironmentId, + Schema.Struct({ + credential: Schema.String, + spawned: Schema.Array(ThreadId), + notSpawned: Schema.Array(ThreadId), + labels: Schema.Array(Schema.Tuple([Schema.String, Schema.String])), + threads: Schema.Array(Schema.Tuple([Schema.String, EnvironmentId, ThreadId])), + }), + ]), + ), + }), +); +const encodeStored = Schema.encodeSync(StoredMemory); +const decodeStored = Schema.decodeUnknownOption(StoredMemory); + +export const encodeMemory = (memory: ConnectionMemory): string => + encodeStored({ + version: 1, + environments: [...memory].map(([environmentId, connection]) => [ + environmentId, + { + credential: connection.credential, + spawned: [...connection.spawned].flatMap(([id, spawned]) => (spawned ? [id] : [])), + notSpawned: [...connection.spawned].flatMap(([id, spawned]) => (spawned ? [] : [id])), + labels: [...connection.names.labels], + threads: [...connection.names.threads].map(([participantId, ref]) => [ + participantId, + ref.environmentId, + ref.threadId, + ]), + }, + ]), + }); + +/** A file this version cannot read is an empty memory: it is only a head start. */ +export const decodeMemory = (raw: string | null): ConnectionMemory => { + const stored = raw === null ? Option.none() : decodeStored(raw); + if (Option.isNone(stored)) return new Map(); + return new Map( + stored.value.environments.map(([environmentId, connection]) => [ + environmentId, + { + credential: connection.credential, + spawned: new Map([ + ...connection.spawned.map((id) => [id, true] as const), + ...connection.notSpawned.map((id) => [id, false] as const), + ]), + names: { + labels: new Map(connection.labels), + threads: new Map( + connection.threads.map(([participantId, home, threadId]) => [ + participantId, + { environmentId: home, threadId } satisfies ScopedThreadRef, + ]), + ), + }, + }, + ]), + ); +}; + +export interface ListedThread { + readonly environmentId: EnvironmentId; + readonly id: ThreadId; + readonly archivedAt: string | null; + readonly pinnedAt?: string | null | undefined; +} + +/** + * The list's threads without the ones an agent spawned (register D22). On a server that has + * answered before, a thread it has not answered for yet waits while the answer is on its way, so + * it never shows and then leaves. Where no answer is coming (offline, a narrower person, a failed + * read) it shows, and so does every thread of a server never heard from, rather than an empty list. + */ +export function crewListedThreads( + threads: ReadonlyArray, + memory: ConnectionMemory, + answerExpected: ReadonlySet, +): ReadonlyArray { + const listed = threads.filter((thread) => { + if (thread.archivedAt !== null || thread.pinnedAt != null) return true; + const answers = memory.get(thread.environmentId)?.spawned; + const spawned = answers?.get(thread.id); + if (spawned === undefined) + return !( + answerExpected.has(thread.environmentId) && + answers !== undefined && + answers.size > 0 + ); + return isSidebarMember(thread, spawned); + }); + // The same array when nothing was dropped, so the list's own memos keep their values. + return listed.length === threads.length ? threads : listed; +} + +/** + * Whether a query has settled again since `baseline`, its value when the credential changed: a + * later settled result came over the new connection, even when it reuses the old value. + */ +export const answeredSince = ( + baseline: unknown, + result: AsyncResult.AsyncResult, +) => result !== baseline && result._tag !== "Initial" && !result.waiting; diff --git a/apps/mobile/src/j5/connection/memory.ts b/apps/mobile/src/j5/connection/memory.ts new file mode 100644 index 0000000000000..6fd8a9acb7d71 --- /dev/null +++ b/apps/mobile/src/j5/connection/memory.ts @@ -0,0 +1,223 @@ +import { participantIdentitiesFromResponse } from "@t3tools/client-runtime/j5/participant-identity"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { File, Paths } from "expo-file-system"; +import * as Option from "effect/Option"; +import { AsyncResult, Atom } from "effect/reactivity"; + +import { environmentCatalog } from "../../connection/catalog"; +import { writeFileAtomically } from "../../lib/atomic-file"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { environmentSession } from "../../state/session"; +import { j5Sharing } from "../sharing/guestAccess"; +import { j5Environment } from "../state"; +import { + answeredSince, + credentialKey, + decodeMemory, + encodeMemory, + observeCredential, + rememberIdentities, + rememberSpawned, + retainSpawned, + type ConnectionMemory, +} from "./memory.logic"; + +export interface MemorySnapshot { + readonly memory: ConnectionMemory; + /** Participants each server has answered for since its credential was last seen this launch. */ + readonly heard: ReadonlyMap>; + /** Servers whose last spawned-children read failed: they answer nothing until it succeeds. */ + readonly failedReads: ReadonlySet; +} + +const file = () => new File(Paths.cache, "j5-connection-memory.json"); + +// Read before the first list paints, so a cold start already knows what it learned last time. +const loadSaved = (): ConnectionMemory => { + try { + const saved = file(); + return decodeMemory(saved.exists ? saved.textSync() : null); + } catch { + return decodeMemory(null); + } +}; + +let snapshot: MemorySnapshot = { memory: loadSaved(), heard: new Map(), failedReads: new Set() }; +const listeners = new Set<() => void>(); +/** The credential each server's connection uses this launch. */ +const credentials = new Map(); +/** The threads each server's lists asked about this launch; the saved file keeps only those. */ +const asked = new Map>(); +const namesInFlight = new Map>(); + +let saveTimer: ReturnType | null = null; +let writing: Promise = Promise.resolve(); +const scheduleSave = () => { + if (saveTimer !== null) return; + saveTimer = setTimeout(() => { + saveTimer = null; + const contents = encodeMemory(retainSpawned(snapshot.memory, asked)); + writing = writing.then(() => writeFileAtomically(file(), contents)).catch(() => undefined); + }, 500); +}; + +const publish = (next: Partial) => { + snapshot = { ...snapshot, ...next }; + if (next.memory !== undefined) scheduleSave(); + listeners.forEach((listener) => listener()); +}; + +const without = (map: ReadonlyMap, key: K) => { + const next = new Map(map); + next.delete(key); + return next; +}; + +const credentialKeysAtom = Atom.make((get) => { + const keys = new Map(); + for (const id of get(environmentCatalog.catalogValueAtom).entries.keys()) { + const prepared = Option.getOrNull(get(environmentSession.preparedConnectionValueAtom(id))); + if (prepared !== null) keys.set(id, credentialKey(prepared)); + } + return keys; +}).pipe(Atom.withLabel("mobile-j5:credential-keys")); + +/** + * Each server's connection-access answer when its credential last changed this launch. Lineage + * waits for a newer answer, so a narrower person never sees the last person's parent. + */ +const accessBaselinesAtom = Atom.make>(new Map()).pipe( + Atom.keepAlive, + Atom.withLabel("mobile-j5:access-baselines"), +); + +const accessQuery = (environmentId: EnvironmentId) => + j5Sharing.connectionAccessQuery({ environmentId, input: {} }); + +// A missing key is a connection between attempts, which keeps its credential. +appAtomRegistry.subscribe( + credentialKeysAtom, + (keys) => { + let memory = snapshot.memory; + let { heard, failedReads } = snapshot; + const changed: Array = []; + for (const [environmentId, key] of keys) { + const previous = credentials.get(environmentId); + if (previous === key) continue; + credentials.set(environmentId, key); + memory = observeCredential(memory, environmentId, key); + if (previous === undefined) continue; + changed.push(environmentId); + heard = without(heard, environmentId); + failedReads = new Set([...failedReads].filter((id) => id !== environmentId)); + namesInFlight.delete(environmentId); + } + if (memory !== snapshot.memory) publish({ memory, heard, failedReads }); + if (changed.length === 0) return; + const baselines = new Map(appAtomRegistry.get(accessBaselinesAtom)); + for (const environmentId of changed) + baselines.set(environmentId, appAtomRegistry.get(accessQuery(environmentId))); + appAtomRegistry.set(accessBaselinesAtom, baselines); + }, + { immediate: true }, +); + +/** + * Whether the server's answer about who this connection is came after its credential last + * changed; true when it has not changed this launch. + */ +export const accessConfirmedAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + const baseline = get(accessBaselinesAtom).get(environmentId); + return baseline === undefined || answeredSince(baseline, get(accessQuery(environmentId))); + }).pipe(Atom.withLabel(`mobile-j5:access-confirmed:${environmentId}`)), +); + +/** + * Servers whose spawned-children answer is on its way: connected, or on a first attempt, to a + * person who reads the whole server. Elsewhere none is coming. + */ +export const answerExpectedAtom = Atom.make((get) => { + const expected = new Set(); + for (const id of get(environmentCatalog.catalogValueAtom).entries.keys()) { + const state = Option.getOrNull(AsyncResult.value(get(environmentCatalog.stateAtom(id)))); + if (state === null || get(j5Sharing.isNarrow(id))) continue; + if (state.phase === "connected" || (state.phase === "connecting" && state.lastFailure === null)) + expected.add(id); + } + return expected; +}).pipe(Atom.withLabel("mobile-j5:answer-expected")); + +export const connectionMemory = { + subscribe: (listener: () => void) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + getSnapshot: () => snapshot, + credentialOf: (environmentId: EnvironmentId) => credentials.get(environmentId) ?? null, + + rememberSpawned: ( + environmentId: EnvironmentId, + credential: string, + requested: ReadonlyArray, + spawnedByAgent: ReadonlyArray, + ) => { + const listed = asked.get(environmentId) ?? new Set(); + for (const threadId of requested) listed.add(threadId); + asked.set(environmentId, listed); + publish({ + memory: rememberSpawned( + snapshot.memory, + environmentId, + credential, + requested, + spawnedByAgent, + ), + failedReads: new Set([...snapshot.failedReads].filter((id) => id !== environmentId)), + }); + }, + + spawnedReadFailed: (environmentId: EnvironmentId) => { + if (!snapshot.failedReads.has(environmentId)) + publish({ failedReads: new Set(snapshot.failedReads).add(environmentId) }); + }, + + /** Asks for the participants this credential has not heard named this launch. */ + readNames: async (environmentId: EnvironmentId, participantIds: ReadonlyArray) => { + const credential = credentials.get(environmentId); + if (credential === undefined) return; + const heard = snapshot.heard.get(environmentId); + const inFlight = namesInFlight.get(environmentId) ?? new Set(); + const missing = [...new Set(participantIds)].filter( + (id) => !heard?.has(id) && !inFlight.has(id), + ); + if (missing.length === 0) return; + namesInFlight.set(environmentId, inFlight); + for (const id of missing) inFlight.add(id); + try { + const result = await j5Environment.readParticipantIdentities.run(appAtomRegistry, { + environmentId, + input: { participantIds: missing }, + }); + // A failed read names nobody and is not heard, so the next connection asks again. + if (result._tag === "Failure" || credentials.get(environmentId) !== credential) return; + publish({ + memory: rememberIdentities( + snapshot.memory, + environmentId, + credential, + missing, + participantIdentitiesFromResponse(environmentId, result.value), + ), + heard: new Map(snapshot.heard).set( + environmentId, + new Set([...(snapshot.heard.get(environmentId) ?? []), ...missing]), + ), + }); + } finally { + for (const id of missing) inFlight.delete(id); + } + }, +}; diff --git a/apps/mobile/src/j5/crew/spawnedChildren.ts b/apps/mobile/src/j5/crew/spawnedChildren.ts index a00f75ed2f37a..0a315949a7a48 100644 --- a/apps/mobile/src/j5/crew/spawnedChildren.ts +++ b/apps/mobile/src/j5/crew/spawnedChildren.ts @@ -3,7 +3,6 @@ import type { PreparedConnection } from "@t3tools/client-runtime/connection"; import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; import { createScopedThreadReadStore } from "@t3tools/client-runtime/j5/scopedThreadReadStore"; import { - isSidebarMember, replaceSpawnedChildren, spawnedChildrenRows, type SpawnedChildrenRow, @@ -19,16 +18,29 @@ import { useEffect, useMemo, useSyncExternalStore } from "react"; import { environmentCatalog } from "../../connection/catalog"; import { appAtomRegistry } from "../../state/atom-registry"; import { environmentSession } from "../../state/session"; +import { answerExpectedAtom, connectionMemory } from "../connection/memory"; +import { crewListedThreads, type ListedThread } from "../connection/memory.logic"; import { j5Sharing } from "../sharing/guestAccess"; import { j5Environment } from "../state"; const store = createScopedThreadReadStore({ load: async (environmentId, threadIds) => { + const credential = connectionMemory.credentialOf(environmentId); const result = await j5Environment.listSpawnedChildren.run(appAtomRegistry, { environmentId, input: { threadIds }, }); - if (result._tag === "Failure") throw Cause.squash(result.cause); + if (result._tag === "Failure") { + connectionMemory.spawnedReadFailed(environmentId); + throw Cause.squash(result.cause); + } + if (credential !== null) + connectionMemory.rememberSpawned( + environmentId, + credential, + threadIds, + result.value.spawnedByAgent, + ); return spawnedChildrenRows(result.value); }, replace: replaceSpawnedChildren, @@ -83,18 +95,15 @@ const requestRows = (refs: ReadonlyArray, revisions: string) => /** * 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. + * spawner's Agents sheet unless pinned. Each answer is remembered for the connection, so the + * list's first paint already leaves them out. Also keeps the spawned-children read current. */ -export function useCrewListedThreads< - T extends { - readonly environmentId: EnvironmentId; - readonly id: ThreadId; - readonly archivedAt: string | null; - readonly pinnedAt?: string | null | undefined; - }, ->(threads: ReadonlyArray): ReadonlyArray { +export function useCrewListedThreads( + threads: ReadonlyArray, +): ReadonlyArray { const connections = useAtomValue(threadReadConnectionsAtom); const revisions = useAtomValue(placementRevisionsAtom); + const answerExpected = useAtomValue(answerExpectedAtom); // The list re-renders while turns stream, so the effect keys on the serialized row set. const key = JSON.stringify( threads.flatMap((thread) => @@ -109,18 +118,20 @@ export function useCrewListedThreads< ); requestRows(refs, revisions); }, [connections, key, revisions]); - const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot); - return useMemo(() => { - const listed = threads.filter((thread) => - isSidebarMember( - thread, - snapshot.get(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))) - ?.spawnedByAgent === true, + const { memory, failedReads } = useSyncExternalStore( + connectionMemory.subscribe, + connectionMemory.getSnapshot, + connectionMemory.getSnapshot, + ); + return useMemo( + () => + crewListedThreads( + threads, + memory, + new Set([...answerExpected].filter((id) => !failedReads.has(id))), ), - ); - // The same array when nothing was dropped, so the list's own memos keep their values. - return listed.length === threads.length ? threads : listed; - }, [threads, snapshot]); + [threads, memory, answerExpected, failedReads], + ); } const EMPTY: ReadonlyArray = []; diff --git a/apps/mobile/src/j5/inbox/InboxScreen.tsx b/apps/mobile/src/j5/inbox/InboxScreen.tsx index 5e87bbee244ce..c0df1b6ebf72b 100644 --- a/apps/mobile/src/j5/inbox/InboxScreen.tsx +++ b/apps/mobile/src/j5/inbox/InboxScreen.tsx @@ -61,9 +61,9 @@ import { worktreeCleanupSourcesAtom, } from "./inboxSources"; import { createPullRefresh } from "./inboxPullRefresh.logic"; -import { useScopedParticipantLabels } from "./senderLabels"; +import { useScopedParticipantLabels, type ScopedParticipantLabels } from "./senderLabels"; -type SenderLabels = ReadonlyMap>; +type SenderLabels = ScopedParticipantLabels; const NO_LABELS: ReadonlyMap = new Map(); @@ -73,11 +73,14 @@ const URGENCY = { fyi: { label: "FYI", className: "text-foreground-muted" }, } as const; +/** Null while the name is on its way, so the line does not swap a stand-in for it. */ const senderName = (item: PresentedHumanInboxItem, labels: SenderLabels) => - presentParticipantIdentity({ - participantId: item.senderId, - participantLabels: labels.get(item.environmentId) ?? NO_LABELS, - }).label; + labels.isPending(item.environmentId, item.senderId) + ? null + : presentParticipantIdentity({ + participantId: item.senderId, + participantLabels: labels.labels.get(item.environmentId) ?? NO_LABELS, + }).label; /** The reader's own name on an item's server, so "Priya answered" can read "You answered". */ function useOwnName(environmentId: EnvironmentId): string | null { diff --git a/apps/mobile/src/j5/inbox/senderLabels.ts b/apps/mobile/src/j5/inbox/senderLabels.ts index c3795e8c18d7b..e233f6815c6ea 100644 --- a/apps/mobile/src/j5/inbox/senderLabels.ts +++ b/apps/mobile/src/j5/inbox/senderLabels.ts @@ -1,9 +1,8 @@ -import { readParticipantIdentities } from "@t3tools/client-runtime/j5/archive-flow"; import type { EnvironmentId } from "@t3tools/contracts"; -import { useEffect, useState } from "react"; +import { useEffect, useMemo, useSyncExternalStore } from "react"; -import { appAtomRegistry } from "../../state/atom-registry"; -import { j5Environment } from "../state"; +import { pendingParticipants } from "../a2a/participantIdentities"; +import { connectionMemory } from "../connection/memory"; export interface ScopedParticipantRef { readonly environmentId: EnvironmentId; @@ -11,14 +10,20 @@ export interface ScopedParticipantRef { readonly connected: boolean; } +export interface ScopedParticipantLabels { + readonly labels: ReadonlyMap>; + /** Whether the sender's name is still on its way from its connected server. */ + readonly isPending: (environmentId: EnvironmentId, participantId: string) => boolean; +} + /** * Names for senders spread across servers, as web's merged inbox reads them: each connected - * server names its own senders once, so saved items shown while offline pick up names on - * reconnect. Earlier names stay shown while a changed set reloads. + * server names its own senders once a connection, and the names are kept per server and paired + * credential, so a revisit shows them on its first frame. */ export function useScopedParticipantLabels( refs: ReadonlyArray, -): ReadonlyMap> { +): ScopedParticipantLabels { const key = Array.from( new Set( refs @@ -28,36 +33,40 @@ export function useScopedParticipantLabels( ) .sort() .join("\n"); - const [labels, setLabels] = useState>>( - () => new Map(), + const snapshot = useSyncExternalStore( + connectionMemory.subscribe, + connectionMemory.getSnapshot, + connectionMemory.getSnapshot, ); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads names from each server for the senders on screen, and drops a stale answer when they change. - useEffect(() => { - const byEnvironment = new Map>(); + const byEnvironment = useMemo(() => { + const ids = new Map>(); for (const entry of key === "" ? [] : key.split("\n")) { const [environmentId, participantId] = JSON.parse(entry) as [EnvironmentId, string]; - byEnvironment.set(environmentId, [ - ...(byEnvironment.get(environmentId) ?? []), - participantId, - ]); + ids.set(environmentId, [...(ids.get(environmentId) ?? []), participantId]); } - let active = true; - void Promise.all( - Array.from(byEnvironment, async ([environmentId, ids]) => { - const identities = await readParticipantIdentities( - j5Environment, - appAtomRegistry, - environmentId, - ids, - ); - return [environmentId, identities.labels] as const; - }), - ).then((entries) => { - if (active) setLabels((current) => new Map([...current, ...entries])); - }); - return () => { - active = false; - }; + return ids; }, [key]); - return labels; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks each server for the senders on screen it has not named this connection. + useEffect(() => { + for (const [environmentId, ids] of byEnvironment) + void connectionMemory.readNames(environmentId, ids); + }, [byEnvironment]); + return useMemo( + () => ({ + labels: new Map( + [...snapshot.memory].map(([environmentId, connection]) => [ + environmentId, + connection.names.labels, + ]), + ), + isPending: (environmentId: EnvironmentId, participantId: string) => + pendingParticipants( + snapshot, + environmentId, + [participantId], + byEnvironment.has(environmentId), + ).size > 0, + }), + [snapshot, byEnvironment], + ); } diff --git a/apps/mobile/src/j5/sharing/sharedConversation.tsx b/apps/mobile/src/j5/sharing/sharedConversation.tsx index c8e833bf05b06..260897c46ef5f 100644 --- a/apps/mobile/src/j5/sharing/sharedConversation.tsx +++ b/apps/mobile/src/j5/sharing/sharedConversation.tsx @@ -13,6 +13,7 @@ import type { ThreadAuthors } from "@t3tools/contracts/j5"; import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { useEffect, useState } from "react"; +import { View } from "react-native"; import { AppText as Text } from "../../components/ui/AppText"; import type { ThreadFeedEntry } from "../../lib/threadActivity"; @@ -151,12 +152,22 @@ export function PromptAnsweredBy(props: { }) { const { answers } = useThreadAuthorIndex(props.environmentId, props.item.threadId); const by = isSettledPrompt(props.item) ? answers.get(props.item.requestId) : undefined; - if (by === undefined && !props.alone && !props.answered) return null; + if (by === undefined && !props.alone && !props.answered) + // The label fits its text on a prompt's row, so the row's end stays where it was. + return answeredByFollowsLabel(props.item, false) ? : null; // Lowercase in every state, as web's "· answered by Priya" is. const said = props.alone ? "answered" : "· answered"; return ( - + {by === undefined ? said : `${said} by ${by.you ? "you" : (by.name ?? "someone")}`} ); } + +/** A prompt's row whose label `PromptAnsweredBy` follows, right after the text (IN-29). */ +export const answeredByFollowsLabel = (item: unknown, answered: boolean) => + answered || isSettledPrompt(item); diff --git a/apps/mobile/src/j5/threads/J5OpenParentBar.tsx b/apps/mobile/src/j5/threads/J5OpenParentBar.tsx index 669c9963b37d1..25eefe0b16dd7 100644 --- a/apps/mobile/src/j5/threads/J5OpenParentBar.tsx +++ b/apps/mobile/src/j5/threads/J5OpenParentBar.tsx @@ -10,6 +10,7 @@ import { Button } from "../../components/ui/Button"; import { useOpenLinkedThread } from "../../features/threads/useOpenLinkedThread"; import { useEnvironmentServerConfig, useQuietThreadShell } from "../../state/entities"; import { useEnvironmentQuery } from "../../state/query"; +import { accessConfirmedAtom } from "../connection/memory"; import { j5Sharing } from "../sharing/guestAccess"; import { j5Environment } from "../state"; @@ -17,9 +18,11 @@ import { j5Environment } from "../state"; function useJ5ParentRow(environmentId: EnvironmentId, threadId: ThreadId): J5LineageRow | null { const supported = j5LedgerSupported(useEnvironmentServerConfig(environmentId)) !== false; // The roster is a server-wide read, refused to a person who reaches less (web's Lineage too). + // After a re-pair it waits for the server to say who the new person is. const narrow = useAtomValue(j5Sharing.isNarrow(environmentId)); + const confirmed = useAtomValue(accessConfirmedAtom(environmentId)); const fleet = useEnvironmentQuery( - supported && !narrow ? j5Environment.fleet({ environmentId, input: {} }) : null, + supported && !narrow && confirmed ? j5Environment.fleet({ environmentId, input: {} }) : null, ); return ( deriveJ5LineageRows(fleet.data?.projects ?? [], threadId).find( diff --git a/apps/mobile/src/j5/upstreamSeams.test.ts b/apps/mobile/src/j5/upstreamSeams.test.ts index 3e54bac9917f6..61c4ffbf00242 100644 --- a/apps/mobile/src/j5/upstreamSeams.test.ts +++ b/apps/mobile/src/j5/upstreamSeams.test.ts @@ -167,6 +167,7 @@ const SEAMS: ReadonlyArray = [ from: "../../j5/sharing/sharedConversation", reaches: [ " Date: Fri, 20 Nov 2026 00:33:11 -0500 Subject: [PATCH 02/11] fix(mobile): hold every unseen thread, re-read names each visit, scope sender links Review round 1 on #1111: - Chats holds every thread no answer covers while one is on its way, with nothing saved too (Captain's ruling); Home and the tablet sidebar show upstream's loading state while the whole list waits. - Names are read again as each screen mounts or reconnects, with only the in-flight read deduped; a read that settles, even failed, ends the blank state so the stand-in shows. - The sender line's thread title and link wait for the new person's access answer after a re-pair, as the Open parent bar does. - The saved file drops servers no longer saved; the Inbox re-renders only when names change. Co-Authored-By: Claude Opus 5.5 --- FORK.md | 4 +- apps/mobile/src/features/home/HomeScreen.tsx | 12 ++- .../threads/ThreadNavigationSidebar.tsx | 5 +- .../src/j5/a2a/participantIdentities.ts | 34 ++++----- apps/mobile/src/j5/a2a/timeline.tsx | 4 +- .../src/j5/a2a/timelinePresentation.test.ts | 1 + .../mobile/src/j5/a2a/timelinePresentation.ts | 2 + apps/mobile/src/j5/a2a/timelineState.ts | 3 + .../src/j5/connection/memory.logic.test.ts | 37 +++++++++- apps/mobile/src/j5/connection/memory.logic.ts | 66 ++++++++++++++--- apps/mobile/src/j5/connection/memory.ts | 73 ++++++++++++------- apps/mobile/src/j5/crew/spawnedChildren.ts | 53 ++++++++++---- apps/mobile/src/j5/inbox/senderLabels.ts | 44 +++++------ .../src/j5/sharing/sharedConversation.tsx | 2 +- apps/mobile/src/j5/upstreamSeams.test.ts | 19 +++++ 15 files changed, 256 insertions(+), 103 deletions(-) diff --git a/FORK.md b/FORK.md index 3f6c711613a42..52515ccbbd033 100644 --- a/FORK.md +++ b/FORK.md @@ -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. Between them, `J5OpenParentBar` (`apps/mobile/src/j5/threads/`) gives a Crew member or Peer Agent upstream's Open parent button, leading to its Captain or spawner, read from the Fleet roster by web's Lineage logic, now `packages/client-runtime/src/j5/lineage.ts` (`./j5/lineage`) ([#1062](https://github.com/Jacksondr5/j5code/issues/1062)). Opened, the dock grows with the question up to the room above the composer, less one row for the playbook bar and the measured height of the rows above the dock. That room is upstream's `pendingUserInputMaxHeight`, which its own pending-question card gets in the composer's place, less the composer's height above its inset, plus that inset while the keyboard covers it (upstream's room takes it off even then), so `ThreadDetailScreen.tsx` passes `J5ComposerControls` `maxHeight`, `composerHeight` and `composerBottomInset` ([#1025](https://github.com/Jacksondr5/j5code/issues/1025)). As in the mobile Inbox, its answer carries photos and files ([#1041](https://github.com/Jacksondr5/j5code/issues/1041)), and an Owner sees the ask's Owner action ([#1040](https://github.com/Jacksondr5/j5code/issues/1040)). 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`, `./j5/crew-memberships` and `./j5/lineage` exports this case appends to upstream-owned `packages/client-runtime/package.json`. -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. Each answer is remembered per server and paired credential (`apps/mobile/src/j5/connection/memory.ts`, saved in the app's cache), so a cold start's first paint already leaves them out, and a thread no answer covers yet waits while one is on its way; 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. +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. Each answer is remembered per server and paired credential (`apps/mobile/src/j5/connection/memory.ts`, saved in the app's cache), so a cold start's first paint already leaves them out, and a thread no answer covers yet waits while one is on its way. When every thread waits (a first launch or a new pairing), `apps/mobile/src/features/home/HomeScreen.tsx` shows upstream's "Connecting to environment" state through `useCrewListWaiting` and `connectingWorkspace`, and `apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx` its "Loading threads…", instead of "No threads yet"; `useThreadListV2`'s 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: `packages/client-runtime/src/j5/lineage.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. @@ -995,6 +995,8 @@ explicitly marked. | `apps/mobile/src/features/threads/work-log-layout.tsx` | N | 99 | | `apps/mobile/src/features/threads/ThreadAgentsSheet.tsx` | N | 115 | | `apps/mobile/src/features/threads/useThreadListV2.ts` | N | 115 | +| `apps/mobile/src/features/home/HomeScreen.tsx` | N | 115 | +| `apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx` | 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 | | `apps/mobile/src/state/threadOutboxDelivery.ts` | A | Saved-agent mentions | diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 4609ecfb96c94..4a727ea12c3ad 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -51,6 +51,7 @@ import { useThreadSearch } from "../../state/queries"; import { requestThreadMessageJump } from "../threads/threadMessageJump"; import { useThreadListSearchMatches } from "../threads/useThreadListSearchMatches"; import { useThreadListV2 } from "../threads/useThreadListV2"; +import { connectingWorkspace, useCrewListWaiting } from "../../j5/crew/spawnedChildren"; import { useThreadListNow } from "../threads/use-thread-list-now"; import { useSearchScrollRestoration } from "../workspace/useSearchScrollRestoration"; import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts"; @@ -652,17 +653,20 @@ export function HomeScreen(props: HomeScreenProps) { workingShelfEnabled, }; + // J5 (case 115): threads waiting for their first spawned-children answer are still loading. + const j5ListWaiting = useCrewListWaiting(props.threads); const hasAnyThreads = - props.threads.some((thread) => thread.archivedAt === null) || - props.pendingTasks.length > 0 || - threadListV2Layout.settledCount > 0; + !j5ListWaiting && + (props.threads.some((thread) => thread.archivedAt === null) || + props.pendingTasks.length > 0 || + threadListV2Layout.settledCount > 0); const selectedEnvironmentLabel = props.selectedEnvironmentId === null ? null : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ?? "this environment"); const emptyState = deriveEmptyState({ - catalogState: props.catalogState, + catalogState: j5ListWaiting ? connectingWorkspace(props.catalogState) : props.catalogState, projectCount: props.projects.length, }); diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 3bbc39d5b9a0e..c6f534902f8cb 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -46,6 +46,7 @@ import { useWorkspaceState } from "../../state/workspace"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands"; import { useThreadListV2 } from "./useThreadListV2"; +import { useCrewListWaiting } from "../../j5/crew/spawnedChildren"; import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts"; import { requestThreadMessageJump } from "./threadMessageJump"; import { useThreadListSearchMatches } from "./useThreadListSearchMatches"; @@ -680,6 +681,8 @@ function ThreadNavigationSidebarPane( filterMenu, onOpenSettings: props.onOpenSettings, }); + // J5 (case 115): threads waiting for their first spawned-children answer are still loading. + const j5ListWaiting = useCrewListWaiting(threads); const listEmpty = ( - {catalogState.isLoadingConnections + {catalogState.isLoadingConnections || j5ListWaiting ? "Loading threads…" : Platform.OS === "android" && !catalogState.hasConnections ? "No environments connected" diff --git a/apps/mobile/src/j5/a2a/participantIdentities.ts b/apps/mobile/src/j5/a2a/participantIdentities.ts index 99e450c8decdb..4bfe069ead595 100644 --- a/apps/mobile/src/j5/a2a/participantIdentities.ts +++ b/apps/mobile/src/j5/a2a/participantIdentities.ts @@ -3,7 +3,8 @@ import type { EnvironmentId } from "@t3tools/contracts"; import { useEffect, useMemo, useSyncExternalStore } from "react"; import { useWorkspaceEnvironments } from "../../state/workspace"; -import { connectionMemory, type MemorySnapshot } from "../connection/memory"; +import { connectionMemory } from "../connection/memory"; +import { pendingParticipants } from "../connection/memory.logic"; export const NO_IDENTITIES: ParticipantIdentities = { labels: new Map(), threads: new Map() }; const NO_ONE: ReadonlySet = new Set(); @@ -13,20 +14,6 @@ export interface ScreenIdentities extends ParticipantIdentities { readonly pending: ReadonlySet; } -/** Ids a connected server has not answered for yet and has no remembered name for. */ -export const pendingParticipants = ( - snapshot: MemorySnapshot, - environmentId: EnvironmentId, - participantIds: ReadonlyArray, - connected: boolean, -): ReadonlySet => { - if (!connected) return NO_ONE; - const heard = snapshot.heard.get(environmentId); - const labels = snapshot.memory.get(environmentId)?.names.labels; - const pending = participantIds.filter((id) => !heard?.has(id) && !labels?.has(id)); - return pending.length === 0 ? NO_ONE : new Set(pending); -}; - export const useConnectedEnvironmentIds = (): ReadonlySet => { const environments = useWorkspaceEnvironments(); const key = environments @@ -40,8 +27,8 @@ export const useConnectedEnvironmentIds = (): ReadonlySet => { /** * Names for the ids on screen, kept per server and paired credential, so a revisit or a new - * sender never drops the names already shown. Each id is asked once a connection; a read sent - * before the environment connects fails, so it waits for the connection. + * sender never drops the names already shown. They are read again as the screen mounts or + * reconnects; a read sent before the environment connects fails, so it waits for the connection. */ export function useParticipantIdentities( environmentId: EnvironmentId, @@ -49,20 +36,25 @@ export function useParticipantIdentities( ): ScreenIdentities { const idsKey = Array.from(new Set(participantIds)).sort().join("\0"); const connected = useConnectedEnvironmentIds().has(environmentId); - const snapshot = useSyncExternalStore( + const { + memory, + names: known, + settled, + } = useSyncExternalStore( connectionMemory.subscribe, connectionMemory.getSnapshot, connectionMemory.getSnapshot, ); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the server for names of the ids on screen it has not named this connection. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads the names of the ids on screen from the server, again on each connection. useEffect(() => { if (idsKey === "" || !connected) return; void connectionMemory.readNames(environmentId, idsKey.split("\0")); }, [connected, environmentId, idsKey]); - const names = snapshot.memory.get(environmentId)?.names ?? NO_IDENTITIES; + const names = known.get(environmentId) ?? NO_IDENTITIES; const pendingKey = [ ...pendingParticipants( - snapshot, + memory, + settled, environmentId, idsKey === "" ? [] : idsKey.split("\0"), connected, diff --git a/apps/mobile/src/j5/a2a/timeline.tsx b/apps/mobile/src/j5/a2a/timeline.tsx index fa671d97076c7..f4d391ddc0b45 100644 --- a/apps/mobile/src/j5/a2a/timeline.tsx +++ b/apps/mobile/src/j5/a2a/timeline.tsx @@ -313,7 +313,9 @@ function useSenderThread( }); // A peer's thread opens only from a client connected to that peer, and only if the person can // see it there; the client's own thread list answers both. - const shell = useQuietThreadShell(presentation.j5?.group === "participant" ? ref : null); + const shell = useQuietThreadShell( + presentation.j5?.group === "participant" && timeline.accessConfirmed ? ref : null, + ); return { ref: shell === null ? null : ref, title: shell?.title }; } diff --git a/apps/mobile/src/j5/a2a/timelinePresentation.test.ts b/apps/mobile/src/j5/a2a/timelinePresentation.test.ts index 312841918a972..8b3d1de8cc53c 100644 --- a/apps/mobile/src/j5/a2a/timelinePresentation.test.ts +++ b/apps/mobile/src/j5/a2a/timelinePresentation.test.ts @@ -22,6 +22,7 @@ const timeline = (viewerParticipantId: string | null): J5Timeline => ({ labels: new Map(), threads: new Map(), pending: new Set(), + accessConfirmed: true, sharedAuthors: new Map(), }); diff --git a/apps/mobile/src/j5/a2a/timelinePresentation.ts b/apps/mobile/src/j5/a2a/timelinePresentation.ts index 9af497c610e53..43fbb748c0615 100644 --- a/apps/mobile/src/j5/a2a/timelinePresentation.ts +++ b/apps/mobile/src/j5/a2a/timelinePresentation.ts @@ -25,6 +25,8 @@ import type { MessageAuthor } from "@t3tools/contracts/j5"; export interface J5Timeline extends ParticipantIdentities { /** Senders whose name is still on its way. */ readonly pending: ReadonlySet; + /** False after a re-pair until the server says who the new person is: no sender threads yet. */ + readonly accessConfirmed: boolean; readonly environmentId: EnvironmentId; readonly viewerParticipantId: string | null; readonly sharedAuthors: ReadonlyMap; diff --git a/apps/mobile/src/j5/a2a/timelineState.ts b/apps/mobile/src/j5/a2a/timelineState.ts index fadaec4f42a85..f635be88ac10d 100644 --- a/apps/mobile/src/j5/a2a/timelineState.ts +++ b/apps/mobile/src/j5/a2a/timelineState.ts @@ -5,6 +5,7 @@ import { } from "@t3tools/client-runtime/j5/user-message"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { accessConfirmedAtom } from "../connection/memory"; import { j5Sharing } from "../sharing/guestAccess"; import { useThreadAuthorIndex } from "../sharing/sharedConversation"; import { useParticipantIdentities } from "./participantIdentities"; @@ -17,6 +18,7 @@ export function useJ5Timeline( messages: ReadonlyArray, ): J5Timeline { const access = useAtomValue(j5Sharing.connectionAccess(environmentId)); + const accessConfirmed = useAtomValue(accessConfirmedAtom(environmentId)); const { authors } = useThreadAuthorIndex(environmentId, threadId); const identities = useParticipantIdentities( environmentId, @@ -24,6 +26,7 @@ export function useJ5Timeline( ); return { ...identities, + accessConfirmed, environmentId, viewerParticipantId: access?.kind === "person" ? access.personId : null, sharedAuthors: authors, diff --git a/apps/mobile/src/j5/connection/memory.logic.test.ts b/apps/mobile/src/j5/connection/memory.logic.test.ts index e0bc271707582..b4dae7d88add1 100644 --- a/apps/mobile/src/j5/connection/memory.logic.test.ts +++ b/apps/mobile/src/j5/connection/memory.logic.test.ts @@ -6,11 +6,14 @@ import { answeredSince, credentialKey, crewListedThreads, + crewListWaiting, decodeMemory, encodeMemory, observeCredential, + pendingParticipants, rememberIdentities, rememberSpawned, + settleNames, type ConnectionMemory, } from "./memory.logic"; @@ -57,8 +60,18 @@ describe("crewListedThreads", () => { expect(titles(crewListedThreads(threads, memory, answering))).toEqual([id("captain")]); // Offline, refused or failed: no answer is coming, so the thread shows. expect(crewListedThreads(threads, memory, nobodyAnswering)).toBe(threads); - // A server never heard from (a first launch, a new pairing) lists everything, not nothing. - expect(crewListedThreads(threads, new Map(), answering)).toBe(threads); + // A first launch or new pairing has nothing saved: every row waits for the first answer. + expect(crewListedThreads(threads, new Map(), answering)).toEqual([]); + }); + + it("calls a first launch's list loading until the first answer, and empty only when it is", () => { + const threads = [row("captain"), row("seat")]; + + expect(crewListWaiting(threads, new Map(), answering)).toBe(true); + expect(crewListWaiting(threads, new Map(), nobodyAnswering)).toBe(false); + // Every thread was spawned: the list is truly empty, not loading. + expect(crewListWaiting(threads, heard(["captain", "seat"], []), answering)).toBe(false); + expect(crewListWaiting(threads, heard([], ["captain"]), answering)).toBe(false); }); it("keeps the Captain listed through a spawn, and the new agent never shows", () => { @@ -154,6 +167,26 @@ describe("participant names", () => { }); }); +describe("pendingParticipants", () => { + const memory = rememberIdentities( + observeCredential(new Map(), server, owner), + server, + owner, + ["agent:a"], + { labels: new Map([["agent:a", "Sender A"]]), threads: new Map() }, + ); + + it("says a new sender's name is on its way until a read settles, even a failed one", () => { + const ids = ["agent:a", "agent:b"]; + + expect([...pendingParticipants(memory, new Map(), server, ids, true)]).toEqual(["agent:b"]); + const failed = settleNames(new Map(), server, ["agent:b"]); + expect(pendingParticipants(memory, failed, server, ids, true).size).toBe(0); + // Offline, no read is coming: the stand-in shows. + expect(pendingParticipants(memory, new Map(), server, ids, false).size).toBe(0); + }); +}); + describe("credentialKey", () => { it("tells two pairings apart without keeping the token", () => { const prepared = (token: string) => ({ diff --git a/apps/mobile/src/j5/connection/memory.logic.ts b/apps/mobile/src/j5/connection/memory.logic.ts index 43a07788a440b..f659d6b183cd9 100644 --- a/apps/mobile/src/j5/connection/memory.logic.ts +++ b/apps/mobile/src/j5/connection/memory.logic.ts @@ -192,10 +192,9 @@ export interface ListedThread { } /** - * The list's threads without the ones an agent spawned (register D22). On a server that has - * answered before, a thread it has not answered for yet waits while the answer is on its way, so - * it never shows and then leaves. Where no answer is coming (offline, a narrower person, a failed - * read) it shows, and so does every thread of a server never heard from, rather than an empty list. + * The list's threads without the ones an agent spawned (register D22). A thread its server has + * not answered for yet waits while the answer is on its way, so it never shows and then leaves. + * Where no answer is coming (offline, a narrower person, a failed read) it shows. */ export function crewListedThreads( threads: ReadonlyArray, @@ -204,14 +203,8 @@ export function crewListedThreads( ): ReadonlyArray { const listed = threads.filter((thread) => { if (thread.archivedAt !== null || thread.pinnedAt != null) return true; - const answers = memory.get(thread.environmentId)?.spawned; - const spawned = answers?.get(thread.id); - if (spawned === undefined) - return !( - answerExpected.has(thread.environmentId) && - answers !== undefined && - answers.size > 0 - ); + const spawned = memory.get(thread.environmentId)?.spawned.get(thread.id); + if (spawned === undefined) return !answerExpected.has(thread.environmentId); return isSidebarMember(thread, spawned); }); // The same array when nothing was dropped, so the list's own memos keep their values. @@ -226,3 +219,52 @@ export const answeredSince = ( baseline: unknown, result: AsyncResult.AsyncResult, ) => result !== baseline && result._tag !== "Initial" && !result.waiting; + +/** The participants a name read has settled for, per server, under its current credential. */ +export type SettledNames = ReadonlyMap>; + +export const settleNames = ( + settled: SettledNames, + environmentId: EnvironmentId, + participantIds: ReadonlyArray, +): SettledNames => + new Map(settled).set( + environmentId, + new Set([...(settled.get(environmentId) ?? []), ...participantIds]), + ); + +const NO_ONE: ReadonlySet = new Set(); + +/** + * Ids whose name is on its way: their connected server has no remembered name for them and no + * read has settled. A screen says nothing for them rather than a stand-in it would replace. + */ +export const pendingParticipants = ( + memory: ConnectionMemory, + settled: SettledNames, + environmentId: EnvironmentId, + participantIds: ReadonlyArray, + connected: boolean, +): ReadonlySet => { + if (!connected) return NO_ONE; + const done = settled.get(environmentId); + const labels = memory.get(environmentId)?.names.labels; + const pending = participantIds.filter((id) => !done?.has(id) && !labels?.has(id)); + return pending.length === 0 ? NO_ONE : new Set(pending); +}; + +/** Whether the list is empty only because every live thread waits for its first answer. */ +export function crewListWaiting( + threads: ReadonlyArray, + memory: ConnectionMemory, + answerExpected: ReadonlySet, +): boolean { + const live = threads.filter((thread) => thread.archivedAt === null); + if (live.length === 0) return false; + if (crewListedThreads(live, memory, answerExpected).length > 0) return false; + return live.some( + (thread) => + answerExpected.has(thread.environmentId) && + memory.get(thread.environmentId)?.spawned.get(thread.id) === undefined, + ); +} diff --git a/apps/mobile/src/j5/connection/memory.ts b/apps/mobile/src/j5/connection/memory.ts index 6fd8a9acb7d71..db7f6ca6ceab8 100644 --- a/apps/mobile/src/j5/connection/memory.ts +++ b/apps/mobile/src/j5/connection/memory.ts @@ -1,4 +1,7 @@ -import { participantIdentitiesFromResponse } from "@t3tools/client-runtime/j5/participant-identity"; +import { + participantIdentitiesFromResponse, + type ParticipantIdentities, +} from "@t3tools/client-runtime/j5/participant-identity"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { File, Paths } from "expo-file-system"; import * as Option from "effect/Option"; @@ -19,13 +22,16 @@ import { rememberIdentities, rememberSpawned, retainSpawned, + settleNames, type ConnectionMemory, + type SettledNames, } from "./memory.logic"; export interface MemorySnapshot { readonly memory: ConnectionMemory; - /** Participants each server has answered for since its credential was last seen this launch. */ - readonly heard: ReadonlyMap>; + /** Each server's names; a new map only when some server's names change. */ + readonly names: ReadonlyMap; + readonly settled: SettledNames; /** Servers whose last spawned-children read failed: they answer nothing until it succeeds. */ readonly failedReads: ReadonlySet; } @@ -42,7 +48,16 @@ const loadSaved = (): ConnectionMemory => { } }; -let snapshot: MemorySnapshot = { memory: loadSaved(), heard: new Map(), failedReads: new Set() }; +const namesOf = (memory: ConnectionMemory) => + new Map([...memory].map(([environmentId, connection]) => [environmentId, connection.names])); + +const loaded = loadSaved(); +let snapshot: MemorySnapshot = { + memory: loaded, + names: namesOf(loaded), + settled: new Map(), + failedReads: new Set(), +}; const listeners = new Set<() => void>(); /** The credential each server's connection uses this launch. */ const credentials = new Map(); @@ -56,13 +71,20 @@ const scheduleSave = () => { if (saveTimer !== null) return; saveTimer = setTimeout(() => { saveTimer = null; - const contents = encodeMemory(retainSpawned(snapshot.memory, asked)); + // Saves follow a credential seen this launch, so the catalog has loaded: a removed server goes. + const saved = new Set(appAtomRegistry.get(environmentCatalog.catalogValueAtom).entries.keys()); + const memory = new Map([...snapshot.memory].filter(([id]) => saved.has(id))); + const contents = encodeMemory(retainSpawned(memory, asked)); writing = writing.then(() => writeFileAtomically(file(), contents)).catch(() => undefined); }, 500); }; -const publish = (next: Partial) => { - snapshot = { ...snapshot, ...next }; +const publish = (next: Partial>) => { + const names = next.memory === undefined ? snapshot.names : namesOf(next.memory); + const sameNames = + names.size === snapshot.names.size && + [...names].every(([environmentId, known]) => snapshot.names.get(environmentId) === known); + snapshot = { ...snapshot, ...next, names: sameNames ? snapshot.names : names }; if (next.memory !== undefined) scheduleSave(); listeners.forEach((listener) => listener()); }; @@ -99,7 +121,7 @@ appAtomRegistry.subscribe( credentialKeysAtom, (keys) => { let memory = snapshot.memory; - let { heard, failedReads } = snapshot; + let { settled, failedReads } = snapshot; const changed: Array = []; for (const [environmentId, key] of keys) { const previous = credentials.get(environmentId); @@ -108,11 +130,11 @@ appAtomRegistry.subscribe( memory = observeCredential(memory, environmentId, key); if (previous === undefined) continue; changed.push(environmentId); - heard = without(heard, environmentId); + settled = without(settled, environmentId); failedReads = new Set([...failedReads].filter((id) => id !== environmentId)); namesInFlight.delete(environmentId); } - if (memory !== snapshot.memory) publish({ memory, heard, failedReads }); + if (memory !== snapshot.memory) publish({ memory, settled, failedReads }); if (changed.length === 0) return; const baselines = new Map(appAtomRegistry.get(accessBaselinesAtom)); for (const environmentId of changed) @@ -184,40 +206,39 @@ export const connectionMemory = { publish({ failedReads: new Set(snapshot.failedReads).add(environmentId) }); }, - /** Asks for the participants this credential has not heard named this launch. */ + /** + * Reads the names of the ids on screen again, as each screen mounts or reconnects: a title can + * change after a spawn. The remembered names stay shown meanwhile. + */ readNames: async (environmentId: EnvironmentId, participantIds: ReadonlyArray) => { const credential = credentials.get(environmentId); if (credential === undefined) return; - const heard = snapshot.heard.get(environmentId); const inFlight = namesInFlight.get(environmentId) ?? new Set(); - const missing = [...new Set(participantIds)].filter( - (id) => !heard?.has(id) && !inFlight.has(id), - ); - if (missing.length === 0) return; + const ids = [...new Set(participantIds)].filter((id) => !inFlight.has(id)); + if (ids.length === 0) return; namesInFlight.set(environmentId, inFlight); - for (const id of missing) inFlight.add(id); + for (const id of ids) inFlight.add(id); try { const result = await j5Environment.readParticipantIdentities.run(appAtomRegistry, { environmentId, - input: { participantIds: missing }, + input: { participantIds: ids }, }); - // A failed read names nobody and is not heard, so the next connection asks again. - if (result._tag === "Failure" || credentials.get(environmentId) !== credential) return; + if (credentials.get(environmentId) !== credential) return; + // A failed read still settles, so its senders fall back to a stand-in until the next one. + const settled = settleNames(snapshot.settled, environmentId, ids); + if (result._tag === "Failure") return publish({ settled }); publish({ memory: rememberIdentities( snapshot.memory, environmentId, credential, - missing, + ids, participantIdentitiesFromResponse(environmentId, result.value), ), - heard: new Map(snapshot.heard).set( - environmentId, - new Set([...(snapshot.heard.get(environmentId) ?? []), ...missing]), - ), + settled, }); } finally { - for (const id of missing) inFlight.delete(id); + for (const id of ids) inFlight.delete(id); } }, }; diff --git a/apps/mobile/src/j5/crew/spawnedChildren.ts b/apps/mobile/src/j5/crew/spawnedChildren.ts index 0a315949a7a48..46c021e0ca628 100644 --- a/apps/mobile/src/j5/crew/spawnedChildren.ts +++ b/apps/mobile/src/j5/crew/spawnedChildren.ts @@ -18,8 +18,9 @@ import { useEffect, useMemo, useSyncExternalStore } from "react"; import { environmentCatalog } from "../../connection/catalog"; import { appAtomRegistry } from "../../state/atom-registry"; import { environmentSession } from "../../state/session"; +import type { WorkspaceState } from "../../state/workspaceModel"; import { answerExpectedAtom, connectionMemory } from "../connection/memory"; -import { crewListedThreads, type ListedThread } from "../connection/memory.logic"; +import { crewListedThreads, crewListWaiting, type ListedThread } from "../connection/memory.logic"; import { j5Sharing } from "../sharing/guestAccess"; import { j5Environment } from "../state"; @@ -93,6 +94,21 @@ const requestRows = (refs: ReadonlyArray, revisions: string) => ); }; +/** The remembered answers, and the servers whose answer is on its way (a failed read is not). */ +const useAnswers = () => { + const expected = useAtomValue(answerExpectedAtom); + const { memory, failedReads } = useSyncExternalStore( + connectionMemory.subscribe, + connectionMemory.getSnapshot, + connectionMemory.getSnapshot, + ); + const answerExpected = useMemo( + () => new Set([...expected].filter((id) => !failedReads.has(id))), + [expected, failedReads], + ); + return { memory, answerExpected }; +}; + /** * The list's threads without the ones an agent spawned (register D22): those show in their * spawner's Agents sheet unless pinned. Each answer is remembered for the connection, so the @@ -103,7 +119,7 @@ export function useCrewListedThreads( ): ReadonlyArray { const connections = useAtomValue(threadReadConnectionsAtom); const revisions = useAtomValue(placementRevisionsAtom); - const answerExpected = useAtomValue(answerExpectedAtom); + const { memory, answerExpected } = useAnswers(); // The list re-renders while turns stream, so the effect keys on the serialized row set. const key = JSON.stringify( threads.flatMap((thread) => @@ -118,22 +134,33 @@ export function useCrewListedThreads( ); requestRows(refs, revisions); }, [connections, key, revisions]); - const { memory, failedReads } = useSyncExternalStore( - connectionMemory.subscribe, - connectionMemory.getSnapshot, - connectionMemory.getSnapshot, + return useMemo( + () => crewListedThreads(threads, memory, answerExpected), + [threads, memory, answerExpected], ); +} + +/** + * Whether the list is empty only because its threads wait for their first spawned-children + * answer (a first launch or new pairing), so it shows upstream's loading state, not "No threads". + */ +export function useCrewListWaiting(threads: ReadonlyArray): boolean { + const { memory, answerExpected } = useAnswers(); return useMemo( - () => - crewListedThreads( - threads, - memory, - new Set([...answerExpected].filter((id) => !failedReads.has(id))), - ), - [threads, memory, answerExpected, failedReads], + () => crewListWaiting(threads, memory, answerExpected), + [threads, memory, answerExpected], ); } +/** The workspace as upstream's "Connecting to environment" loading state reads it. */ +export const connectingWorkspace = (state: WorkspaceState): WorkspaceState => ({ + ...state, + connectionState: "connecting", + hasConnectingEnvironment: true, + hasLoadedShellSnapshot: false, + connectionError: null, +}); + const EMPTY: ReadonlyArray = []; /** diff --git a/apps/mobile/src/j5/inbox/senderLabels.ts b/apps/mobile/src/j5/inbox/senderLabels.ts index e233f6815c6ea..b6cd92d738191 100644 --- a/apps/mobile/src/j5/inbox/senderLabels.ts +++ b/apps/mobile/src/j5/inbox/senderLabels.ts @@ -1,8 +1,8 @@ import type { EnvironmentId } from "@t3tools/contracts"; import { useEffect, useMemo, useSyncExternalStore } from "react"; -import { pendingParticipants } from "../a2a/participantIdentities"; import { connectionMemory } from "../connection/memory"; +import { pendingParticipants } from "../connection/memory.logic"; export interface ScopedParticipantRef { readonly environmentId: EnvironmentId; @@ -18,8 +18,8 @@ export interface ScopedParticipantLabels { /** * Names for senders spread across servers, as web's merged inbox reads them: each connected - * server names its own senders once a connection, and the names are kept per server and paired - * credential, so a revisit shows them on its first frame. + * server names its own senders as the Inbox opens or reconnects, and the names are kept per + * server and paired credential, so a revisit shows them on its first frame. */ export function useScopedParticipantLabels( refs: ReadonlyArray, @@ -33,7 +33,7 @@ export function useScopedParticipantLabels( ) .sort() .join("\n"); - const snapshot = useSyncExternalStore( + const { memory, names, settled } = useSyncExternalStore( connectionMemory.subscribe, connectionMemory.getSnapshot, connectionMemory.getSnapshot, @@ -46,27 +46,29 @@ export function useScopedParticipantLabels( } return ids; }, [key]); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks each server for the senders on screen it has not named this connection. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads each server's names for the senders on screen, again as they connect. useEffect(() => { for (const [environmentId, ids] of byEnvironment) void connectionMemory.readNames(environmentId, ids); }, [byEnvironment]); - return useMemo( - () => ({ - labels: new Map( - [...snapshot.memory].map(([environmentId, connection]) => [ - environmentId, - connection.names.labels, - ]), + // Keyed on the names alone, so a classification answer does not re-render the cards. + const labels = useMemo( + () => new Map([...names].map(([environmentId, known]) => [environmentId, known.labels])), + [names], + ); + const pendingKey = [...byEnvironment] + .flatMap(([environmentId, ids]) => + [...pendingParticipants(memory, settled, environmentId, ids, true)].map((id) => + JSON.stringify([environmentId, id]), ), + ) + .join("\n"); + return useMemo(() => { + const pending = new Set(pendingKey === "" ? [] : pendingKey.split("\n")); + return { + labels, isPending: (environmentId: EnvironmentId, participantId: string) => - pendingParticipants( - snapshot, - environmentId, - [participantId], - byEnvironment.has(environmentId), - ).size > 0, - }), - [snapshot, byEnvironment], - ); + pending.has(JSON.stringify([environmentId, participantId])), + }; + }, [labels, pendingKey]); } diff --git a/apps/mobile/src/j5/sharing/sharedConversation.tsx b/apps/mobile/src/j5/sharing/sharedConversation.tsx index 260897c46ef5f..b9ad8a2c8ac9f 100644 --- a/apps/mobile/src/j5/sharing/sharedConversation.tsx +++ b/apps/mobile/src/j5/sharing/sharedConversation.tsx @@ -160,7 +160,7 @@ export function PromptAnsweredBy(props: { return ( {by === undefined ? said : `${said} by ${by.you ? "you" : (by.name ?? "someone")}`} diff --git a/apps/mobile/src/j5/upstreamSeams.test.ts b/apps/mobile/src/j5/upstreamSeams.test.ts index 61c4ffbf00242..3f1766c456d0a 100644 --- a/apps/mobile/src/j5/upstreamSeams.test.ts +++ b/apps/mobile/src/j5/upstreamSeams.test.ts @@ -206,6 +206,25 @@ const SEAMS: ReadonlyArray = [ from: "../../j5/crew/spawnedChildren", reaches: ["const threads = useCrewListedThreads(input.threads);"], }, + { + file: "features/home/HomeScreen.tsx", + record: "case 115: a list waiting for its first answer is loading", + from: "../../j5/crew/spawnedChildren", + reaches: [ + "const j5ListWaiting = useCrewListWaiting(props.threads);", + "!j5ListWaiting &&", + "j5ListWaiting ? connectingWorkspace(props.catalogState) : props.catalogState", + ], + }, + { + file: "features/threads/ThreadNavigationSidebar.tsx", + record: "case 115: a list waiting for its first answer is loading", + from: "../../j5/crew/spawnedChildren", + reaches: [ + "const j5ListWaiting = useCrewListWaiting(threads);", + "catalogState.isLoadingConnections || j5ListWaiting", + ], + }, { file: "features/settings/SettingsAgentsRouteScreen.tsx", record: "PR #75–#86 role library: Personas settings", From a128d5851f0bc0022e4f2a78bbd7b8a0701518c1 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Fri, 20 Nov 2026 00:39:15 -0500 Subject: [PATCH 03/11] fix(mobile): a narrower person's sender links come only from the server Review round 2 on #1111: - A narrower person's sender thread comes only from the identity read, not the letter's thread id looked up in a thread list that can still hold the last person's threads after a re-pair. - Only a successful access read confirms who the new person is. - A task being created still shows while the list waits for its first answer. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/features/home/HomeScreen.tsx | 7 +++-- apps/mobile/src/j5/a2a/timeline.tsx | 17 +++--------- .../src/j5/a2a/timelinePresentation.test.ts | 26 +++++++++++++++++- .../mobile/src/j5/a2a/timelinePresentation.ts | 27 +++++++++++++++++++ apps/mobile/src/j5/a2a/timelineState.ts | 2 ++ .../src/j5/connection/memory.logic.test.ts | 6 +++++ apps/mobile/src/j5/connection/memory.logic.ts | 7 ++--- apps/mobile/src/j5/upstreamSeams.test.ts | 2 +- 8 files changed, 72 insertions(+), 22 deletions(-) diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 4a727ea12c3ad..848458c49b8ff 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -656,10 +656,9 @@ export function HomeScreen(props: HomeScreenProps) { // J5 (case 115): threads waiting for their first spawned-children answer are still loading. const j5ListWaiting = useCrewListWaiting(props.threads); const hasAnyThreads = - !j5ListWaiting && - (props.threads.some((thread) => thread.archivedAt === null) || - props.pendingTasks.length > 0 || - threadListV2Layout.settledCount > 0); + (!j5ListWaiting && props.threads.some((thread) => thread.archivedAt === null)) || + props.pendingTasks.length > 0 || + threadListV2Layout.settledCount > 0; const selectedEnvironmentLabel = props.selectedEnvironmentId === null ? null diff --git a/apps/mobile/src/j5/a2a/timeline.tsx b/apps/mobile/src/j5/a2a/timeline.tsx index f4d391ddc0b45..6f8848fed33ef 100644 --- a/apps/mobile/src/j5/a2a/timeline.tsx +++ b/apps/mobile/src/j5/a2a/timeline.tsx @@ -1,7 +1,4 @@ -import { - j5MessageAuthorName, - j5SenderThreadRef, -} from "@t3tools/client-runtime/j5/participant-identity"; +import { j5MessageAuthorName } from "@t3tools/client-runtime/j5/participant-identity"; import { crewApprovalSummary, crewDeclinedSummary, @@ -26,6 +23,7 @@ import { useQuietThreadShell } from "../../state/entities"; import { PersonAvatar } from "../sharing/PersonAvatar"; import { SharedConversationNote } from "../sharing/SharedConversationNote"; import { + j5TimelineSenderRef, presentJ5TimelineNotice, type J5FeedMessagePresentation, type J5Timeline, @@ -305,17 +303,10 @@ function useSenderThread( presentation: J5FeedMessagePresentation, timeline: J5Timeline, ) { - const ref = j5SenderThreadRef({ - environmentId: timeline.environmentId, - presentation: presentation.j5, - messageSenderThreadId: message.senderThreadId, - participantThreads: timeline.threads, - }); + const ref = j5TimelineSenderRef(message, presentation.j5, timeline); // A peer's thread opens only from a client connected to that peer, and only if the person can // see it there; the client's own thread list answers both. - const shell = useQuietThreadShell( - presentation.j5?.group === "participant" && timeline.accessConfirmed ? ref : null, - ); + const shell = useQuietThreadShell(ref); return { ref: shell === null ? null : ref, title: shell?.title }; } diff --git a/apps/mobile/src/j5/a2a/timelinePresentation.test.ts b/apps/mobile/src/j5/a2a/timelinePresentation.test.ts index 8b3d1de8cc53c..cbc90d80bbe5b 100644 --- a/apps/mobile/src/j5/a2a/timelinePresentation.test.ts +++ b/apps/mobile/src/j5/a2a/timelinePresentation.test.ts @@ -1,9 +1,10 @@ import { J5_A2A_DELIVERY_MESSAGE_PREFIX } from "@t3tools/client-runtime/j5/user-message"; -import { EnvironmentId } from "@t3tools/contracts"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { j5FoldHeader, + j5TimelineSenderRef, presentJ5QueuedMessage, presentJ5TimelineNotice, resolveJ5FeedMessage, @@ -23,6 +24,7 @@ const timeline = (viewerParticipantId: string | null): J5Timeline => ({ threads: new Map(), pending: new Set(), accessConfirmed: true, + narrow: false, sharedAuthors: new Map(), }); @@ -282,3 +284,25 @@ describe("j5FoldHeader", () => { }); }); }); + +describe("j5TimelineSenderRef", () => { + const here = EnvironmentId.make("environment-here"); + const letter = { ...delivery("agent", askRaw), senderThreadId: "thread-captain" }; + const sender = (overrides: Partial) => + j5TimelineSenderRef(letter, resolveJ5FeedMessage(letter, timeline(null)).j5, { + ...timeline(null), + ...overrides, + }); + + it("gives a narrower person only the sender thread the server named for them", () => { + // After a re-pair the thread list can still hold the last person's Captain thread. + expect(sender({ narrow: true })).toBeNull(); + const named = { environmentId: here, threadId: ThreadId.make("thread-named") }; + expect(sender({ narrow: true, threads: new Map([["agent:captain", named]]) })).toEqual(named); + expect(sender({})).toEqual({ environmentId: here, threadId: "thread-captain" }); + }); + + it("names no sender thread until the server says who the new person is", () => { + expect(sender({ accessConfirmed: false })).toBeNull(); + }); +}); diff --git a/apps/mobile/src/j5/a2a/timelinePresentation.ts b/apps/mobile/src/j5/a2a/timelinePresentation.ts index 43fbb748c0615..4e44b87fabab5 100644 --- a/apps/mobile/src/j5/a2a/timelinePresentation.ts +++ b/apps/mobile/src/j5/a2a/timelinePresentation.ts @@ -4,6 +4,7 @@ import { type CrewNoticePresentation, } from "@t3tools/client-runtime/j5/crew-notices"; import { + j5SenderThreadRef, nameJ5NoticeParticipants, type ParticipantIdentities, } from "@t3tools/client-runtime/j5/participant-identity"; @@ -14,6 +15,7 @@ import { type J5NoticeKind, type J5PromptKind, type J5UserMessageInput, + type J5UserMessagePresentation, } from "@t3tools/client-runtime/j5/user-message"; import type { EnvironmentId } from "@t3tools/contracts"; import type { MessageAuthor } from "@t3tools/contracts/j5"; @@ -27,6 +29,8 @@ export interface J5Timeline extends ParticipantIdentities { readonly pending: ReadonlySet; /** False after a re-pair until the server says who the new person is: no sender threads yet. */ readonly accessConfirmed: boolean; + /** The person reaches less than the whole server. */ + readonly narrow: boolean; readonly environmentId: EnvironmentId; readonly viewerParticipantId: string | null; readonly sharedAuthors: ReadonlyMap; @@ -138,3 +142,26 @@ export function presentJ5TimelineNotice( detail: notice.detail === null ? null : named(notice.detail), }; } + +/** + * The thread a letter's sender works in, as far as this person may know it. A narrower person + * gets only what the server's identity read names for them: the letter's own thread id would be + * looked up in a thread list that can still hold the last person's threads after a re-pair. + */ +export function j5TimelineSenderRef( + message: J5UserMessageInput & { readonly senderThreadId?: string | undefined }, + presentation: J5UserMessagePresentation | null, + timeline: J5Timeline, +) { + if (presentation?.group !== "participant" || !timeline.accessConfirmed) return null; + if (timeline.narrow) + return presentation.senderId === null + ? null + : (timeline.threads.get(presentation.senderId) ?? null); + return j5SenderThreadRef({ + environmentId: timeline.environmentId, + presentation, + messageSenderThreadId: message.senderThreadId, + participantThreads: timeline.threads, + }); +} diff --git a/apps/mobile/src/j5/a2a/timelineState.ts b/apps/mobile/src/j5/a2a/timelineState.ts index f635be88ac10d..59836a5418107 100644 --- a/apps/mobile/src/j5/a2a/timelineState.ts +++ b/apps/mobile/src/j5/a2a/timelineState.ts @@ -19,6 +19,7 @@ export function useJ5Timeline( ): J5Timeline { const access = useAtomValue(j5Sharing.connectionAccess(environmentId)); const accessConfirmed = useAtomValue(accessConfirmedAtom(environmentId)); + const narrow = useAtomValue(j5Sharing.isNarrow(environmentId)); const { authors } = useThreadAuthorIndex(environmentId, threadId); const identities = useParticipantIdentities( environmentId, @@ -27,6 +28,7 @@ export function useJ5Timeline( return { ...identities, accessConfirmed, + narrow, environmentId, viewerParticipantId: access?.kind === "person" ? access.personId : null, sharedAuthors: authors, diff --git a/apps/mobile/src/j5/connection/memory.logic.test.ts b/apps/mobile/src/j5/connection/memory.logic.test.ts index b4dae7d88add1..1c9ca1c01f781 100644 --- a/apps/mobile/src/j5/connection/memory.logic.test.ts +++ b/apps/mobile/src/j5/connection/memory.logic.test.ts @@ -210,4 +210,10 @@ describe("answeredSince", () => { expect(answeredSince(baseline, AsyncResult.success(owner, { waiting: true }))).toBe(false); expect(answeredSince(baseline, AsyncResult.success(owner))).toBe(true); }); + + it("does not take a failed read as the answer", () => { + const baseline = AsyncResult.success({ kind: "person", wide: true }); + + expect(answeredSince(baseline, AsyncResult.fail(new Error("refused")))).toBe(false); + }); }); diff --git a/apps/mobile/src/j5/connection/memory.logic.ts b/apps/mobile/src/j5/connection/memory.logic.ts index f659d6b183cd9..5609709c111ba 100644 --- a/apps/mobile/src/j5/connection/memory.logic.ts +++ b/apps/mobile/src/j5/connection/memory.logic.ts @@ -212,13 +212,14 @@ export function crewListedThreads( } /** - * Whether a query has settled again since `baseline`, its value when the credential changed: a - * later settled result came over the new connection, even when it reuses the old value. + * Whether a query has answered again since `baseline`, its value when the credential changed: a + * later settled success came over the new connection, even when it reuses the old value. A + * failure says nothing about who the new person is. */ export const answeredSince = ( baseline: unknown, result: AsyncResult.AsyncResult, -) => result !== baseline && result._tag !== "Initial" && !result.waiting; +) => result !== baseline && result._tag === "Success" && !result.waiting; /** The participants a name read has settled for, per server, under its current credential. */ export type SettledNames = ReadonlyMap>; diff --git a/apps/mobile/src/j5/upstreamSeams.test.ts b/apps/mobile/src/j5/upstreamSeams.test.ts index 3f1766c456d0a..f7e51e5e62d2c 100644 --- a/apps/mobile/src/j5/upstreamSeams.test.ts +++ b/apps/mobile/src/j5/upstreamSeams.test.ts @@ -212,7 +212,7 @@ const SEAMS: ReadonlyArray = [ from: "../../j5/crew/spawnedChildren", reaches: [ "const j5ListWaiting = useCrewListWaiting(props.threads);", - "!j5ListWaiting &&", + "(!j5ListWaiting && props.threads.some(", "j5ListWaiting ? connectingWorkspace(props.catalogState) : props.catalogState", ], }, From 5abcee84bc18ceec98d8ecdc522794b120a5e7af Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Fri, 20 Nov 2026 02:23:29 -0500 Subject: [PATCH 04/11] fix(mobile): a re-pair's author lines wait for the name instead of saying "Agent" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Visual review on #1111: after a re-pair the names were dropped and the author lines read "Agent" for 1–2 s while the new connection came up, because a name counted as on its way only once the server was connected. It now counts as on its way through a first connection attempt that has not failed, the rule Chats uses, for every person. Co-Authored-By: Claude Opus 5.5 --- .../src/j5/a2a/participantIdentities.ts | 7 ++++-- .../src/j5/connection/memory.logic.test.ts | 13 ++++++++++ apps/mobile/src/j5/connection/memory.logic.ts | 24 +++++++++++++++---- apps/mobile/src/j5/connection/memory.ts | 17 ++++++++----- apps/mobile/src/j5/inbox/senderLabels.ts | 22 ++++++++++++----- 5 files changed, 64 insertions(+), 19 deletions(-) diff --git a/apps/mobile/src/j5/a2a/participantIdentities.ts b/apps/mobile/src/j5/a2a/participantIdentities.ts index 4bfe069ead595..14060a91f4aea 100644 --- a/apps/mobile/src/j5/a2a/participantIdentities.ts +++ b/apps/mobile/src/j5/a2a/participantIdentities.ts @@ -1,9 +1,10 @@ +import { useAtomValue } from "@effect/atom-react"; import type { ParticipantIdentities } from "@t3tools/client-runtime/j5/participant-identity"; import type { EnvironmentId } from "@t3tools/contracts"; import { useEffect, useMemo, useSyncExternalStore } from "react"; import { useWorkspaceEnvironments } from "../../state/workspace"; -import { connectionMemory } from "../connection/memory"; +import { connectionMemory, namesExpectedAtom } from "../connection/memory"; import { pendingParticipants } from "../connection/memory.logic"; export const NO_IDENTITIES: ParticipantIdentities = { labels: new Map(), threads: new Map() }; @@ -36,6 +37,8 @@ export function useParticipantIdentities( ): ScreenIdentities { const idsKey = Array.from(new Set(participantIds)).sort().join("\0"); const connected = useConnectedEnvironmentIds().has(environmentId); + // Through a re-pair's first connection too, so the line never swaps a stand-in for the name. + const expected = useAtomValue(namesExpectedAtom).has(environmentId); const { memory, names: known, @@ -57,7 +60,7 @@ export function useParticipantIdentities( settled, environmentId, idsKey === "" ? [] : idsKey.split("\0"), - connected, + expected, ), ].join("\0"); const pending = useMemo( diff --git a/apps/mobile/src/j5/connection/memory.logic.test.ts b/apps/mobile/src/j5/connection/memory.logic.test.ts index 1c9ca1c01f781..f34f4ed5d1ea1 100644 --- a/apps/mobile/src/j5/connection/memory.logic.test.ts +++ b/apps/mobile/src/j5/connection/memory.logic.test.ts @@ -2,8 +2,11 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { describe, expect, it } from "vite-plus/test"; +import { credentialMissingError } from "@t3tools/client-runtime/connection"; + import { answeredSince, + answerOnItsWay, credentialKey, crewListedThreads, crewListWaiting, @@ -185,6 +188,16 @@ describe("pendingParticipants", () => { // Offline, no read is coming: the stand-in shows. expect(pendingParticipants(memory, new Map(), server, ids, false).size).toBe(0); }); + + it("counts a re-pair's first connection as an answer on its way, and a retry after a failure not", () => { + const failure = credentialMissingError("connection-1"); + + expect(answerOnItsWay({ phase: "connected", lastFailure: null })).toBe(true); + expect(answerOnItsWay({ phase: "connecting", lastFailure: null })).toBe(true); + expect(answerOnItsWay({ phase: "connecting", lastFailure: failure })).toBe(false); + expect(answerOnItsWay({ phase: "backoff", lastFailure: failure })).toBe(false); + expect(answerOnItsWay(null)).toBe(false); + }); }); describe("credentialKey", () => { diff --git a/apps/mobile/src/j5/connection/memory.logic.ts b/apps/mobile/src/j5/connection/memory.logic.ts index 5609709c111ba..1e5ff083e3b40 100644 --- a/apps/mobile/src/j5/connection/memory.logic.ts +++ b/apps/mobile/src/j5/connection/memory.logic.ts @@ -1,4 +1,7 @@ -import type { PreparedConnection } from "@t3tools/client-runtime/connection"; +import type { + PreparedConnection, + SupervisorConnectionState, +} from "@t3tools/client-runtime/connection"; import { isSidebarMember } from "@t3tools/client-runtime/j5/spawned-children"; import type { ParticipantIdentities } from "@t3tools/client-runtime/j5/participant-identity"; import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; @@ -237,17 +240,28 @@ export const settleNames = ( const NO_ONE: ReadonlySet = new Set(); /** - * Ids whose name is on its way: their connected server has no remembered name for them and no - * read has settled. A screen says nothing for them rather than a stand-in it would replace. + * Whether a server's answer is on its way: it is connected, or on a first attempt that has not + * failed yet, as after a re-pair. A retry after a failure may take minutes. + */ +export const answerOnItsWay = ( + state: Pick | null, +) => + state !== null && + (state.phase === "connected" || (state.phase === "connecting" && state.lastFailure === null)); + +/** + * Ids whose name is on its way: their server's answer is coming, it has no remembered name for + * them, and no read has settled. A screen says nothing for them rather than a stand-in it would + * replace. */ export const pendingParticipants = ( memory: ConnectionMemory, settled: SettledNames, environmentId: EnvironmentId, participantIds: ReadonlyArray, - connected: boolean, + answerOnItsWay: boolean, ): ReadonlySet => { - if (!connected) return NO_ONE; + if (!answerOnItsWay) return NO_ONE; const done = settled.get(environmentId); const labels = memory.get(environmentId)?.names.labels; const pending = participantIds.filter((id) => !done?.has(id) && !labels?.has(id)); diff --git a/apps/mobile/src/j5/connection/memory.ts b/apps/mobile/src/j5/connection/memory.ts index db7f6ca6ceab8..11f57fa4c80e5 100644 --- a/apps/mobile/src/j5/connection/memory.ts +++ b/apps/mobile/src/j5/connection/memory.ts @@ -15,6 +15,7 @@ import { j5Sharing } from "../sharing/guestAccess"; import { j5Environment } from "../state"; import { answeredSince, + answerOnItsWay, credentialKey, decodeMemory, encodeMemory, @@ -161,15 +162,19 @@ export const accessConfirmedAtom = Atom.family((environmentId: EnvironmentId) => */ export const answerExpectedAtom = Atom.make((get) => { const expected = new Set(); - for (const id of get(environmentCatalog.catalogValueAtom).entries.keys()) { - const state = Option.getOrNull(AsyncResult.value(get(environmentCatalog.stateAtom(id)))); - if (state === null || get(j5Sharing.isNarrow(id))) continue; - if (state.phase === "connected" || (state.phase === "connecting" && state.lastFailure === null)) - expected.add(id); - } + for (const id of get(namesExpectedAtom)) if (!get(j5Sharing.isNarrow(id))) expected.add(id); return expected; }).pipe(Atom.withLabel("mobile-j5:answer-expected")); +/** Servers whose answers are on its way to anyone, a narrower person's name reads included. */ +export const namesExpectedAtom = Atom.make((get) => { + const expected = new Set(); + for (const id of get(environmentCatalog.catalogValueAtom).entries.keys()) + if (answerOnItsWay(Option.getOrNull(AsyncResult.value(get(environmentCatalog.stateAtom(id)))))) + expected.add(id); + return expected; +}).pipe(Atom.withLabel("mobile-j5:names-expected")); + export const connectionMemory = { subscribe: (listener: () => void) => { listeners.add(listener); diff --git a/apps/mobile/src/j5/inbox/senderLabels.ts b/apps/mobile/src/j5/inbox/senderLabels.ts index b6cd92d738191..f5c323d1db7ce 100644 --- a/apps/mobile/src/j5/inbox/senderLabels.ts +++ b/apps/mobile/src/j5/inbox/senderLabels.ts @@ -1,7 +1,8 @@ +import { useAtomValue } from "@effect/atom-react"; import type { EnvironmentId } from "@t3tools/contracts"; import { useEffect, useMemo, useSyncExternalStore } from "react"; -import { connectionMemory } from "../connection/memory"; +import { connectionMemory, namesExpectedAtom } from "../connection/memory"; import { pendingParticipants } from "../connection/memory.logic"; export interface ScopedParticipantRef { @@ -56,12 +57,21 @@ export function useScopedParticipantLabels( () => new Map([...names].map(([environmentId, known]) => [environmentId, known.labels])), [names], ); - const pendingKey = [...byEnvironment] - .flatMap(([environmentId, ids]) => - [...pendingParticipants(memory, settled, environmentId, ids, true)].map((id) => - JSON.stringify([environmentId, id]), - ), + // Every sender on screen, through a re-pair's first connection too: a name on its way shows none. + const expected = useAtomValue(namesExpectedAtom); + const pendingKey = refs + .flatMap((ref) => + pendingParticipants( + memory, + settled, + ref.environmentId, + [ref.participantId], + expected.has(ref.environmentId), + ).size > 0 + ? [JSON.stringify([ref.environmentId, ref.participantId])] + : [], ) + .sort() .join("\n"); return useMemo(() => { const pending = new Set(pendingKey === "" ? [] : pendingKey.split("\n")); From 3e38831bbc04e5af7e81f674795df8019d025455 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Fri, 20 Nov 2026 02:33:21 -0500 Subject: [PATCH 05/11] fix(mobile): a long "answered by" name no longer hides the question it follows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Live capture on #1111: a folded question row answered by a long name showed only "· answered by …" and no question, because the suffix never shrank. It now shrinks with the label, so each truncates in proportion to its length. Co-Authored-By: Claude Opus 5.5 --- FORK.md | 2 +- apps/mobile/src/j5/sharing/sharedConversation.tsx | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/FORK.md b/FORK.md index 52515ccbbd033..3d3d39f8c0e75 100644 --- a/FORK.md +++ b/FORK.md @@ -518,7 +518,7 @@ migrations after upstream migrations. 98. Mobile reads artifacts ([#833](https://github.com/Jacksondr5/j5code/issues/833)), landing two reserved mobile seams. Route registration: `apps/mobile/src/Stack.tsx` imports J5-owned `j5ThreadRoutes` (`apps/mobile/src/j5/threadRoutes.ts`) and spreads it after `ThreadFile`, adding the thread-scoped `ThreadArtifacts` list and `ThreadArtifact` viewer (`apps/mobile/src/j5/artifacts/ThreadArtifactsScreen.tsx`), read-only, with no delete; since case 114 it also registers the `ThreadCrewProposal` review screen. Link resolver: `onMarkdownLinkPress` in `apps/mobile/src/features/threads/ThreadFeed.tsx` makes one call to J5-owned `openArtifactLink` before its thread, media and file branches, so an `artifacts/…` link opens the viewer instead of a missing workspace file; its `fileContextMenu` and `onFileContextMenuAction` each make one call first (`artifactLinkContextMenu`, `onArtifactLinkMenuAction`), so an artifact link's long press offers Open artifact and Copy path instead of workspace-file actions. Links inside a Markdown artifact go through the same helpers in the J5 viewer. Recognition, preview kind and the HTTP read are shared with web in `packages/client-runtime/src/j5/artifacts.ts`. No upstream entry point reaches the list yet; it is one tap from any opened artifact. -99. Mobile's shared conversations show who wrote each message and who answered each prompt, the mobile half of case 80 ([#832](https://github.com/Jacksondr5/j5code/issues/832), register D33, Shared conversations AC9 to AC11, AC14 and AC16). The record and its change feed are `threadAuthors` and `threadAuthorsChanges` in `packages/client-runtime/src/j5/sharing.ts`, beside who reaches the thread (`scopePeople` and `scopePeopleChanges`), which says the thread is shared before any author is recorded (`mayBeSharedConversation`, [#871](https://github.com/Jacksondr5/j5code/issues/871)); and the reading of it (`sharedMessageView`, the typed text, the answers without their mark, the search label) is `packages/client-runtime/src/j5/sharedConversation.ts`, both shared with web. `apps/mobile/src/features/threads/ThreadRouteScreen.tsx` imports `useSharedConversationFeed` from J5-owned `apps/mobile/src/j5/sharing/sharedConversation.tsx` and passes its answer as `ThreadDetailScreen`'s `selectedThreadFeed` in place of `composer.selectedThreadFeed`: an authored message shows as typed, after its note to the agent as a muted line that opens (drawn by case 97's `renderJ5TimelineNotice`), a message whose author is not read yet is held back or shown as this client typed it, and a question's answers lose the platform's `[Answer from …]` mark. Case 97's `useJ5Timeline` also reads the record, so `resolveJ5FeedMessage` puts another person's message on the left and `J5MessageAuthorLine` names them, or says who edited the reader's own. `apps/mobile/src/features/threads/thread-work-log.tsx` mounts `PromptAnsweredBy` after a work row's label (" · answered by Priya", on an approval too), outside the label so the label truncates first. On a prompt's row (`answeredByFollowsLabel`) it passes upstream's `WorkLogLabel` (`work-log-layout.tsx`) a new optional `fitText`, so the label ends with its text and `PromptAnsweredBy` follows it and takes the spare width; with nothing to say there, it is an empty spacer that keeps the row's end in place. A folded answered question shows its trimmed question and who answered, or "· answered" where no one is recorded, as in an unshared thread ([#1028](https://github.com/Jacksondr5/j5code/issues/1028)); its answer is in the opened row ([#959](https://github.com/Jacksondr5/j5code/issues/959)). Opened, an answered question whose answer records its question text drops the trimmed question from the header for "answered by Priya", or "answered" where no one is recorded, and the row draws no raw item JSON beneath the question and answer, as web draws neither ([#891](https://github.com/Jacksondr5/j5code/issues/891)). `apps/mobile/src/features/threads/ThreadQueueControl.tsx` reads its rows through `useSharedQueuedRuns` where it builds `queuedRuns`, ahead of case 97's hook, so a queued message's row and the text an edit loads are the words typed. `apps/mobile/src/features/threads/thread-search-match.tsx` labels a hit with `threadSearchMatchLabel` instead of "You:" for every user-role hit. `apps/mobile/src/lib/filePreview.test.ts` mocks `sharedConversation.tsx` as it mocks case 97's `timelineState.ts`. Proofs: `apps/mobile/src/j5/sharing/sharedConversationFeed.test.ts`, `apps/mobile/src/j5/a2a/timelinePresentation.test.ts`, `packages/client-runtime/src/j5/sharedConversation.test.ts`, `packages/client-runtime/src/j5/threadSearchMatchLabel.test.ts`, and the four files' rows in `apps/mobile/src/j5/upstreamSeams.test.ts`. On every rebase, keep the calls that test lists. +99. Mobile's shared conversations show who wrote each message and who answered each prompt, the mobile half of case 80 ([#832](https://github.com/Jacksondr5/j5code/issues/832), register D33, Shared conversations AC9 to AC11, AC14 and AC16). The record and its change feed are `threadAuthors` and `threadAuthorsChanges` in `packages/client-runtime/src/j5/sharing.ts`, beside who reaches the thread (`scopePeople` and `scopePeopleChanges`), which says the thread is shared before any author is recorded (`mayBeSharedConversation`, [#871](https://github.com/Jacksondr5/j5code/issues/871)); and the reading of it (`sharedMessageView`, the typed text, the answers without their mark, the search label) is `packages/client-runtime/src/j5/sharedConversation.ts`, both shared with web. `apps/mobile/src/features/threads/ThreadRouteScreen.tsx` imports `useSharedConversationFeed` from J5-owned `apps/mobile/src/j5/sharing/sharedConversation.tsx` and passes its answer as `ThreadDetailScreen`'s `selectedThreadFeed` in place of `composer.selectedThreadFeed`: an authored message shows as typed, after its note to the agent as a muted line that opens (drawn by case 97's `renderJ5TimelineNotice`), a message whose author is not read yet is held back or shown as this client typed it, and a question's answers lose the platform's `[Answer from …]` mark. Case 97's `useJ5Timeline` also reads the record, so `resolveJ5FeedMessage` puts another person's message on the left and `J5MessageAuthorLine` names them, or says who edited the reader's own. `apps/mobile/src/features/threads/thread-work-log.tsx` mounts `PromptAnsweredBy` after a work row's label (" · answered by Priya", on an approval too), outside the label so the two truncate together and a long name never hides the question. On a prompt's row (`answeredByFollowsLabel`) it passes upstream's `WorkLogLabel` (`work-log-layout.tsx`) a new optional `fitText`, so the label ends with its text and `PromptAnsweredBy` follows it and takes the spare width; with nothing to say there, it is an empty spacer that keeps the row's end in place. A folded answered question shows its trimmed question and who answered, or "· answered" where no one is recorded, as in an unshared thread ([#1028](https://github.com/Jacksondr5/j5code/issues/1028)); its answer is in the opened row ([#959](https://github.com/Jacksondr5/j5code/issues/959)). Opened, an answered question whose answer records its question text drops the trimmed question from the header for "answered by Priya", or "answered" where no one is recorded, and the row draws no raw item JSON beneath the question and answer, as web draws neither ([#891](https://github.com/Jacksondr5/j5code/issues/891)). `apps/mobile/src/features/threads/ThreadQueueControl.tsx` reads its rows through `useSharedQueuedRuns` where it builds `queuedRuns`, ahead of case 97's hook, so a queued message's row and the text an edit loads are the words typed. `apps/mobile/src/features/threads/thread-search-match.tsx` labels a hit with `threadSearchMatchLabel` instead of "You:" for every user-role hit. `apps/mobile/src/lib/filePreview.test.ts` mocks `sharedConversation.tsx` as it mocks case 97's `timelineState.ts`. Proofs: `apps/mobile/src/j5/sharing/sharedConversationFeed.test.ts`, `apps/mobile/src/j5/a2a/timelinePresentation.test.ts`, `packages/client-runtime/src/j5/sharedConversation.test.ts`, `packages/client-runtime/src/j5/threadSearchMatchLabel.test.ts`, and the four files' rows in `apps/mobile/src/j5/upstreamSeams.test.ts`. On every rebase, keep the calls that test lists. 100. The mobile new-task composer gives a saved agent its own row and lets the slash menu cover the draft rows ([#866](https://github.com/Jacksondr5/j5code/issues/866), Jackson's direction at Checkpoint 1, 2026-11-01; register entry in the wave-2 docs PR). Upstream's composer shows the model in its input row and opens the slash menu above everything stacked over the input. In `apps/mobile/src/features/threads/NewTaskDraftScreen.tsx`, the draft controls render J5-owned `j5/agents/DraftAgentRow.tsx` under the checkout row: the saved-agent picker, then the chosen agent's persona, route and remove action. `apps/mobile/src/features/threads/ThreadComposer.tsx` renders the persona lock control, which wraps upstream's `usesLargeControls` model control since v0.1.7, only when `!props.isDraft`, so a draft's input row stays the editor, and wraps `ComposerPopoverAnchor` in a zero-height `relative` view placed after `draftControls`. The anchor's `bottom-full` (and the Android anchor's measured frame) then starts at the top of the input, so the menu draws over the checkout and agent rows instead of above them. A started thread has no draft controls, so its menu opens where it did. diff --git a/apps/mobile/src/j5/sharing/sharedConversation.tsx b/apps/mobile/src/j5/sharing/sharedConversation.tsx index b9ad8a2c8ac9f..f2cde6fb38050 100644 --- a/apps/mobile/src/j5/sharing/sharedConversation.tsx +++ b/apps/mobile/src/j5/sharing/sharedConversation.tsx @@ -160,8 +160,9 @@ export function PromptAnsweredBy(props: { return ( {by === undefined ? said : `${said} by ${by.you ? "you" : (by.name ?? "someone")}`} From 6a0fbc999ee4bb7bcbc8d0406b5f87baa670bdcc Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Fri, 20 Nov 2026 02:35:39 -0500 Subject: [PATCH 06/11] fix(mobile): "answered by" keeps its name and stops at half the row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review on #1111: sharing the shrink cut a short name ("· answered b…") on the common row with a long question, reversing case 99's "the label truncates first". The suffix keeps its width again, capped at half the row, and a spacer after it holds the row's end. Co-Authored-By: Claude Opus 5.5 --- FORK.md | 2 +- .../src/j5/sharing/sharedConversation.tsx | 19 +++++++++++-------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/FORK.md b/FORK.md index 3d3d39f8c0e75..0d7b4cc0c7df3 100644 --- a/FORK.md +++ b/FORK.md @@ -518,7 +518,7 @@ migrations after upstream migrations. 98. Mobile reads artifacts ([#833](https://github.com/Jacksondr5/j5code/issues/833)), landing two reserved mobile seams. Route registration: `apps/mobile/src/Stack.tsx` imports J5-owned `j5ThreadRoutes` (`apps/mobile/src/j5/threadRoutes.ts`) and spreads it after `ThreadFile`, adding the thread-scoped `ThreadArtifacts` list and `ThreadArtifact` viewer (`apps/mobile/src/j5/artifacts/ThreadArtifactsScreen.tsx`), read-only, with no delete; since case 114 it also registers the `ThreadCrewProposal` review screen. Link resolver: `onMarkdownLinkPress` in `apps/mobile/src/features/threads/ThreadFeed.tsx` makes one call to J5-owned `openArtifactLink` before its thread, media and file branches, so an `artifacts/…` link opens the viewer instead of a missing workspace file; its `fileContextMenu` and `onFileContextMenuAction` each make one call first (`artifactLinkContextMenu`, `onArtifactLinkMenuAction`), so an artifact link's long press offers Open artifact and Copy path instead of workspace-file actions. Links inside a Markdown artifact go through the same helpers in the J5 viewer. Recognition, preview kind and the HTTP read are shared with web in `packages/client-runtime/src/j5/artifacts.ts`. No upstream entry point reaches the list yet; it is one tap from any opened artifact. -99. Mobile's shared conversations show who wrote each message and who answered each prompt, the mobile half of case 80 ([#832](https://github.com/Jacksondr5/j5code/issues/832), register D33, Shared conversations AC9 to AC11, AC14 and AC16). The record and its change feed are `threadAuthors` and `threadAuthorsChanges` in `packages/client-runtime/src/j5/sharing.ts`, beside who reaches the thread (`scopePeople` and `scopePeopleChanges`), which says the thread is shared before any author is recorded (`mayBeSharedConversation`, [#871](https://github.com/Jacksondr5/j5code/issues/871)); and the reading of it (`sharedMessageView`, the typed text, the answers without their mark, the search label) is `packages/client-runtime/src/j5/sharedConversation.ts`, both shared with web. `apps/mobile/src/features/threads/ThreadRouteScreen.tsx` imports `useSharedConversationFeed` from J5-owned `apps/mobile/src/j5/sharing/sharedConversation.tsx` and passes its answer as `ThreadDetailScreen`'s `selectedThreadFeed` in place of `composer.selectedThreadFeed`: an authored message shows as typed, after its note to the agent as a muted line that opens (drawn by case 97's `renderJ5TimelineNotice`), a message whose author is not read yet is held back or shown as this client typed it, and a question's answers lose the platform's `[Answer from …]` mark. Case 97's `useJ5Timeline` also reads the record, so `resolveJ5FeedMessage` puts another person's message on the left and `J5MessageAuthorLine` names them, or says who edited the reader's own. `apps/mobile/src/features/threads/thread-work-log.tsx` mounts `PromptAnsweredBy` after a work row's label (" · answered by Priya", on an approval too), outside the label so the two truncate together and a long name never hides the question. On a prompt's row (`answeredByFollowsLabel`) it passes upstream's `WorkLogLabel` (`work-log-layout.tsx`) a new optional `fitText`, so the label ends with its text and `PromptAnsweredBy` follows it and takes the spare width; with nothing to say there, it is an empty spacer that keeps the row's end in place. A folded answered question shows its trimmed question and who answered, or "· answered" where no one is recorded, as in an unshared thread ([#1028](https://github.com/Jacksondr5/j5code/issues/1028)); its answer is in the opened row ([#959](https://github.com/Jacksondr5/j5code/issues/959)). Opened, an answered question whose answer records its question text drops the trimmed question from the header for "answered by Priya", or "answered" where no one is recorded, and the row draws no raw item JSON beneath the question and answer, as web draws neither ([#891](https://github.com/Jacksondr5/j5code/issues/891)). `apps/mobile/src/features/threads/ThreadQueueControl.tsx` reads its rows through `useSharedQueuedRuns` where it builds `queuedRuns`, ahead of case 97's hook, so a queued message's row and the text an edit loads are the words typed. `apps/mobile/src/features/threads/thread-search-match.tsx` labels a hit with `threadSearchMatchLabel` instead of "You:" for every user-role hit. `apps/mobile/src/lib/filePreview.test.ts` mocks `sharedConversation.tsx` as it mocks case 97's `timelineState.ts`. Proofs: `apps/mobile/src/j5/sharing/sharedConversationFeed.test.ts`, `apps/mobile/src/j5/a2a/timelinePresentation.test.ts`, `packages/client-runtime/src/j5/sharedConversation.test.ts`, `packages/client-runtime/src/j5/threadSearchMatchLabel.test.ts`, and the four files' rows in `apps/mobile/src/j5/upstreamSeams.test.ts`. On every rebase, keep the calls that test lists. +99. Mobile's shared conversations show who wrote each message and who answered each prompt, the mobile half of case 80 ([#832](https://github.com/Jacksondr5/j5code/issues/832), register D33, Shared conversations AC9 to AC11, AC14 and AC16). The record and its change feed are `threadAuthors` and `threadAuthorsChanges` in `packages/client-runtime/src/j5/sharing.ts`, beside who reaches the thread (`scopePeople` and `scopePeopleChanges`), which says the thread is shared before any author is recorded (`mayBeSharedConversation`, [#871](https://github.com/Jacksondr5/j5code/issues/871)); and the reading of it (`sharedMessageView`, the typed text, the answers without their mark, the search label) is `packages/client-runtime/src/j5/sharedConversation.ts`, both shared with web. `apps/mobile/src/features/threads/ThreadRouteScreen.tsx` imports `useSharedConversationFeed` from J5-owned `apps/mobile/src/j5/sharing/sharedConversation.tsx` and passes its answer as `ThreadDetailScreen`'s `selectedThreadFeed` in place of `composer.selectedThreadFeed`: an authored message shows as typed, after its note to the agent as a muted line that opens (drawn by case 97's `renderJ5TimelineNotice`), a message whose author is not read yet is held back or shown as this client typed it, and a question's answers lose the platform's `[Answer from …]` mark. Case 97's `useJ5Timeline` also reads the record, so `resolveJ5FeedMessage` puts another person's message on the left and `J5MessageAuthorLine` names them, or says who edited the reader's own. `apps/mobile/src/features/threads/thread-work-log.tsx` mounts `PromptAnsweredBy` after a work row's label (" · answered by Priya", on an approval too), outside the label so the label truncates first; a long name is capped at half the row. On a prompt's row (`answeredByFollowsLabel`) it passes upstream's `WorkLogLabel` (`work-log-layout.tsx`) a new optional `fitText`, so the label ends with its text, `PromptAnsweredBy` follows it, and a spacer after it takes the spare width; with nothing to say there, it is an empty spacer that keeps the row's end in place. A folded answered question shows its trimmed question and who answered, or "· answered" where no one is recorded, as in an unshared thread ([#1028](https://github.com/Jacksondr5/j5code/issues/1028)); its answer is in the opened row ([#959](https://github.com/Jacksondr5/j5code/issues/959)). Opened, an answered question whose answer records its question text drops the trimmed question from the header for "answered by Priya", or "answered" where no one is recorded, and the row draws no raw item JSON beneath the question and answer, as web draws neither ([#891](https://github.com/Jacksondr5/j5code/issues/891)). `apps/mobile/src/features/threads/ThreadQueueControl.tsx` reads its rows through `useSharedQueuedRuns` where it builds `queuedRuns`, ahead of case 97's hook, so a queued message's row and the text an edit loads are the words typed. `apps/mobile/src/features/threads/thread-search-match.tsx` labels a hit with `threadSearchMatchLabel` instead of "You:" for every user-role hit. `apps/mobile/src/lib/filePreview.test.ts` mocks `sharedConversation.tsx` as it mocks case 97's `timelineState.ts`. Proofs: `apps/mobile/src/j5/sharing/sharedConversationFeed.test.ts`, `apps/mobile/src/j5/a2a/timelinePresentation.test.ts`, `packages/client-runtime/src/j5/sharedConversation.test.ts`, `packages/client-runtime/src/j5/threadSearchMatchLabel.test.ts`, and the four files' rows in `apps/mobile/src/j5/upstreamSeams.test.ts`. On every rebase, keep the calls that test lists. 100. The mobile new-task composer gives a saved agent its own row and lets the slash menu cover the draft rows ([#866](https://github.com/Jacksondr5/j5code/issues/866), Jackson's direction at Checkpoint 1, 2026-11-01; register entry in the wave-2 docs PR). Upstream's composer shows the model in its input row and opens the slash menu above everything stacked over the input. In `apps/mobile/src/features/threads/NewTaskDraftScreen.tsx`, the draft controls render J5-owned `j5/agents/DraftAgentRow.tsx` under the checkout row: the saved-agent picker, then the chosen agent's persona, route and remove action. `apps/mobile/src/features/threads/ThreadComposer.tsx` renders the persona lock control, which wraps upstream's `usesLargeControls` model control since v0.1.7, only when `!props.isDraft`, so a draft's input row stays the editor, and wraps `ComposerPopoverAnchor` in a zero-height `relative` view placed after `draftControls`. The anchor's `bottom-full` (and the Android anchor's measured frame) then starts at the top of the input, so the menu draws over the checkout and agent rows instead of above them. A started thread has no draft controls, so its menu opens where it did. diff --git a/apps/mobile/src/j5/sharing/sharedConversation.tsx b/apps/mobile/src/j5/sharing/sharedConversation.tsx index f2cde6fb38050..e413a383056bb 100644 --- a/apps/mobile/src/j5/sharing/sharedConversation.tsx +++ b/apps/mobile/src/j5/sharing/sharedConversation.tsx @@ -158,14 +158,17 @@ export function PromptAnsweredBy(props: { // Lowercase in every state, as web's "· answered by Priya" is. const said = props.alone ? "answered" : "· answered"; return ( - - {by === undefined ? said : `${said} by ${by.you ? "you" : (by.name ?? "someone")}`} - + <> + + {by === undefined ? said : `${said} by ${by.you ? "you" : (by.name ?? "someone")}`} + + + ); } From 0009107601707947aa5158594f06346ba6771d22 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Fri, 20 Nov 2026 02:51:46 -0500 Subject: [PATCH 07/11] fix(mobile): an opened question's "answered by" takes the whole row Visual review on #1111: the half-row cap also cut the name on an opened question, where no question shares the row. The cap now applies only after a question; alone, the name truncates at the row's edge. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/j5/sharing/sharedConversation.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/j5/sharing/sharedConversation.tsx b/apps/mobile/src/j5/sharing/sharedConversation.tsx index e413a383056bb..fb20404e741c1 100644 --- a/apps/mobile/src/j5/sharing/sharedConversation.tsx +++ b/apps/mobile/src/j5/sharing/sharedConversation.tsx @@ -161,9 +161,9 @@ export function PromptAnsweredBy(props: { <> {by === undefined ? said : `${said} by ${by.you ? "you" : (by.name ?? "someone")}`} From 6a94c352f4ec89791d0c59dac8dbd2ee8cba9048 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Fri, 20 Nov 2026 22:53:33 -0500 Subject: [PATCH 08/11] fix(mobile): a re-pair holds back the last person's names and lineage at once Android capture on #1111: after re-pairing as a Viewer, the Owner's author names and Open parent bar stayed about 8 s, until the new connection opened and reported its credential. Re-pairing replaces the server's saved entry at once, so J5 now treats a replaced entry as a credential in question: that server's names read as on their way and lineage waits for a new access answer, until the new connection shows its credential, kept if it's the same and dropped if not. An opened question's "answered by" also takes its row itself instead of sharing it with a spacer, which gave back the gap a long name lost (Opus nit). Co-Authored-By: Claude Opus 5.5 --- .../src/j5/a2a/participantIdentities.ts | 8 +- .../src/j5/connection/memory.logic.test.ts | 42 +++++-- apps/mobile/src/j5/connection/memory.logic.ts | 21 +++- apps/mobile/src/j5/connection/memory.ts | 104 ++++++++++++------ apps/mobile/src/j5/inbox/senderLabels.ts | 4 +- .../src/j5/sharing/sharedConversation.tsx | 4 +- 6 files changed, 125 insertions(+), 58 deletions(-) diff --git a/apps/mobile/src/j5/a2a/participantIdentities.ts b/apps/mobile/src/j5/a2a/participantIdentities.ts index 14060a91f4aea..127f7fbed86ac 100644 --- a/apps/mobile/src/j5/a2a/participantIdentities.ts +++ b/apps/mobile/src/j5/a2a/participantIdentities.ts @@ -39,11 +39,7 @@ export function useParticipantIdentities( const connected = useConnectedEnvironmentIds().has(environmentId); // Through a re-pair's first connection too, so the line never swaps a stand-in for the name. const expected = useAtomValue(namesExpectedAtom).has(environmentId); - const { - memory, - names: known, - settled, - } = useSyncExternalStore( + const { names: known, settled } = useSyncExternalStore( connectionMemory.subscribe, connectionMemory.getSnapshot, connectionMemory.getSnapshot, @@ -56,7 +52,7 @@ export function useParticipantIdentities( const names = known.get(environmentId) ?? NO_IDENTITIES; const pendingKey = [ ...pendingParticipants( - memory, + known, settled, environmentId, idsKey === "" ? [] : idsKey.split("\0"), diff --git a/apps/mobile/src/j5/connection/memory.logic.test.ts b/apps/mobile/src/j5/connection/memory.logic.test.ts index f34f4ed5d1ea1..a0403c27387a2 100644 --- a/apps/mobile/src/j5/connection/memory.logic.test.ts +++ b/apps/mobile/src/j5/connection/memory.logic.test.ts @@ -12,6 +12,7 @@ import { crewListWaiting, decodeMemory, encodeMemory, + heldNames, observeCredential, pendingParticipants, rememberIdentities, @@ -171,22 +172,18 @@ describe("participant names", () => { }); describe("pendingParticipants", () => { - const memory = rememberIdentities( - observeCredential(new Map(), server, owner), - server, - owner, - ["agent:a"], - { labels: new Map([["agent:a", "Sender A"]]), threads: new Map() }, - ); + const names = new Map([ + [server, { labels: new Map([["agent:a", "Sender A"]]), threads: new Map() }], + ]); it("says a new sender's name is on its way until a read settles, even a failed one", () => { const ids = ["agent:a", "agent:b"]; - expect([...pendingParticipants(memory, new Map(), server, ids, true)]).toEqual(["agent:b"]); + expect([...pendingParticipants(names, new Map(), server, ids, true)]).toEqual(["agent:b"]); const failed = settleNames(new Map(), server, ["agent:b"]); - expect(pendingParticipants(memory, failed, server, ids, true).size).toBe(0); + expect(pendingParticipants(names, failed, server, ids, true).size).toBe(0); // Offline, no read is coming: the stand-in shows. - expect(pendingParticipants(memory, new Map(), server, ids, false).size).toBe(0); + expect(pendingParticipants(names, new Map(), server, ids, false).size).toBe(0); }); it("counts a re-pair's first connection as an answer on its way, and a retry after a failure not", () => { @@ -200,6 +197,31 @@ describe("pendingParticipants", () => { }); }); +describe("heldNames", () => { + it("holds back a re-paired server's names until its new credential shows, so they read as on their way", () => { + const memory = rememberIdentities( + observeCredential(new Map(), server, owner), + server, + owner, + ["agent:captain"], + { labels: new Map([["agent:captain", "Captain"]]), threads: new Map() }, + ); + const settled = settleNames(new Map(), server, ["agent:captain"]); + + const held = heldNames(memory, settled, new Set([server])); + expect(held.names.size).toBe(0); + expect([ + ...pendingParticipants(held.names, held.settled, server, ["agent:captain"], true), + ]).toEqual(["agent:captain"]); + // Once the new connection shows the same credential, the names are back as they were. + const shown = heldNames(memory, settled, new Set()); + expect(shown.names.get(server)?.labels.get("agent:captain")).toBe("Captain"); + expect( + pendingParticipants(shown.names, shown.settled, server, ["agent:captain"], true).size, + ).toBe(0); + }); +}); + describe("credentialKey", () => { it("tells two pairings apart without keeping the token", () => { const prepared = (token: string) => ({ diff --git a/apps/mobile/src/j5/connection/memory.logic.ts b/apps/mobile/src/j5/connection/memory.logic.ts index 1e5ff083e3b40..07807031d67e2 100644 --- a/apps/mobile/src/j5/connection/memory.logic.ts +++ b/apps/mobile/src/j5/connection/memory.logic.ts @@ -255,7 +255,7 @@ export const answerOnItsWay = ( * replace. */ export const pendingParticipants = ( - memory: ConnectionMemory, + names: ReadonlyMap, settled: SettledNames, environmentId: EnvironmentId, participantIds: ReadonlyArray, @@ -263,7 +263,7 @@ export const pendingParticipants = ( ): ReadonlySet => { if (!answerOnItsWay) return NO_ONE; const done = settled.get(environmentId); - const labels = memory.get(environmentId)?.names.labels; + const labels = names.get(environmentId)?.labels; const pending = participantIds.filter((id) => !done?.has(id) && !labels?.has(id)); return pending.length === 0 ? NO_ONE : new Set(pending); }; @@ -283,3 +283,20 @@ export function crewListWaiting( memory.get(thread.environmentId)?.spawned.get(thread.id) === undefined, ); } + +/** + * The names and settled reads screens may show. A server whose credential is in question (re-paired, + * its new connection not yet open) shows none, so its names read as on their way. + */ +export const heldNames = ( + memory: ConnectionMemory, + settled: SettledNames, + uncertain: ReadonlySet, +) => ({ + names: new Map( + [...memory].flatMap(([environmentId, connection]) => + uncertain.has(environmentId) ? [] : [[environmentId, connection.names] as const], + ), + ), + settled: new Map([...settled].filter(([environmentId]) => !uncertain.has(environmentId))), +}); diff --git a/apps/mobile/src/j5/connection/memory.ts b/apps/mobile/src/j5/connection/memory.ts index 11f57fa4c80e5..5bf90b6da9b6a 100644 --- a/apps/mobile/src/j5/connection/memory.ts +++ b/apps/mobile/src/j5/connection/memory.ts @@ -19,6 +19,7 @@ import { credentialKey, decodeMemory, encodeMemory, + heldNames, observeCredential, rememberIdentities, rememberSpawned, @@ -49,16 +50,13 @@ const loadSaved = (): ConnectionMemory => { } }; -const namesOf = (memory: ConnectionMemory) => - new Map([...memory].map(([environmentId, connection]) => [environmentId, connection.names])); +type MemoryState = Omit; -const loaded = loadSaved(); -let snapshot: MemorySnapshot = { - memory: loaded, - names: namesOf(loaded), - settled: new Map(), - failedReads: new Set(), -}; +let state: MemoryState = { memory: loadSaved(), settled: new Map(), failedReads: new Set() }; +/** Servers re-paired or re-routed this launch whose new credential has not shown itself yet. */ +const uncertain = new Set(); +const heldState = () => heldNames(state.memory, state.settled, uncertain); +let snapshot: MemorySnapshot = { ...state, ...heldState() }; const listeners = new Set<() => void>(); /** The credential each server's connection uses this launch. */ const credentials = new Map(); @@ -74,18 +72,19 @@ const scheduleSave = () => { saveTimer = null; // Saves follow a credential seen this launch, so the catalog has loaded: a removed server goes. const saved = new Set(appAtomRegistry.get(environmentCatalog.catalogValueAtom).entries.keys()); - const memory = new Map([...snapshot.memory].filter(([id]) => saved.has(id))); + const memory = new Map([...state.memory].filter(([id]) => saved.has(id))); const contents = encodeMemory(retainSpawned(memory, asked)); writing = writing.then(() => writeFileAtomically(file(), contents)).catch(() => undefined); }, 500); }; -const publish = (next: Partial>) => { - const names = next.memory === undefined ? snapshot.names : namesOf(next.memory); +const publish = (next: Partial) => { + state = { ...state, ...next }; + const { names, settled } = heldState(); const sameNames = names.size === snapshot.names.size && [...names].every(([environmentId, known]) => snapshot.names.get(environmentId) === known); - snapshot = { ...snapshot, ...next, names: sameNames ? snapshot.names : names }; + snapshot = { ...state, settled, names: sameNames ? snapshot.names : names }; if (next.memory !== undefined) scheduleSave(); listeners.forEach((listener) => listener()); }; @@ -96,11 +95,16 @@ const without = (map: ReadonlyMap, key: K) => { return next; }; +const preparedOf = (environmentId: EnvironmentId) => + Option.getOrNull( + appAtomRegistry.get(environmentSession.preparedConnectionValueAtom(environmentId)), + ); + const credentialKeysAtom = Atom.make((get) => { - const keys = new Map(); + const keys = new Map(); for (const id of get(environmentCatalog.catalogValueAtom).entries.keys()) { const prepared = Option.getOrNull(get(environmentSession.preparedConnectionValueAtom(id))); - if (prepared !== null) keys.set(id, credentialKey(prepared)); + if (prepared !== null) keys.set(id, { key: credentialKey(prepared), prepared }); } return keys; }).pipe(Atom.withLabel("mobile-j5:credential-keys")); @@ -117,14 +121,30 @@ const accessBaselinesAtom = Atom.make>(new M const accessQuery = (environmentId: EnvironmentId) => j5Sharing.connectionAccessQuery({ environmentId, input: {} }); +/** Lineage on these servers waits for an access answer newer than the one they hold now. */ +const awaitNewAccess = (environmentIds: ReadonlyArray) => { + if (environmentIds.length === 0) return; + const baselines = new Map(appAtomRegistry.get(accessBaselinesAtom)); + for (const environmentId of environmentIds) + baselines.set(environmentId, appAtomRegistry.get(accessQuery(environmentId))); + appAtomRegistry.set(accessBaselinesAtom, baselines); +}; + +/** The prepared connection each uncertain server had when it became uncertain. */ +const preparedWhenUncertain = new Map(); + // A missing key is a connection between attempts, which keeps its credential. appAtomRegistry.subscribe( credentialKeysAtom, (keys) => { - let memory = snapshot.memory; - let { settled, failedReads } = snapshot; + let { memory, settled, failedReads } = state; + let settledUncertainty = false; const changed: Array = []; - for (const [environmentId, key] of keys) { + for (const [environmentId, { key, prepared }] of keys) { + if (uncertain.has(environmentId) && prepared !== preparedWhenUncertain.get(environmentId)) { + uncertain.delete(environmentId); + settledUncertainty = true; + } const previous = credentials.get(environmentId); if (previous === key) continue; credentials.set(environmentId, key); @@ -135,12 +155,30 @@ appAtomRegistry.subscribe( failedReads = new Set([...failedReads].filter((id) => id !== environmentId)); namesInFlight.delete(environmentId); } - if (memory !== snapshot.memory) publish({ memory, settled, failedReads }); - if (changed.length === 0) return; - const baselines = new Map(appAtomRegistry.get(accessBaselinesAtom)); - for (const environmentId of changed) - baselines.set(environmentId, appAtomRegistry.get(accessQuery(environmentId))); - appAtomRegistry.set(accessBaselinesAtom, baselines); + if (memory !== state.memory || settledUncertainty) publish({ memory, settled, failedReads }); + awaitNewAccess(changed); + }, + { immediate: true }, +); + +const entries = new Map(); +// Re-pairing replaces a server's saved entry at once, while its new connection reports the +// credential only once it opens: until then, the last person's names and lineage are held back. +appAtomRegistry.subscribe( + environmentCatalog.catalogValueAtom, + (catalog) => { + const replaced: Array = []; + for (const [environmentId, entry] of catalog.entries) { + const previous = entries.get(environmentId); + entries.set(environmentId, entry); + if (previous === undefined || previous === entry) continue; + replaced.push(environmentId); + uncertain.add(environmentId); + preparedWhenUncertain.set(environmentId, preparedOf(environmentId)); + } + if (replaced.length === 0) return; + publish({}); + awaitNewAccess(replaced); }, { immediate: true }, ); @@ -195,20 +233,14 @@ export const connectionMemory = { for (const threadId of requested) listed.add(threadId); asked.set(environmentId, listed); publish({ - memory: rememberSpawned( - snapshot.memory, - environmentId, - credential, - requested, - spawnedByAgent, - ), - failedReads: new Set([...snapshot.failedReads].filter((id) => id !== environmentId)), + memory: rememberSpawned(state.memory, environmentId, credential, requested, spawnedByAgent), + failedReads: new Set([...state.failedReads].filter((id) => id !== environmentId)), }); }, spawnedReadFailed: (environmentId: EnvironmentId) => { - if (!snapshot.failedReads.has(environmentId)) - publish({ failedReads: new Set(snapshot.failedReads).add(environmentId) }); + if (!state.failedReads.has(environmentId)) + publish({ failedReads: new Set(state.failedReads).add(environmentId) }); }, /** @@ -230,11 +262,11 @@ export const connectionMemory = { }); if (credentials.get(environmentId) !== credential) return; // A failed read still settles, so its senders fall back to a stand-in until the next one. - const settled = settleNames(snapshot.settled, environmentId, ids); + const settled = settleNames(state.settled, environmentId, ids); if (result._tag === "Failure") return publish({ settled }); publish({ memory: rememberIdentities( - snapshot.memory, + state.memory, environmentId, credential, ids, diff --git a/apps/mobile/src/j5/inbox/senderLabels.ts b/apps/mobile/src/j5/inbox/senderLabels.ts index f5c323d1db7ce..e0aba2c402a18 100644 --- a/apps/mobile/src/j5/inbox/senderLabels.ts +++ b/apps/mobile/src/j5/inbox/senderLabels.ts @@ -34,7 +34,7 @@ export function useScopedParticipantLabels( ) .sort() .join("\n"); - const { memory, names, settled } = useSyncExternalStore( + const { names, settled } = useSyncExternalStore( connectionMemory.subscribe, connectionMemory.getSnapshot, connectionMemory.getSnapshot, @@ -62,7 +62,7 @@ export function useScopedParticipantLabels( const pendingKey = refs .flatMap((ref) => pendingParticipants( - memory, + names, settled, ref.environmentId, [ref.participantId], diff --git a/apps/mobile/src/j5/sharing/sharedConversation.tsx b/apps/mobile/src/j5/sharing/sharedConversation.tsx index fb20404e741c1..999a07036c4d3 100644 --- a/apps/mobile/src/j5/sharing/sharedConversation.tsx +++ b/apps/mobile/src/j5/sharing/sharedConversation.tsx @@ -163,11 +163,11 @@ export function PromptAnsweredBy(props: { numberOfLines={1} // After a question, the question truncates first and a long name stops at half the row. // Alone, it takes the row and cancels the gap-1.5 around the empty label before it. - className={`pr-1.5 text-sm text-foreground-muted ${props.alone ? "-ml-1.5 min-w-0 shrink" : "max-w-[50%] shrink-0 pl-1"}`} + className={`pr-1.5 text-sm text-foreground-muted ${props.alone ? "-ml-1.5 min-w-0 flex-1" : "max-w-[50%] shrink-0 pl-1"}`} > {by === undefined ? said : `${said} by ${by.you ? "you" : (by.name ?? "someone")}`} - + {props.alone ? null : } ); } From ce0886febc51fdacb4229add632c3f931c3cd037 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Fri, 20 Nov 2026 23:00:56 -0500 Subject: [PATCH 09/11] fix(mobile): a re-pair is told by the stored token, not by any entry change Review on #1111: a learned route replaces a server's entry on a live connection, so the hold on names and lineage could stay on until the next reconnect. J5 now reads the stored bearer token when a server's entry changes: a learned route keeps the token and changes nothing, while a re-pair stores a new one and drops the last person's names and lineage at once. Co-Authored-By: Claude Opus 5.5 --- .../src/j5/connection/memory.logic.test.ts | 49 ++++---- apps/mobile/src/j5/connection/memory.logic.ts | 17 --- apps/mobile/src/j5/connection/memory.ts | 111 ++++++++++-------- 3 files changed, 84 insertions(+), 93 deletions(-) diff --git a/apps/mobile/src/j5/connection/memory.logic.test.ts b/apps/mobile/src/j5/connection/memory.logic.test.ts index a0403c27387a2..fc06f629f340a 100644 --- a/apps/mobile/src/j5/connection/memory.logic.test.ts +++ b/apps/mobile/src/j5/connection/memory.logic.test.ts @@ -12,7 +12,6 @@ import { crewListWaiting, decodeMemory, encodeMemory, - heldNames, observeCredential, pendingParticipants, rememberIdentities, @@ -197,43 +196,35 @@ describe("pendingParticipants", () => { }); }); -describe("heldNames", () => { - it("holds back a re-paired server's names until its new credential shows, so they read as on their way", () => { - const memory = rememberIdentities( - observeCredential(new Map(), server, owner), - server, - owner, - ["agent:captain"], - { labels: new Map([["agent:captain", "Captain"]]), threads: new Map() }, - ); - const settled = settleNames(new Map(), server, ["agent:captain"]); - - const held = heldNames(memory, settled, new Set([server])); - expect(held.names.size).toBe(0); - expect([ - ...pendingParticipants(held.names, held.settled, server, ["agent:captain"], true), - ]).toEqual(["agent:captain"]); - // Once the new connection shows the same credential, the names are back as they were. - const shown = heldNames(memory, settled, new Set()); - expect(shown.names.get(server)?.labels.get("agent:captain")).toBe("Captain"); - expect( - pendingParticipants(shown.names, shown.settled, server, ["agent:captain"], true).size, - ).toBe(0); +describe("credentialKey", () => { + const prepared = (token: string, address = "https://server-1") => ({ + httpAuthorization: { _tag: "Bearer" as const, token }, + target: { environmentId: server, address }, }); -}); -describe("credentialKey", () => { it("tells two pairings apart without keeping the token", () => { - const prepared = (token: string) => ({ - httpAuthorization: { _tag: "Bearer" as const, token }, - target: { environmentId: server }, - }); const first = credentialKey(prepared("secret-token-one")); expect(first).toBe(credentialKey(prepared("secret-token-one"))); expect(first).not.toBe(credentialKey(prepared("secret-token-two"))); expect(first).not.toContain("secret"); }); + + it("keeps a server's names through a learned route, and drops them on a re-pair", () => { + const named = rememberIdentities( + observeCredential(new Map(), server, credentialKey(prepared("owner-token"))), + server, + credentialKey(prepared("owner-token")), + ["agent:captain"], + { labels: new Map([["agent:captain", "Captain"]]), threads: new Map() }, + ); + // A learned route replaces the saved entry but keeps the paired token. + const rerouted = credentialKey(prepared("owner-token", "http://100.64.0.7:3773")); + expect(observeCredential(named, server, rerouted)).toBe(named); + // Re-pairing stores another token: the last person's names go at once. + const repaired = observeCredential(named, server, credentialKey(prepared("viewer-token"))); + expect(repaired.get(server)?.names.labels.size).toBe(0); + }); }); describe("answeredSince", () => { diff --git a/apps/mobile/src/j5/connection/memory.logic.ts b/apps/mobile/src/j5/connection/memory.logic.ts index 07807031d67e2..fb61195b91cd3 100644 --- a/apps/mobile/src/j5/connection/memory.logic.ts +++ b/apps/mobile/src/j5/connection/memory.logic.ts @@ -283,20 +283,3 @@ export function crewListWaiting( memory.get(thread.environmentId)?.spawned.get(thread.id) === undefined, ); } - -/** - * The names and settled reads screens may show. A server whose credential is in question (re-paired, - * its new connection not yet open) shows none, so its names read as on their way. - */ -export const heldNames = ( - memory: ConnectionMemory, - settled: SettledNames, - uncertain: ReadonlySet, -) => ({ - names: new Map( - [...memory].flatMap(([environmentId, connection]) => - uncertain.has(environmentId) ? [] : [[environmentId, connection.names] as const], - ), - ), - settled: new Map([...settled].filter(([environmentId]) => !uncertain.has(environmentId))), -}); diff --git a/apps/mobile/src/j5/connection/memory.ts b/apps/mobile/src/j5/connection/memory.ts index 5bf90b6da9b6a..db7b82b9d939f 100644 --- a/apps/mobile/src/j5/connection/memory.ts +++ b/apps/mobile/src/j5/connection/memory.ts @@ -2,12 +2,21 @@ import { participantIdentitiesFromResponse, type ParticipantIdentities, } from "@t3tools/client-runtime/j5/participant-identity"; +import { + CredentialStore, + credentialConnectionId, + EnvironmentRegistry, +} from "@t3tools/client-runtime/connection"; +import { createRuntimeCommand } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { File, Paths } from "expo-file-system"; +import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; +import * as SubscriptionRef from "effect/SubscriptionRef"; import { environmentCatalog } from "../../connection/catalog"; +import { connectionAtomRuntime } from "../../connection/runtime"; import { writeFileAtomically } from "../../lib/atomic-file"; import { appAtomRegistry } from "../../state/atom-registry"; import { environmentSession } from "../../state/session"; @@ -19,7 +28,6 @@ import { credentialKey, decodeMemory, encodeMemory, - heldNames, observeCredential, rememberIdentities, rememberSpawned, @@ -52,11 +60,11 @@ const loadSaved = (): ConnectionMemory => { type MemoryState = Omit; +const namesOf = (memory: ConnectionMemory) => + new Map([...memory].map(([environmentId, connection]) => [environmentId, connection.names])); + let state: MemoryState = { memory: loadSaved(), settled: new Map(), failedReads: new Set() }; -/** Servers re-paired or re-routed this launch whose new credential has not shown itself yet. */ -const uncertain = new Set(); -const heldState = () => heldNames(state.memory, state.settled, uncertain); -let snapshot: MemorySnapshot = { ...state, ...heldState() }; +let snapshot: MemorySnapshot = { ...state, names: namesOf(state.memory) }; const listeners = new Set<() => void>(); /** The credential each server's connection uses this launch. */ const credentials = new Map(); @@ -80,11 +88,11 @@ const scheduleSave = () => { const publish = (next: Partial) => { state = { ...state, ...next }; - const { names, settled } = heldState(); + const names = namesOf(state.memory); const sameNames = names.size === snapshot.names.size && [...names].every(([environmentId, known]) => snapshot.names.get(environmentId) === known); - snapshot = { ...state, settled, names: sameNames ? snapshot.names : names }; + snapshot = { ...state, names: sameNames ? snapshot.names : names }; if (next.memory !== undefined) scheduleSave(); listeners.forEach((listener) => listener()); }; @@ -95,16 +103,11 @@ const without = (map: ReadonlyMap, key: K) => { return next; }; -const preparedOf = (environmentId: EnvironmentId) => - Option.getOrNull( - appAtomRegistry.get(environmentSession.preparedConnectionValueAtom(environmentId)), - ); - const credentialKeysAtom = Atom.make((get) => { - const keys = new Map(); + const keys = new Map(); for (const id of get(environmentCatalog.catalogValueAtom).entries.keys()) { const prepared = Option.getOrNull(get(environmentSession.preparedConnectionValueAtom(id))); - if (prepared !== null) keys.set(id, { key: credentialKey(prepared), prepared }); + if (prepared !== null) keys.set(id, credentialKey(prepared)); } return keys; }).pipe(Atom.withLabel("mobile-j5:credential-keys")); @@ -130,55 +133,69 @@ const awaitNewAccess = (environmentIds: ReadonlyArray) => { appAtomRegistry.set(accessBaselinesAtom, baselines); }; -/** The prepared connection each uncertain server had when it became uncertain. */ -const preparedWhenUncertain = new Map(); +/** A server moves to a credential; a different one is another person, who starts with nothing. */ +const applyCredential = (environmentId: EnvironmentId, key: string) => { + const previous = credentials.get(environmentId); + if (previous === key) return; + credentials.set(environmentId, key); + const memory = observeCredential(state.memory, environmentId, key); + if (previous === undefined) { + if (memory !== state.memory) publish({ memory }); + return; + } + namesInFlight.delete(environmentId); + publish({ + memory, + settled: without(state.settled, environmentId), + failedReads: new Set([...state.failedReads].filter((id) => id !== environmentId)), + }); + awaitNewAccess([environmentId]); +}; // A missing key is a connection between attempts, which keeps its credential. appAtomRegistry.subscribe( credentialKeysAtom, - (keys) => { - let { memory, settled, failedReads } = state; - let settledUncertainty = false; - const changed: Array = []; - for (const [environmentId, { key, prepared }] of keys) { - if (uncertain.has(environmentId) && prepared !== preparedWhenUncertain.get(environmentId)) { - uncertain.delete(environmentId); - settledUncertainty = true; - } - const previous = credentials.get(environmentId); - if (previous === key) continue; - credentials.set(environmentId, key); - memory = observeCredential(memory, environmentId, key); - if (previous === undefined) continue; - changed.push(environmentId); - settled = without(settled, environmentId); - failedReads = new Set([...failedReads].filter((id) => id !== environmentId)); - namesInFlight.delete(environmentId); - } - if (memory !== state.memory || settledUncertainty) publish({ memory, settled, failedReads }); - awaitNewAccess(changed); - }, + (keys) => keys.forEach((key, environmentId) => applyCredential(environmentId, key)), { immediate: true }, ); +/** The credential a saved server's entry now pairs with, read from the device's store. */ +const storedCredentialKey = createRuntimeCommand(connectionAtomRuntime, { + label: "mobile-j5:stored-credential-key", + execute: Effect.fn("j5.connectionMemory.storedCredentialKey")(function* ( + environmentId: EnvironmentId, + ) { + const registry = yield* EnvironmentRegistry.EnvironmentRegistry; + const entry = (yield* SubscriptionRef.get(registry.entries)).get(environmentId); + if (entry?.target._tag !== "BearerConnectionTarget") return null; + const store = yield* CredentialStore.ConnectionCredentialStore; + const stored = yield* store.get(credentialConnectionId(entry.target.connectionId)); + return Option.match(stored, { + onNone: () => null, + onSome: (credential) => + credentialKey({ + httpAuthorization: { _tag: "Bearer", token: credential.token }, + target: entry.target, + }), + }); + }), +}); + const entries = new Map(); -// Re-pairing replaces a server's saved entry at once, while its new connection reports the -// credential only once it opens: until then, the last person's names and lineage are held back. +// Re-pairing stores a new token and replaces the server's entry at once, while its connection +// reports the credential only once it opens. A learned route replaces the entry but keeps the token. appAtomRegistry.subscribe( environmentCatalog.catalogValueAtom, (catalog) => { - const replaced: Array = []; for (const [environmentId, entry] of catalog.entries) { const previous = entries.get(environmentId); entries.set(environmentId, entry); if (previous === undefined || previous === entry) continue; - replaced.push(environmentId); - uncertain.add(environmentId); - preparedWhenUncertain.set(environmentId, preparedOf(environmentId)); + void storedCredentialKey.run(appAtomRegistry, environmentId).then((result) => { + if (result._tag === "Success" && result.value !== null) + applyCredential(environmentId, result.value); + }); } - if (replaced.length === 0) return; - publish({}); - awaitNewAccess(replaced); }, { immediate: true }, ); From bc9f048f0a8a6e1d2d02e5d0f529111429332562 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Fri, 20 Nov 2026 23:06:10 -0500 Subject: [PATCH 10/11] fix(mobile): a read that set out under the last person is refused after a re-pair Review on #1111: after a re-pair, a late report from the old connection could make the Owner's credential current again, and a name read still in flight under it would then land. Each credential change now issues a new ticket that reads carry out and hand back, so a key coming back never matches an older read. Failures to read or save the connection memory are now logged instead of swallowed, to find why an Android cold launch did not apply saved answers. Co-Authored-By: Claude Opus 5.5 --- .../src/j5/connection/memory.logic.test.ts | 20 +++++++++++ apps/mobile/src/j5/connection/memory.logic.ts | 25 ++++++++++++++ apps/mobile/src/j5/connection/memory.ts | 33 +++++++++++-------- apps/mobile/src/j5/crew/spawnedChildren.ts | 6 ++-- 4 files changed, 67 insertions(+), 17 deletions(-) diff --git a/apps/mobile/src/j5/connection/memory.logic.test.ts b/apps/mobile/src/j5/connection/memory.logic.test.ts index fc06f629f340a..20ef9d26be2f8 100644 --- a/apps/mobile/src/j5/connection/memory.logic.test.ts +++ b/apps/mobile/src/j5/connection/memory.logic.test.ts @@ -7,6 +7,7 @@ import { credentialMissingError } from "@t3tools/client-runtime/connection"; import { answeredSince, answerOnItsWay, + createCredentialTickets, credentialKey, crewListedThreads, crewListWaiting, @@ -227,6 +228,25 @@ describe("credentialKey", () => { }); }); +describe("createCredentialTickets", () => { + it("refuses a read that set out under the last person, even when a late report brings their key back", () => { + const tickets = createCredentialTickets(); + expect(tickets.move(server, owner)).toBeUndefined(); + // The Owner's name read sets out. + const ownerRead = tickets.current(server)!; + // The re-pair's stored token moves the server to the Viewer. + expect(tickets.move(server, viewer)?.key).toBe(owner); + // The old connection's late report names the Owner's credential again. + expect(tickets.move(server, owner)?.key).toBe(viewer); + // The Owner's read answers now: it is not taken, though the key matches. + expect(tickets.isCurrent(server, ownerRead)).toBe(false); + // A reconnect on the same credential issues nothing new, so a read in flight still lands. + const current = tickets.current(server)!; + expect(tickets.move(server, owner)).toBeNull(); + expect(tickets.isCurrent(server, current)).toBe(true); + }); +}); + describe("answeredSince", () => { it("waits for the access answer the new connection settles, even when it reuses the value", () => { const owner = { kind: "person", wide: true }; diff --git a/apps/mobile/src/j5/connection/memory.logic.ts b/apps/mobile/src/j5/connection/memory.logic.ts index fb61195b91cd3..b2ff07fd1b945 100644 --- a/apps/mobile/src/j5/connection/memory.logic.ts +++ b/apps/mobile/src/j5/connection/memory.logic.ts @@ -283,3 +283,28 @@ export function crewListWaiting( memory.get(thread.environmentId)?.spawned.get(thread.id) === undefined, ); } + +/** One server's credential as a read saw it when it set out. */ +export interface CredentialTicket { + readonly key: string; +} + +/** + * The credential each server uses this launch. Every change issues a new ticket, so a read that + * set out under an earlier one is refused even when a late report brings the same key back. + */ +export function createCredentialTickets() { + const tickets = new Map(); + return { + current: (environmentId: EnvironmentId) => tickets.get(environmentId) ?? null, + /** The previous ticket when the key changed, `undefined` when it is the first, null when unchanged. */ + move: (environmentId: EnvironmentId, key: string): CredentialTicket | undefined | null => { + const previous = tickets.get(environmentId); + if (previous?.key === key) return null; + tickets.set(environmentId, { key }); + return previous; + }, + isCurrent: (environmentId: EnvironmentId, ticket: CredentialTicket) => + tickets.get(environmentId) === ticket, + }; +} diff --git a/apps/mobile/src/j5/connection/memory.ts b/apps/mobile/src/j5/connection/memory.ts index db7b82b9d939f..81e0adfc15df0 100644 --- a/apps/mobile/src/j5/connection/memory.ts +++ b/apps/mobile/src/j5/connection/memory.ts @@ -25,6 +25,7 @@ import { j5Environment } from "../state"; import { answeredSince, answerOnItsWay, + createCredentialTickets, credentialKey, decodeMemory, encodeMemory, @@ -34,6 +35,7 @@ import { retainSpawned, settleNames, type ConnectionMemory, + type CredentialTicket, type SettledNames, } from "./memory.logic"; @@ -53,7 +55,8 @@ const loadSaved = (): ConnectionMemory => { try { const saved = file(); return decodeMemory(saved.exists ? saved.textSync() : null); - } catch { + } catch (cause) { + console.warn("J5 could not read its saved connection memory", cause); return decodeMemory(null); } }; @@ -66,8 +69,7 @@ const namesOf = (memory: ConnectionMemory) => let state: MemoryState = { memory: loadSaved(), settled: new Map(), failedReads: new Set() }; let snapshot: MemorySnapshot = { ...state, names: namesOf(state.memory) }; const listeners = new Set<() => void>(); -/** The credential each server's connection uses this launch. */ -const credentials = new Map(); +const tickets = createCredentialTickets(); /** The threads each server's lists asked about this launch; the saved file keeps only those. */ const asked = new Map>(); const namesInFlight = new Map>(); @@ -82,7 +84,9 @@ const scheduleSave = () => { const saved = new Set(appAtomRegistry.get(environmentCatalog.catalogValueAtom).entries.keys()); const memory = new Map([...state.memory].filter(([id]) => saved.has(id))); const contents = encodeMemory(retainSpawned(memory, asked)); - writing = writing.then(() => writeFileAtomically(file(), contents)).catch(() => undefined); + writing = writing + .then(() => writeFileAtomically(file(), contents)) + .catch((cause) => console.warn("J5 could not save its connection memory", cause)); }, 500); }; @@ -135,9 +139,8 @@ const awaitNewAccess = (environmentIds: ReadonlyArray) => { /** A server moves to a credential; a different one is another person, who starts with nothing. */ const applyCredential = (environmentId: EnvironmentId, key: string) => { - const previous = credentials.get(environmentId); - if (previous === key) return; - credentials.set(environmentId, key); + const previous = tickets.move(environmentId, key); + if (previous === null) return; const memory = observeCredential(state.memory, environmentId, key); if (previous === undefined) { if (memory !== state.memory) publish({ memory }); @@ -238,19 +241,21 @@ export const connectionMemory = { }; }, getSnapshot: () => snapshot, - credentialOf: (environmentId: EnvironmentId) => credentials.get(environmentId) ?? null, + /** The ticket a read carries out and hands back with its answer. */ + ticketOf: (environmentId: EnvironmentId) => tickets.current(environmentId), rememberSpawned: ( environmentId: EnvironmentId, - credential: string, + ticket: CredentialTicket, requested: ReadonlyArray, spawnedByAgent: ReadonlyArray, ) => { + if (!tickets.isCurrent(environmentId, ticket)) return; const listed = asked.get(environmentId) ?? new Set(); for (const threadId of requested) listed.add(threadId); asked.set(environmentId, listed); publish({ - memory: rememberSpawned(state.memory, environmentId, credential, requested, spawnedByAgent), + memory: rememberSpawned(state.memory, environmentId, ticket.key, requested, spawnedByAgent), failedReads: new Set([...state.failedReads].filter((id) => id !== environmentId)), }); }, @@ -265,8 +270,8 @@ export const connectionMemory = { * change after a spawn. The remembered names stay shown meanwhile. */ readNames: async (environmentId: EnvironmentId, participantIds: ReadonlyArray) => { - const credential = credentials.get(environmentId); - if (credential === undefined) return; + const ticket = tickets.current(environmentId); + if (ticket === null) return; const inFlight = namesInFlight.get(environmentId) ?? new Set(); const ids = [...new Set(participantIds)].filter((id) => !inFlight.has(id)); if (ids.length === 0) return; @@ -277,7 +282,7 @@ export const connectionMemory = { environmentId, input: { participantIds: ids }, }); - if (credentials.get(environmentId) !== credential) return; + if (!tickets.isCurrent(environmentId, ticket)) return; // A failed read still settles, so its senders fall back to a stand-in until the next one. const settled = settleNames(state.settled, environmentId, ids); if (result._tag === "Failure") return publish({ settled }); @@ -285,7 +290,7 @@ export const connectionMemory = { memory: rememberIdentities( state.memory, environmentId, - credential, + ticket.key, ids, participantIdentitiesFromResponse(environmentId, result.value), ), diff --git a/apps/mobile/src/j5/crew/spawnedChildren.ts b/apps/mobile/src/j5/crew/spawnedChildren.ts index 46c021e0ca628..0119f520e24c4 100644 --- a/apps/mobile/src/j5/crew/spawnedChildren.ts +++ b/apps/mobile/src/j5/crew/spawnedChildren.ts @@ -26,7 +26,7 @@ import { j5Environment } from "../state"; const store = createScopedThreadReadStore({ load: async (environmentId, threadIds) => { - const credential = connectionMemory.credentialOf(environmentId); + const ticket = connectionMemory.ticketOf(environmentId); const result = await j5Environment.listSpawnedChildren.run(appAtomRegistry, { environmentId, input: { threadIds }, @@ -35,10 +35,10 @@ const store = createScopedThreadReadStore Date: Fri, 20 Nov 2026 23:48:45 -0500 Subject: [PATCH 11/11] fix(mobile): a narrower person's sender link waits for their own thread list Review on #1111: after re-pairing as a Viewer, the Captain's author line was a link for up to about 3 s, because the device's thread list still held the Owner's threads until the resync finished. A narrower person's sender now links only once that server's thread list is live for this connection; until then the name shows as plain text, as it settles. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/j5/a2a/timelinePresentation.test.ts | 9 +++++++++ apps/mobile/src/j5/a2a/timelinePresentation.ts | 8 +++++--- apps/mobile/src/j5/a2a/timelineState.ts | 3 +++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/j5/a2a/timelinePresentation.test.ts b/apps/mobile/src/j5/a2a/timelinePresentation.test.ts index cbc90d80bbe5b..ea28a1eeeb421 100644 --- a/apps/mobile/src/j5/a2a/timelinePresentation.test.ts +++ b/apps/mobile/src/j5/a2a/timelinePresentation.test.ts @@ -25,6 +25,7 @@ const timeline = (viewerParticipantId: string | null): J5Timeline => ({ pending: new Set(), accessConfirmed: true, narrow: false, + threadListLive: true, sharedAuthors: new Map(), }); @@ -305,4 +306,12 @@ describe("j5TimelineSenderRef", () => { it("names no sender thread until the server says who the new person is", () => { expect(sender({ accessConfirmed: false })).toBeNull(); }); + + it("links a narrower person's sender only once the thread list was read for them", () => { + const named = { environmentId: here, threadId: ThreadId.make("thread-captain") }; + const threads = new Map([["agent:captain", named]]); + // Re-paired as a Viewer, the list still holds the Owner's threads while it resyncs. + expect(sender({ narrow: true, threads, threadListLive: false })).toBeNull(); + expect(sender({ narrow: true, threads, threadListLive: true })).toEqual(named); + }); }); diff --git a/apps/mobile/src/j5/a2a/timelinePresentation.ts b/apps/mobile/src/j5/a2a/timelinePresentation.ts index 4e44b87fabab5..6249e11399181 100644 --- a/apps/mobile/src/j5/a2a/timelinePresentation.ts +++ b/apps/mobile/src/j5/a2a/timelinePresentation.ts @@ -31,6 +31,8 @@ export interface J5Timeline extends ParticipantIdentities { readonly accessConfirmed: boolean; /** The person reaches less than the whole server. */ readonly narrow: boolean; + /** The server's thread list was read over this connection, not kept from an earlier one. */ + readonly threadListLive: boolean; readonly environmentId: EnvironmentId; readonly viewerParticipantId: string | null; readonly sharedAuthors: ReadonlyMap; @@ -145,8 +147,8 @@ export function presentJ5TimelineNotice( /** * The thread a letter's sender works in, as far as this person may know it. A narrower person - * gets only what the server's identity read names for them: the letter's own thread id would be - * looked up in a thread list that can still hold the last person's threads after a re-pair. + * gets only what the server's identity read names for them, and only once the thread list is + * live: until then it can still hold the last person's threads after a re-pair. */ export function j5TimelineSenderRef( message: J5UserMessageInput & { readonly senderThreadId?: string | undefined }, @@ -155,7 +157,7 @@ export function j5TimelineSenderRef( ) { if (presentation?.group !== "participant" || !timeline.accessConfirmed) return null; if (timeline.narrow) - return presentation.senderId === null + return presentation.senderId === null || !timeline.threadListLive ? null : (timeline.threads.get(presentation.senderId) ?? null); return j5SenderThreadRef({ diff --git a/apps/mobile/src/j5/a2a/timelineState.ts b/apps/mobile/src/j5/a2a/timelineState.ts index 59836a5418107..13d43b2fe9e21 100644 --- a/apps/mobile/src/j5/a2a/timelineState.ts +++ b/apps/mobile/src/j5/a2a/timelineState.ts @@ -5,6 +5,7 @@ import { } from "@t3tools/client-runtime/j5/user-message"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { environmentShell } from "../../state/shell"; import { accessConfirmedAtom } from "../connection/memory"; import { j5Sharing } from "../sharing/guestAccess"; import { useThreadAuthorIndex } from "../sharing/sharedConversation"; @@ -20,6 +21,7 @@ export function useJ5Timeline( const access = useAtomValue(j5Sharing.connectionAccess(environmentId)); const accessConfirmed = useAtomValue(accessConfirmedAtom(environmentId)); const narrow = useAtomValue(j5Sharing.isNarrow(environmentId)); + const threadListLive = useAtomValue(environmentShell.statusAtom(environmentId)) === "live"; const { authors } = useThreadAuthorIndex(environmentId, threadId); const identities = useParticipantIdentities( environmentId, @@ -29,6 +31,7 @@ export function useJ5Timeline( ...identities, accessConfirmed, narrow, + threadListLive, environmentId, viewerParticipantId: access?.kind === "person" ? access.personId : null, sharedAuthors: authors,