The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 19:45 UTC
fix(mobile): the thread list no longer reshuffles once per environment on startup (#34596)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Theo Browne committed
Nov 12, 2026 at 04:05 UTC
65c0195b46817a7b04e8765522f72ee08a7430f8
18 files changed
+803
-61
apps/mobile/src/App.tsx
+21
-6
@@ -4,7 +4,7 @@ import { installThreadOutboxDelivery } from "./state/threadOutboxDelivery";
4
import * as Linking from "expo-linking";
5
import * as SplashScreen from "expo-splash-screen";
6
import { requireNativeModule } from "expo";
7
-import { useEffect } from "react";
7
+import { useEffect, useState } from "react";
8
import { Platform, StatusBar } from "react-native";
9
import { GestureHandlerRootView } from "react-native-gesture-handler";
10
import { KeyboardProvider } from "react-native-keyboard-controller";
@@ -21,7 +21,7 @@ import {
21
import { pipe } from "effect/Function";
22
import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
23
24
-import { RegistryContext } from "@effect/atom-react";
24
+import { RegistryContext, useAtomValue } from "@effect/atom-react";
25
import { ProjectChipIconRasterizer } from "./native/ProjectChipIconImages";
26
import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet";
27
import * as Dialog from "./components/ui/Dialog";
@@ -50,7 +50,7 @@ import { RootStack, rootPathnameFromState, workspaceLocationFromState } from "./
50
import { appAtomRegistry } from "./state/atom-registry";
51
import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts";
52
import { environmentThreadShells, threadEnvironment } from "./state/threads";
53
-import { environmentShell } from "./state/shell";
53
+import { environmentShell, shellCachesReadAtom } from "./state/shell";
54
import { OverlayPortalHost } from "./components/ui/OverlayPortal";
55
import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
56
import { hasCloudPublicConfig } from "./features/cloud/publicConfig";
@@ -204,13 +204,28 @@ disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.ho
204
for (const dispose of appServiceDisposers) dispose();
205
});
206
207
+// Cached shells are local reads that end in a fraction of this time; the limit only keeps a
208
+// failed read from holding the splash screen.
209
+const SPLASH_SHELL_CACHE_WAIT_MS = 1_500;
210
+
211
function SplashScreenCoordinator() {
212
const { isReady } = useAppearancePreferences();
213
+ const shellCachesRead = useAtomValue(shellCachesReadAtom);
214
+ const [waitEnded, setWaitEnded] = useState(false);
215
+
216
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the limit on how long the native splash screen waits for cached shells
217
+ useEffect(() => {
218
+ const timer = setTimeout(() => setWaitEnded(true), SPLASH_SHELL_CACHE_WAIT_MS);
219
+ return () => clearTimeout(timer);
220
+ }, []);
221
210
- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hides the native splash screen once appearance preferences have loaded
222
+ // The thread list paints every environment's cached rows at once when the splash hides
223
+ // after they are read.
224
+ const canHide = isReady && (shellCachesRead || waitEnded);
225
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hides the native splash screen once preferences and cached shells have loaded
226
useEffect(() => {
212
- if (isReady) void SplashScreen.hide();
213
- }, [isReady]);
227
+ if (canHide) void SplashScreen.hide();
228
+ }, [canHide]);
229
230
return null;
231
}
apps/mobile/src/features/home/HomeRouteScreen.tsx
+2
-2
@@ -15,7 +15,7 @@ import {
15
} from "@t3tools/client-runtime/state/project-grouping";
16
17
import { useProjects } from "../../state/entities";
18
-import { environmentThreadShells } from "../../state/threads";
18
+import { steadyNavigationThreadShellsAtom } from "../../state/threads";
19
import { useLaunchingThreads, usePendingNewTasks } from "../../state/use-pending-new-tasks";
20
import { useWorkspaceState } from "../../state/workspace";
21
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
@@ -47,7 +47,7 @@ export function HomeRouteScreen() {
47
// Stop rebuilding the streaming thread list while Thread covers Home.
48
const visible = useHomeRouteVisible();
49
const threads = useLaunchingThreads(
50
- useAtomValueWhileVisible(environmentThreadShells.navigationThreadShellsAtom, visible),
50
+ useAtomValueWhileVisible(steadyNavigationThreadShellsAtom, visible),
51
);
52
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
53
const { savedConnectionsById } = useSavedRemoteConnections();
apps/mobile/src/features/home/useThreadListActions.test.ts
+55
-22
@@ -16,6 +16,7 @@ const state = vi.hoisted(() => ({
16
connectedEnvironmentIds: [] as EnvironmentId[],
17
pendingOrder: null as object | null,
18
dropBusy: false,
19
+ holdingRows: false,
20
failedAction: null as string | null,
21
archivedRefreshes: [] as string[],
22
scopes: new Map<string, Set<string>>(),
@@ -78,26 +79,28 @@ vi.mock("../../state/atom-registry", () => ({
79
? state.connectedEnvironmentIds
80
: atom === "thread-drop-busy"
81
? state.dropBusy
81
- : atom === "thread-shells"
82
- ? state.shells
83
- : atom === "queued-thread-keys"
84
- ? new Set<string>()
85
- : new Map(
86
- [...state.scopes.keys()].map((environmentId) => [
87
- environmentId,
88
- {
89
- environment: {
90
- capabilities: {
91
- threadSettlement: true,
92
- threadSnooze: true,
93
- threadPinning: true,
94
- threadPinReorder: true,
95
- threadTitleRegeneration: true,
82
+ : atom === "steady-shells-holding"
83
+ ? state.holdingRows
84
+ : atom === "thread-shells"
85
+ ? state.shells
86
+ : atom === "queued-thread-keys"
87
+ ? new Set<string>()
88
+ : new Map(
89
+ [...state.scopes.keys()].map((environmentId) => [
90
+ environmentId,
91
+ {
92
+ environment: {
93
+ capabilities: {
94
+ threadSettlement: true,
95
+ threadSnooze: true,
96
+ threadPinning: true,
97
+ threadPinReorder: true,
98
+ threadTitleRegeneration: true,
99
+ },
100
},
101
},
98
- },
99
- ]),
100
- ),
102
+ ]),
103
+ ),
104
},
105
}));
106
vi.mock("../../state/use-atom-command", () => ({
@@ -121,10 +124,9 @@ vi.mock("../../state/thread-order", () => ({
124
},
125
}));
126
vi.mock("../../state/threads", () => ({
124
- environmentThreadShells: {
125
- threadShellsAtom: "thread-shells",
126
- navigationThreadShellsAtom: "thread-shells",
127
- },
127
+ environmentThreadShells: { threadShellsAtom: "thread-shells" },
128
+ steadyNavigationThreadShellsAtom: "thread-shells",
129
+ steadyShellsHoldingAtom: "steady-shells-holding",
130
threadEnvironment: Object.fromEntries(
131
[
132
"archive",
@@ -193,6 +195,7 @@ beforeEach(() => {
195
state.archivedRefreshes = [];
196
state.pendingOrder = null;
197
state.dropBusy = false;
198
+ state.holdingRows = false;
199
state.scopes = new Map([
200
[primaryEnvironmentId, new Set([AuthOrchestrationOperateScope])],
201
[otherEnvironmentId, new Set<string>()],
@@ -274,6 +277,12 @@ describe("pinned thread operation permissions", () => {
277
}),
278
];
279
280
+ // Rows that wait to show can hold order keys the server has replaced.
281
+ state.holdingRows = true;
282
+ expect(await useThreadListActions().moveThread(moved, "up")).toBe(false);
283
+ expect(state.requests).toEqual([]);
284
+ state.holdingRows = false;
285
+
286
expect(await useThreadListActions().moveThread(moved, "up")).toBe(true);
287
expect(state.requests).toEqual([
288
expect.objectContaining({ action: "reorderPin", environmentId: primaryEnvironmentId }),
@@ -494,6 +503,25 @@ describe("thread action undo", () => {
503
},
504
);
505
506
+ it.each(["settleThread", "unpinThread"] as const)(
507
+ "%s plans its undo from the live row when the list holds an older one",
508
+ async (handler) => {
509
+ const held = makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z", pinOrderKey: "m" });
510
+ const live = makeThread({
511
+ pinnedAt: "2026-09-02T00:00:00.000Z",
512
+ pinOrderKey: "t",
513
+ snoozedUntil: "2099-01-01T09:00:00.000Z",
514
+ });
515
+ state.shells = [live];
516
+ await useThreadListActions()[handler](held);
517
+ await readThreadUndoNotice()!.undo();
518
+ expect(state.requests.slice(-2)).toMatchObject([
519
+ { action: "pin", input: { threadId: live.id, orderKey: "t" } },
520
+ { action: "snooze", input: { threadId: live.id, snoozedUntil: live.snoozedUntil } },
521
+ ]);
522
+ },
523
+ );
524
+
525
// regression: #21401 restore archive and thread action undo
526
it("does not restore snooze if undoing an unpin fails", async () => {
527
const thread = makeThread({
@@ -570,5 +598,10 @@ describe("thread archive guard", () => {
598
expect(state.requests).toEqual([]);
599
expect(state.archivedRefreshes).toEqual([]);
600
expect(state.alerts.at(-1)?.title).toBe("Could not archive thread");
601
+
602
+ // A list can hold a row from before the run started.
603
+ state.shells = [thread];
604
+ expect(await useThreadListActions().archiveThread(makeThread())).toBe(false);
605
+ expect(state.requests).toEqual([]);
606
});
607
});
apps/mobile/src/features/home/useThreadListActions.ts
+35
-13
@@ -17,7 +17,12 @@ import { appAtomRegistry } from "../../state/atom-registry";
17
import { environmentServerConfigsAtom } from "../../state/server";
18
import { connectedEnvironmentIdsAtom } from "../../state/presentation";
19
import { readEnvironmentScope } from "../../state/session";
20
-import { environmentThreadShells, threadEnvironment } from "../../state/threads";
20
+import {
21
+ environmentThreadShells,
22
+ steadyNavigationThreadShellsAtom,
23
+ steadyShellsHoldingAtom,
24
+ threadEnvironment,
25
+} from "../../state/threads";
26
import { queuedThreadKeysAtom } from "../../state/use-thread-outbox";
27
import { useAtomCommand } from "../../state/use-atom-command";
28
import {
@@ -83,6 +88,19 @@ function checkThreadOperationPermission(thread: EnvironmentThreadShell, title: s
88
return false;
89
}
90
91
+/**
92
+ * The live row of a thread that a list passes to an action. A list holds its rows while an
93
+ * environment synchronizes (`steadyNavigationThreadShellsAtom`), so its row can be older than
94
+ * the client's data: an undo plan or a guard read from it would use replaced state.
95
+ */
96
+function liveThread(thread: EnvironmentThreadShell): EnvironmentThreadShell {
97
+ return (
98
+ appAtomRegistry
99
+ .get(environmentThreadShells.threadShellsAtom)
100
+ .find((row) => row.id === thread.id && row.environmentId === thread.environmentId) ?? thread
101
+ );
102
+}
103
+
104
function useThreadActionExecutor(
105
onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void,
106
) {
@@ -572,7 +590,10 @@ export function useThreadListActions(): {
590
const moveThread = async (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {
591
if (!checkThreadOperationPermission(thread, "Could not move thread")) return false;
592
if (getPendingThreadOrder() !== null || appAtomRegistry.get(threadDropBusyAtom)) return false;
575
- const shells = appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom);
593
+ // The rows on screen can be older than the server's while they wait to show. A move
594
+ // planned from them could act on a pin or an order key that the server has replaced.
595
+ if (appAtomRegistry.get(steadyShellsHoldingAtom)) return false;
596
+ const shells = appAtomRegistry.get(steadyNavigationThreadShellsAtom);
597
const current = shells.find(
598
(row) => row.id === thread.id && row.environmentId === thread.environmentId,
599
);
@@ -708,19 +729,20 @@ export function useThreadListActions(): {
729
const confirmDeleteThread = (thread: EnvironmentThreadShell) =>
730
confirmThreadDeletion(executeAction, thread);
731
732
+ // `moveThread` looks up its own row, and refuses while a list holds older rows.
733
return {
712
- archiveThread,
713
- confirmDeleteThread,
714
- settleThread,
715
- snoozeThread,
716
- unsnoozeThread,
717
- unsettleThread,
718
- pinThread,
719
- unpinThread,
720
- setThreadAutoSettle,
734
+ archiveThread: (thread) => archiveThread(liveThread(thread)),
735
+ confirmDeleteThread: (thread) => confirmDeleteThread(liveThread(thread)),
736
+ settleThread: (thread) => settleThread(liveThread(thread)),
737
+ snoozeThread: (thread, snoozedUntil) => snoozeThread(liveThread(thread), snoozedUntil),
738
+ unsnoozeThread: (thread) => unsnoozeThread(liveThread(thread)),
739
+ unsettleThread: (thread) => unsettleThread(liveThread(thread)),
740
+ pinThread: (thread) => pinThread(liveThread(thread)),
741
+ unpinThread: (thread) => unpinThread(liveThread(thread)),
742
+ setThreadAutoSettle: (thread, enabled) => setThreadAutoSettle(liveThread(thread), enabled),
743
moveThread,
722
- renameThread,
723
- regenerateThreadTitle,
744
+ renameThread: (thread) => renameThread(liveThread(thread)),
745
+ regenerateThreadTitle: (thread) => regenerateThreadTitle(liveThread(thread)),
746
};
747
}
748
apps/mobile/src/features/threads/ThreadArrangementSheet.tsx
+4
-2
@@ -18,7 +18,7 @@ import { scopedThreadKey } from "../../lib/scopedEntities";
18
import { deriveThreadArrangementSizing } from "../../lib/layout";
19
import { environmentServerConfigsAtom } from "../../state/server";
20
import { threadListEnvironmentsAtom } from "../../state/presentation";
21
-import { environmentThreadShells } from "../../state/threads";
21
+import { steadyNavigationThreadShellsAtom, steadyShellsHoldingAtom } from "../../state/threads";
22
import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort";
23
import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../../state/olderSettledShelf";
24
import {
@@ -170,12 +170,13 @@ function ThreadArrangementSheet(props: { onClose: () => void }) {
170
baseFontSize: appearance.baseFontSize,
171
fontScale,
172
});
173
- const threads = useAtomValue(environmentThreadShells.navigationThreadShellsAtom);
173
+ const threads = useAtomValue(steadyNavigationThreadShellsAtom);
174
const configs = useAtomValue(environmentServerConfigsAtom);
175
const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
176
const queuedThreadKeys = useAtomValue(queuedThreadKeysAtom);
177
const pendingOrder = useAtomValue(pendingThreadOrderAtom);
178
const dropBusy = useAtomValue(threadDropBusyAtom);
179
+ const holdingRows = useAtomValue(steadyShellsHoldingAtom);
180
const { moveThread } = useThreadListActions();
181
const { workingShelfEnabled } = useThreadListV2ShelfPreferences();
182
const now = useThreadListNow(threads);
@@ -489,6 +490,7 @@ function ThreadArrangementSheet(props: { onClose: () => void }) {
490
disabled={
491
dropBusy ||
492
pendingOrder !== null ||
493
+ holdingRows ||
494
(!listEnvironments.pinReorderEnvironmentIds.has(
495
thread.environmentId,
496
) &&
apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+3
-2
@@ -27,7 +27,8 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
27
import { AppText as Text } from "../../components/ui/AppText";
28
import { Button } from "../../components/ui/Button";
29
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
30
-import { useProjects, useNavigationThreadShells } from "../../state/entities";
30
+import { useProjects } from "../../state/entities";
31
+import { steadyNavigationThreadShellsAtom } from "../../state/threads";
32
import { useThreadSearch } from "../../state/queries";
33
import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
34
import { useThreadListNow } from "./use-thread-list-now";
@@ -121,7 +122,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
122
const insets = useSafeAreaInsets();
123
const { fabClearance, fabSize } = useAndroidControlSizing();
124
const projects = useProjects();
124
- const threads = useNavigationThreadShells();
125
+ const threads = useAtomValue(steadyNavigationThreadShellsAtom);
126
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
127
const { savedConnectionsById } = useSavedRemoteConnections();
128
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
apps/mobile/src/state/shell.ts
+20
@@ -1,3 +1,4 @@
1
+import { enabledEnvironmentIds } from "@t3tools/client-runtime/state/connections";
2
import {
3
createEnvironmentShellAtoms,
4
createEnvironmentShellSummaryAtom,
@@ -27,6 +28,25 @@ const shellHasError = (state: EnvironmentShellState) => Option.isSome(state.erro
28
// The empty placeholder stands until the environment has read its cached shell.
29
const shellCacheRead = (state: EnvironmentShellState) => state !== EMPTY_SHELL_STATE;
30
31
+const shellCacheReadAtom = Atom.family((environmentId: EnvironmentId) =>
32
+ Atom.make((get) => shellCacheRead(get(environmentShell.stateValueAtom(environmentId)))),
33
+);
34
+
35
+/**
36
+ * True once every enabled environment has read its cached shell. A list that paints before
37
+ * then gets the cached rows of one environment at a time.
38
+ */
39
+export const shellCachesReadAtom = Atom.make((get) => {
40
+ const catalog = get(environmentCatalog.catalogValueAtom);
41
+ if (!catalog.isReady) return false;
42
+ // Reads every environment, so each one loads its cache now and not after the one before it.
43
+ let allRead = true;
44
+ for (const environmentId of enabledEnvironmentIds(catalog)) {
45
+ if (!get(shellCacheReadAtom(environmentId))) allRead = false;
46
+ }
47
+ return allRead;
48
+}).pipe(Atom.withLabel("mobile-shell-caches-read"));
49
+
50
export function useEnvironmentShellReadiness(environmentId: EnvironmentId | null) {
51
const atom =
52
environmentId === null
apps/mobile/src/state/thread-order.test.ts
+3
-3
@@ -12,7 +12,7 @@ import {
12
pendingThreadOrderAtom,
13
} from "./thread-order";
14
import { environmentServerConfigsAtom } from "./server";
15
-import { environmentThreadShells } from "./threads";
15
+import { steadyNavigationThreadShellsAtom } from "./threads";
16
17
vi.mock("./atom-registry", async () => {
18
const { AtomRegistry } = await import("effect/reactivity");
@@ -21,7 +21,7 @@ vi.mock("./atom-registry", async () => {
21
vi.mock("./threads", async () => {
22
const { Atom } = await import("effect/reactivity");
23
return {
24
- environmentThreadShells: { navigationThreadShellsAtom: Atom.make([]).pipe(Atom.keepAlive) },
24
+ steadyNavigationThreadShellsAtom: Atom.make([]).pipe(Atom.keepAlive),
25
};
26
});
27
vi.mock("./server", async () => {
@@ -36,7 +36,7 @@ vi.mock("./use-thread-outbox", async () => {
36
type ServerConfigs = Atom.Type<typeof environmentServerConfigsAtom>;
37
type ServerConfig = ServerConfigs extends ReadonlyMap<EnvironmentId, infer Config> ? Config : never;
38
const configsAtom = environmentServerConfigsAtom as Atom.Writable<ServerConfigs, ServerConfigs>;
39
-const shellsAtom = environmentThreadShells.navigationThreadShellsAtom as Atom.Writable<
39
+const shellsAtom = steadyNavigationThreadShellsAtom as Atom.Writable<
40
readonly EnvironmentThreadShell[],
41
readonly EnvironmentThreadShell[]
42
>;
apps/mobile/src/state/thread-order.ts
+4
-9
@@ -12,7 +12,7 @@ import {
12
} from "../features/threads/threadListV2";
13
import { appAtomRegistry } from "./atom-registry";
14
import { environmentServerConfigsAtom } from "./server";
15
-import { environmentThreadShells } from "./threads";
15
+import { steadyNavigationThreadShellsAtom } from "./threads";
16
import { queuedThreadKeysAtom } from "./use-thread-outbox";
17
18
export const threadArrangementOpenAtom = Atom.make(false).pipe(Atom.keepAlive);
@@ -64,7 +64,7 @@ export function beginPendingThreadOrder(pending: PendingThreadOrder) {
64
const current = appAtomRegistry.get(pendingThreadOrderAtom);
65
if (current === null) return;
66
const configs = appAtomRegistry.get(environmentServerConfigsAtom);
67
- const threads = appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom);
67
+ const threads = appAtomRegistry.get(steadyNavigationThreadShellsAtom);
68
const nowMs = Date.now();
69
const ordered = getThreadListV2OrderedSection({
70
threads,
@@ -87,17 +87,12 @@ export function beginPendingThreadOrder(pending: PendingThreadOrder) {
87
teardownPendingOrder = teardown;
88
appAtomRegistry.set(pendingThreadOrderAtom, pending);
89
unsubscribers.push(
90
- appAtomRegistry.subscribe(environmentThreadShells.navigationThreadShellsAtom, refresh),
90
+ appAtomRegistry.subscribe(steadyNavigationThreadShellsAtom, refresh),
91
appAtomRegistry.subscribe(environmentServerConfigsAtom, refresh),
92
appAtomRegistry.subscribe(queuedThreadKeysAtom, refresh),
93
minuteTick.subscribe(refresh),
94
);
95
- armWake(
96
- nextSnoozeWakeAfter(
97
- appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom),
98
- Date.now(),
99
- ),
100
- );
95
+ armWake(nextSnoozeWakeAfter(appAtomRegistry.get(steadyNavigationThreadShellsAtom), Date.now()));
96
return {
97
isPending: () => {
98
refresh();
apps/mobile/src/state/threads.ts
+18
@@ -10,6 +10,7 @@ import {
10
createThreadEnvironmentAtoms,
11
createThreadFamilyAtoms,
12
} from "@t3tools/client-runtime/state/threads";
13
+import { createSteadyShellAtoms } from "@t3tools/client-runtime/state/shell";
14
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
15
import { AsyncResult, Atom } from "effect/reactivity";
16
@@ -46,6 +47,23 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({
47
snapshotAtom: threadEnvironment.snapshotAtom,
48
hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom,
49
});
50
+const steadyShells = createSteadyShellAtoms({
51
+ catalogValueAtom: environmentCatalog.catalogValueAtom,
52
+ snapshotAtom: threadEnvironment.snapshotAtom,
53
+ shellStateAtom: environmentShell.stateValueAtom,
54
+ rowActionsAtom: threadEnvironment.rowActionsAtom,
55
+ connectionStateAtom: environmentCatalog.stateAtom,
56
+});
57
+/**
58
+ * The threads that lists arrange. Rows wait while their environment synchronizes, so a list
59
+ * changes once when environments connect, not once per environment.
60
+ */
61
+export const steadyShellsHoldingAtom = steadyShells.holdingAtom;
62
+export const steadyNavigationThreadShellsAtom = createEnvironmentThreadShellAtoms({
63
+ catalogValueAtom: environmentCatalog.catalogValueAtom,
64
+ snapshotAtom: steadyShells.snapshotAtom,
65
+ hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom,
66
+}).navigationThreadShellsAtom;
67
export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({
68
childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom,
69
pendingRequestsAtom: environmentThreadDetails.pendingRequestsAtom,
docs/internals/connection-runtime.md
+20
@@ -75,6 +75,26 @@ connection nor overwrite newer live data during a reconnect. Loading and
75
resuming snapshots belongs to the shared state services, so every view agrees
76
on which data is current.
77
78
+Each environment synchronizes at its own time, so a thread list that follows every
79
+snapshot moves once per environment on each cold start and resume. Mobile lists read
80
+[steady shells](../../packages/client-runtime/src/state/steadyShells.ts): an
81
+environment's rows stay as shown until its connection's server snapshot arrives,
82
+it is synchronized, or it disconnects, and environments that get there within two
83
+seconds of each other show together. Only an environment that is connected or on
84
+its first attempt, and still owes its snapshot, is waited for; a retry can take
85
+minutes. A move in a list is refused while its rows wait, because its plan would
86
+use order keys the server may have replaced. Every other row action looks up the
87
+live row before it reads thread state, so an undo plan or a guard never uses a held
88
+row. The hold stops only changes the user
89
+did not cause: a command that moves or removes a row (settle, snooze, pin, archive,
90
+delete, and their reverses) makes that environment's rows follow the live snapshot
91
+until it is live. Point reads (a
92
+thread's own shell, route checks) keep the live snapshot, where a row the server just
93
+sent must not look missing. The decision reads the snapshot's own sequence: a second
94
+atom derived from the same shell state can be one update behind the rows. The mobile
95
+splash screen also waits, for a bounded time, until every enabled environment has
96
+read its cached shell, so the first frame holds all cached rows.
97
+
98
Shell snapshots can leave rows out when the client asks. Servers that advertise
99
`shellThreadFamilies` leave out idle subagent children: a child stays while it
100
has a live or queued run, a pending request or background work, or a subagent
packages/client-runtime/src/state/shell.ts
+1
@@ -719,3 +719,4 @@ export * from "./shellReducer.ts";
719
export * from "./shellPullRequests.ts";
720
export * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
721
export * from "./snapshots.ts";
722
+export * from "./steadyShells.ts";
packages/client-runtime/src/state/steadyShells.test.ts
new
+338
@@ -0,0 +1,338 @@
1
+import { EnvironmentId, type OrchestrationV2ShellSnapshot } from "@t3tools/contracts";
2
+import * as Option from "effect/Option";
3
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
4
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5
+
6
+import {
7
+ AVAILABLE_CONNECTION_STATE,
8
+ PrimaryConnectionTarget,
9
+ type SupervisorConnectionState,
10
+} from "../connection/model.ts";
11
+import type { EnvironmentCatalogState } from "./connections.ts";
12
+import { v2ShellSnapshot } from "./orchestrationV2TestFixtures.ts";
13
+import { EMPTY_SHELL_STATE, type EnvironmentShellState } from "./shell.ts";
14
+import {
15
+ createSteadyShellAtoms,
16
+ EMPTY_STEADY_SHELLS_STATE,
17
+ stepSteadyShells,
18
+ type SteadyShellInput,
19
+ type SteadyShellsState,
20
+} from "./steadyShells.ts";
21
+
22
+const A = EnvironmentId.make("a");
23
+const B = EnvironmentId.make("b");
24
+const WINDOW = 2_000;
25
+
26
+const snapshot = (snapshotSequence: number): OrchestrationV2ShellSnapshot => ({
27
+ ...v2ShellSnapshot,
28
+ snapshotSequence,
29
+});
30
+const shell = (
31
+ environmentId: EnvironmentId,
32
+ value: OrchestrationV2ShellSnapshot | null,
33
+ phase: "connecting" | "disconnected" | "live",
34
+ generation = 0,
35
+ rowActions = 0,
36
+): SteadyShellInput => ({
37
+ environmentId,
38
+ snapshot: value,
39
+ serverSequence: value?.snapshotSequence ?? null,
40
+ status: phase === "live" ? "live" : phase === "connecting" ? "synchronizing" : "cached",
41
+ generation,
42
+ connecting: phase !== "disconnected",
43
+ rowActions,
44
+});
45
+const shown = (state: SteadyShellsState, environmentId: EnvironmentId) =>
46
+ state.shells.get(environmentId)?.shown;
47
+
48
+describe("stepSteadyShells", () => {
49
+ it("shows cached rows at once and holds server rows until the environment is synchronized", () => {
50
+ const cached = snapshot(7);
51
+ const withLinks = { ...cached };
52
+ const fromServer = snapshot(9);
53
+ let state = stepSteadyShells(EMPTY_STEADY_SHELLS_STATE, [shell(A, cached, "connecting")], 0);
54
+ expect(shown(state, A)).toBe(cached);
55
+
56
+ // The cached links fill in without new server data.
57
+ state = stepSteadyShells(state, [shell(A, withLinks, "connecting")], 10);
58
+ expect(shown(state, A)).toBe(withLinks);
59
+
60
+ state = stepSteadyShells(state, [shell(A, fromServer, "connecting")], 20);
61
+ expect(shown(state, A)).toBe(withLinks);
62
+
63
+ state = stepSteadyShells(state, [shell(A, fromServer, "live")], 30);
64
+ expect(shown(state, A)).toBe(fromServer);
65
+ expect(state.releaseAt).toBeNull();
66
+ });
67
+
68
+ it("shows a connection's server snapshot when it arrives, and the events after it when live", () => {
69
+ const [cached, fromServer, withEvents] = [snapshot(7), snapshot(9), snapshot(10)];
70
+ let state = stepSteadyShells(EMPTY_STEADY_SHELLS_STATE, [shell(A, cached, "connecting")], 0);
71
+ state = stepSteadyShells(state, [shell(A, fromServer, "connecting", 1)], 10);
72
+ expect(shown(state, A)).toBe(fromServer);
73
+ state = stepSteadyShells(state, [shell(A, withEvents, "connecting", 1)], 20);
74
+ expect(shown(state, A)).toBe(fromServer);
75
+ state = stepSteadyShells(state, [shell(A, withEvents, "live", 1)], 30);
76
+ expect(shown(state, A)).toBe(withEvents);
77
+ });
78
+
79
+ it("does not wait for an environment that already shows its server snapshot", () => {
80
+ const [cachedA, cachedB, serverA, serverB] = [
81
+ snapshot(1),
82
+ snapshot(2),
83
+ snapshot(3),
84
+ snapshot(4),
85
+ ];
86
+ let state = stepSteadyShells(
87
+ EMPTY_STEADY_SHELLS_STATE,
88
+ [shell(A, cachedA, "connecting"), shell(B, cachedB, "connecting")],
89
+ 0,
90
+ );
91
+ state = stepSteadyShells(
92
+ state,
93
+ [shell(A, cachedA, "connecting"), shell(B, serverB, "connecting", 1)],
94
+ 10,
95
+ );
96
+ expect(shown(state, B)).toBe(cachedB);
97
+ state = stepSteadyShells(
98
+ state,
99
+ [shell(A, serverA, "connecting", 2), shell(B, serverB, "connecting", 1)],
100
+ 20,
101
+ );
102
+ expect(shown(state, A)).toBe(serverA);
103
+ expect(shown(state, B)).toBe(serverB);
104
+ // B is not live yet, and A's next rows do not wait for it.
105
+ const liveA = snapshot(5);
106
+ state = stepSteadyShells(
107
+ state,
108
+ [shell(A, liveA, "live", 2), shell(B, serverB, "connecting", 1)],
109
+ 30,
110
+ );
111
+ expect(shown(state, A)).toBe(liveA);
112
+ });
113
+
114
+ it("shows rows that wait when their environment disconnects", () => {
115
+ const [cachedA, cachedB, serverA] = [snapshot(7), snapshot(2), snapshot(9)];
116
+ let state = stepSteadyShells(
117
+ EMPTY_STEADY_SHELLS_STATE,
118
+ [shell(A, cachedA, "connecting"), shell(B, cachedB, "connecting")],
119
+ 0,
120
+ );
121
+ state = stepSteadyShells(
122
+ state,
123
+ [shell(A, serverA, "connecting", 1), shell(B, cachedB, "connecting")],
124
+ 10,
125
+ );
126
+ expect(shown(state, A)).toBe(cachedA);
127
+ const disconnected = [shell(A, serverA, "disconnected", 1), shell(B, cachedB, "connecting")];
128
+ state = stepSteadyShells(state, disconnected, 20);
129
+ expect(shown(state, A)).toBe(cachedA);
130
+ expect(state.releaseAt).toBe(10 + WINDOW);
131
+ state = stepSteadyShells(state, disconnected, 10 + WINDOW);
132
+ expect(shown(state, A)).toBe(serverA);
133
+ });
134
+
135
+ it("holds replayed events after a reconnect until the environment is live again", () => {
136
+ const [first, replayed] = [snapshot(1), snapshot(4)];
137
+ let state = stepSteadyShells(EMPTY_STEADY_SHELLS_STATE, [shell(A, first, "live", 1)], 0);
138
+ state = stepSteadyShells(state, [shell(A, replayed, "connecting", 1)], 10);
139
+ expect(shown(state, A)).toBe(first);
140
+ state = stepSteadyShells(state, [shell(A, replayed, "live", 1)], 20);
141
+ expect(shown(state, A)).toBe(replayed);
142
+ });
143
+
144
+ it("shows the cache of an environment that was first seen before its cache was read", () => {
145
+ const cached = snapshot(7);
146
+ let state = stepSteadyShells(EMPTY_STEADY_SHELLS_STATE, [shell(A, null, "connecting")], 0);
147
+ state = stepSteadyShells(state, [shell(A, cached, "connecting")], 10);
148
+ expect(shown(state, A)).toBe(cached);
149
+ state = stepSteadyShells(state, [shell(A, snapshot(9), "connecting")], 20);
150
+ expect(shown(state, A)).toBe(cached);
151
+ });
152
+
153
+ it("shows the rows of environments that synchronize within the window together", () => {
154
+ const [cachedA, cachedB, liveA, liveB] = [snapshot(1), snapshot(2), snapshot(3), snapshot(4)];
155
+ let state = stepSteadyShells(
156
+ EMPTY_STEADY_SHELLS_STATE,
157
+ [shell(A, cachedA, "connecting"), shell(B, cachedB, "connecting")],
158
+ 0,
159
+ );
160
+ state = stepSteadyShells(
161
+ state,
162
+ [shell(A, liveA, "live"), shell(B, cachedB, "connecting")],
163
+ 500,
164
+ );
165
+ expect(shown(state, A)).toBe(cachedA);
166
+ expect(state.releaseAt).toBe(500 + WINDOW);
167
+
168
+ state = stepSteadyShells(state, [shell(A, liveA, "live"), shell(B, liveB, "live")], 900);
169
+ expect(shown(state, A)).toBe(liveA);
170
+ expect(shown(state, B)).toBe(liveB);
171
+ expect(state.releaseAt).toBeNull();
172
+ });
173
+
174
+ it("stops waiting for a slow environment when the window ends, then shows it on its own", () => {
175
+ const [cachedA, cachedB, liveA, liveB] = [snapshot(1), snapshot(2), snapshot(3), snapshot(4)];
176
+ let state = stepSteadyShells(
177
+ EMPTY_STEADY_SHELLS_STATE,
178
+ [shell(A, cachedA, "connecting"), shell(B, cachedB, "connecting")],
179
+ 0,
180
+ );
181
+ const waiting = [shell(A, liveA, "live"), shell(B, cachedB, "connecting")];
182
+ state = stepSteadyShells(state, waiting, 500);
183
+ expect(stepSteadyShells(state, waiting, 500 + WINDOW - 1)).toBe(state);
184
+
185
+ state = stepSteadyShells(state, waiting, 500 + WINDOW);
186
+ expect(shown(state, A)).toBe(liveA);
187
+ expect(shown(state, B)).toBe(cachedB);
188
+
189
+ state = stepSteadyShells(state, [shell(A, liveA, "live"), shell(B, liveB, "live")], 9_000);
190
+ expect(shown(state, B)).toBe(liveB);
191
+ });
192
+
193
+ it("does not wait for an environment that already failed", () => {
194
+ const [cachedA, cachedB, liveA] = [snapshot(1), snapshot(2), snapshot(3)];
195
+ let state = stepSteadyShells(
196
+ EMPTY_STEADY_SHELLS_STATE,
197
+ [shell(A, cachedA, "connecting"), shell(B, cachedB, "disconnected")],
198
+ 0,
199
+ );
200
+ state = stepSteadyShells(
201
+ state,
202
+ [shell(A, liveA, "live"), shell(B, cachedB, "disconnected")],
203
+ 500,
204
+ );
205
+ expect(shown(state, A)).toBe(liveA);
206
+ });
207
+
208
+ it("follows a synchronized environment, and holds its rows again while it reconnects", () => {
209
+ const [first, second, missed, caughtUp] = [snapshot(1), snapshot(2), snapshot(5), snapshot(6)];
210
+ let state = stepSteadyShells(EMPTY_STEADY_SHELLS_STATE, [shell(A, first, "live")], 0);
211
+ state = stepSteadyShells(state, [shell(A, second, "live")], 10);
212
+ expect(shown(state, A)).toBe(second);
213
+
214
+ state = stepSteadyShells(state, [shell(A, second, "connecting")], 20);
215
+ state = stepSteadyShells(state, [shell(A, missed, "connecting")], 30);
216
+ expect(shown(state, A)).toBe(second);
217
+
218
+ state = stepSteadyShells(state, [shell(A, caughtUp, "live")], 40);
219
+ expect(shown(state, A)).toBe(caughtUp);
220
+ });
221
+
222
+ it("follows an environment's live rows once the user moves or removes a row there", () => {
223
+ const [cachedA, cachedB, liveA, confirmedA] = [
224
+ snapshot(1),
225
+ snapshot(2),
226
+ snapshot(3),
227
+ snapshot(4),
228
+ ];
229
+ const [replayedB, archivedB, laterB] = [snapshot(5), snapshot(6), snapshot(7)];
230
+ const settledA = { ...liveA };
231
+ let state = stepSteadyShells(
232
+ EMPTY_STEADY_SHELLS_STATE,
233
+ [shell(A, cachedA, "connecting"), shell(B, cachedB, "connecting")],
234
+ 0,
235
+ );
236
+ state = stepSteadyShells(state, [shell(A, liveA, "live"), shell(B, cachedB, "connecting")], 10);
237
+ expect(shown(state, A)).toBe(cachedA);
238
+
239
+ // The user settles a thread of A: its rows show at once, and B's rows still wait.
240
+ const heldB = shell(B, replayedB, "connecting");
241
+ state = stepSteadyShells(state, [shell(A, settledA, "live", 0, 1), heldB], 20);
242
+ expect(shown(state, A)).toBe(settledA);
243
+ expect(shown(state, B)).toBe(cachedB);
244
+ expect(state.releaseAt).toBeNull();
245
+ state = stepSteadyShells(state, [shell(A, confirmedA, "live", 0, 1), heldB], 30);
246
+ expect(shown(state, A)).toBe(confirmedA);
247
+
248
+ // B still synchronizes when the user archives a thread there. Its rows follow the
249
+ // replayed events until it is live, then wait again on the next reconnect.
250
+ const a = shell(A, confirmedA, "live", 0, 1);
251
+ state = stepSteadyShells(state, [a, shell(B, replayedB, "connecting", 0, 1)], 40);
252
+ expect(shown(state, B)).toBe(replayedB);
253
+ state = stepSteadyShells(state, [a, shell(B, archivedB, "connecting", 0, 1)], 50);
254
+ expect(shown(state, B)).toBe(archivedB);
255
+ state = stepSteadyShells(state, [a, shell(B, archivedB, "live", 0, 1)], 60);
256
+ state = stepSteadyShells(state, [a, shell(B, laterB, "connecting", 0, 1)], 70);
257
+ expect(shown(state, B)).toBe(archivedB);
258
+ });
259
+
260
+ it("drops an environment that left the list of enabled environments", () => {
261
+ const state = stepSteadyShells(
262
+ stepSteadyShells(EMPTY_STEADY_SHELLS_STATE, [shell(A, snapshot(1), "live")], 0),
263
+ [],
264
+ 10,
265
+ );
266
+ expect(state.shells.size).toBe(0);
267
+ });
268
+});
269
+
270
+describe("createSteadyShellAtoms", () => {
271
+ beforeEach(() => {
272
+ vi.useFakeTimers();
273
+ vi.setSystemTime(10_000);
274
+ });
275
+ afterEach(() => {
276
+ vi.clearAllTimers();
277
+ vi.useRealTimers();
278
+ });
279
+
280
+ it("shows held rows when the window ends without another change", () => {
281
+ const entry = (environmentId: EnvironmentId) => ({
282
+ target: new PrimaryConnectionTarget({
283
+ environmentId,
284
+ label: environmentId,
285
+ httpBaseUrl: "https://example.test",
286
+ wsBaseUrl: "wss://example.test",
287
+ }),
288
+ enabled: true,
289
+ profile: Option.none(),
290
+ });
291
+ const catalog = Atom.make<EnvironmentCatalogState>({
292
+ isReady: true,
293
+ entries: new Map([
294
+ [A, entry(A)],
295
+ [B, entry(B)],
296
+ ]),
297
+ });
298
+ const [cachedA, liveA] = [snapshot(1), snapshot(3)];
299
+ const snapshots = Atom.family((environmentId: EnvironmentId) =>
300
+ Atom.make<OrchestrationV2ShellSnapshot | null>(environmentId === A ? cachedA : snapshot(2)),
301
+ );
302
+ const rowActions = Atom.family((_: EnvironmentId) => Atom.make(0));
303
+ const shellStates = Atom.family((_: EnvironmentId) =>
304
+ Atom.make<EnvironmentShellState>({ ...EMPTY_SHELL_STATE, status: "synchronizing" }),
305
+ );
306
+ const connections = Atom.family((_: EnvironmentId) =>
307
+ Atom.make(
308
+ AsyncResult.success<SupervisorConnectionState>({
309
+ ...AVAILABLE_CONNECTION_STATE,
310
+ desired: true,
311
+ phase: "connecting",
312
+ attempt: 1,
313
+ }),
314
+ ),
315
+ );
316
+ const steady = createSteadyShellAtoms({
317
+ catalogValueAtom: catalog,
318
+ snapshotAtom: snapshots,
319
+ shellStateAtom: shellStates,
320
+ rowActionsAtom: rowActions,
321
+ connectionStateAtom: connections,
322
+ });
323
+ const registry = AtomRegistry.make();
324
+ const release = registry.mount(steady.snapshotAtom(A));
325
+
326
+ registry.set(snapshots(A), liveA);
327
+ registry.set(shellStates(A), { ...EMPTY_SHELL_STATE, status: "live", generation: 1 });
328
+ registry.set(
329
+ connections(A),
330
+ AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, desired: true, phase: "connected" }),
331
+ );
332
+ expect(registry.get(steady.snapshotAtom(A))).toBe(cachedA);
333
+
334
+ vi.advanceTimersByTime(WINDOW);
335
+ expect(registry.get(steady.snapshotAtom(A))).toBe(liveA);
336
+ release();
337
+ });
338
+});
packages/client-runtime/src/state/steadyShells.ts
new
+217
@@ -0,0 +1,217 @@
1
+// @effect-diagnostics globalTimers:off - The release timer runs in web and native clients, outside an Effect runtime.
2
+import type { EnvironmentId, OrchestrationV2ShellSnapshot } from "@t3tools/contracts";
3
+import { AsyncResult, Atom } from "effect/reactivity";
4
+
5
+import { AVAILABLE_CONNECTION_STATE, type SupervisorConnectionState } from "../connection/model.ts";
6
+import { presentConnectionState } from "../connection/presentation.ts";
7
+import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
8
+import type { EnvironmentShellState, EnvironmentShellStatus } from "./shell.ts";
9
+
10
+/**
11
+ * How long fresh rows wait for environments that are still connecting. Each environment
12
+ * gets its server data at its own time, and a list that follows each one moves once per
13
+ * environment; within this time they move together.
14
+ */
15
+const STEADY_SHELL_RELEASE_WINDOW_MS = 2_000;
16
+
17
+export interface SteadyShellInput {
18
+ readonly environmentId: EnvironmentId;
19
+ readonly snapshot: OrchestrationV2ShellSnapshot | null;
20
+ /**
21
+ * The snapshot's server sequence. It moves with new server data and with nothing else, and
22
+ * it comes from the snapshot itself: a second atom could be one update behind the rows.
23
+ */
24
+ readonly serverSequence: number | null;
25
+ readonly status: EnvironmentShellStatus;
26
+ /** The shell state's generation: it grows with each server snapshot. */
27
+ readonly generation: number;
28
+ /** The connection is up or on its first attempt, so fresh rows can come soon. */
29
+ readonly connecting: boolean;
30
+ /** How many times the user moved or removed a row of this environment. */
31
+ readonly rowActions: number;
32
+}
33
+
34
+interface SteadyShell {
35
+ readonly shown: OrchestrationV2ShellSnapshot | null;
36
+ readonly shownSequence: number | null;
37
+ readonly shownGeneration: number;
38
+ /** The rows were shown while live, so each live change shows at once. */
39
+ readonly following: boolean;
40
+ /** The rows hold a server snapshot of the connection that is synchronizing. */
41
+ readonly caughtUp: boolean;
42
+ /** The `rowActions` count when the rows last showed while live. */
43
+ readonly rowActions: number;
44
+}
45
+
46
+export interface SteadyShellsState {
47
+ readonly shells: ReadonlyMap<EnvironmentId, SteadyShell>;
48
+ /** When held rows show at the latest; null while none wait. */
49
+ readonly releaseAt: number | null;
50
+}
51
+
52
+export const EMPTY_STEADY_SHELLS_STATE: SteadyShellsState = { shells: new Map(), releaseAt: null };
53
+
54
+/**
55
+ * Decides which snapshot of each environment a thread list shows. New server rows wait for
56
+ * a complete state (a server snapshot, live, or disconnected), then show with every other
57
+ * environment that has one: at once when no other owes its rows, else when the window ends.
58
+ * Returns `previous` itself when nothing changes.
59
+ */
60
+export function stepSteadyShells(
61
+ previous: SteadyShellsState,
62
+ inputs: ReadonlyArray<SteadyShellInput>,
63
+ now: number,
64
+ windowMs = STEADY_SHELL_RELEASE_WINDOW_MS,
65
+): SteadyShellsState {
66
+ const shells = new Map<EnvironmentId, SteadyShell>();
67
+ const waiting: Array<SteadyShellInput> = [];
68
+ let othersOweRows = false;
69
+ const show = (
70
+ input: SteadyShellInput,
71
+ caughtUp: boolean,
72
+ current: SteadyShell | undefined,
73
+ ): SteadyShell => ({
74
+ shown: input.snapshot,
75
+ shownSequence: input.serverSequence,
76
+ shownGeneration: input.generation,
77
+ following: input.status === "live",
78
+ caughtUp,
79
+ rowActions:
80
+ input.status === "live" || current === undefined ? input.rowActions : current.rowActions,
81
+ });
82
+ const keep = (input: SteadyShellInput, next: SteadyShell, current: SteadyShell | undefined) => {
83
+ othersOweRows ||= input.status === "synchronizing" && input.connecting && !next.caughtUp;
84
+ const same =
85
+ current !== undefined &&
86
+ current.shown === next.shown &&
87
+ current.shownSequence === next.shownSequence &&
88
+ current.shownGeneration === next.shownGeneration &&
89
+ current.following === next.following &&
90
+ current.caughtUp === next.caughtUp &&
91
+ current.rowActions === next.rowActions;
92
+ shells.set(input.environmentId, same ? current : next);
93
+ };
94
+ for (const input of inputs) {
95
+ const current = previous.shells.get(input.environmentId);
96
+ const synchronizing = input.status === "synchronizing";
97
+ if (current === undefined) {
98
+ keep(input, show(input, false, current), current);
99
+ continue;
100
+ }
101
+ const newSnapshot = input.generation > current.shownGeneration;
102
+ // Without new server data the change is local (cached links, rows loaded on demand), and
103
+ // an environment that shows nothing (its cache is not read yet) has nothing to hold back.
104
+ const local =
105
+ current.shown === null || (input.serverSequence === current.shownSequence && !newSnapshot);
106
+ // The hold stops changes the user did not cause. After the user moves or removes a row,
107
+ // the environment's rows follow the live data until it is live.
108
+ const userActed = input.rowActions !== current.rowActions;
109
+ if (local || userActed || (input.status === "live" && current.following)) {
110
+ const caughtUp = synchronizing && (current.caughtUp || newSnapshot);
111
+ keep(input, show(input, caughtUp, current), current);
112
+ } else if (!synchronizing || newSnapshot) {
113
+ waiting.push(input);
114
+ shells.set(input.environmentId, current);
115
+ } else {
116
+ // Events that a synchronizing environment replays are complete only when it is live.
117
+ keep(input, { ...current, following: false }, current);
118
+ }
119
+ }
120
+
121
+ let releaseAt: number | null = null;
122
+ if (waiting.length > 0) {
123
+ releaseAt = previous.releaseAt ?? now + windowMs;
124
+ if (!othersOweRows || now >= releaseAt) {
125
+ releaseAt = null;
126
+ for (const input of waiting) {
127
+ const current = shells.get(input.environmentId);
128
+ shells.set(input.environmentId, show(input, input.status === "synchronizing", current));
129
+ }
130
+ }
131
+ }
132
+
133
+ const unchanged =
134
+ releaseAt === previous.releaseAt &&
135
+ shells.size === previous.shells.size &&
136
+ [...shells].every(([environmentId, shell]) => previous.shells.get(environmentId) === shell);
137
+ return unchanged ? previous : { shells, releaseAt };
138
+}
139
+
140
+/**
141
+ * Snapshots for lists that arrange threads across environments; see `stepSteadyShells`.
142
+ * Point reads (a thread's own shell, route checks) keep the live snapshot, where a row
143
+ * that the server just sent must not look missing.
144
+ */
145
+export function createSteadyShellAtoms<E>(input: {
146
+ readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
147
+ readonly snapshotAtom: (
148
+ environmentId: EnvironmentId,
149
+ ) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
150
+ readonly shellStateAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
151
+ readonly rowActionsAtom: (environmentId: EnvironmentId) => Atom.Atom<number>;
152
+ readonly connectionStateAtom: (
153
+ environmentId: EnvironmentId,
154
+ ) => Atom.Atom<AsyncResult.AsyncResult<SupervisorConnectionState, E>>;
155
+}) {
156
+ const now = () => {
157
+ // @effect-diagnostics-next-line globalDate:off - The release window is wall-clock time.
158
+ return Date.now();
159
+ };
160
+ // Outlives the atom's rebuilds, and its unmount while no list is on screen.
161
+ let state = EMPTY_STEADY_SHELLS_STATE;
162
+ const stateAtom = Atom.make((get) => {
163
+ const inputs: Array<SteadyShellInput> = [];
164
+ for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
165
+ const snapshot = get(input.snapshotAtom(environmentId));
166
+ const shell = get(input.shellStateAtom(environmentId));
167
+ const connection = AsyncResult.getOrElse(
168
+ get(input.connectionStateAtom(environmentId)),
169
+ () => AVAILABLE_CONNECTION_STATE,
170
+ );
171
+ // An enabled environment starts out connecting, before its supervisor reports.
172
+ const phase =
173
+ connection === AVAILABLE_CONNECTION_STATE
174
+ ? "connecting"
175
+ : presentConnectionState(connection).phase;
176
+ inputs.push({
177
+ environmentId,
178
+ snapshot,
179
+ serverSequence: snapshot?.snapshotSequence ?? null,
180
+ status: shell.status,
181
+ generation: shell.generation,
182
+ // A retry after a failure can take minutes, so it is not waited for until it connects.
183
+ connecting: phase === "connecting" || phase === "connected",
184
+ rowActions: get(input.rowActionsAtom(environmentId)),
185
+ });
186
+ }
187
+ state = stepSteadyShells(state, inputs, now());
188
+ if (state.releaseAt !== null) {
189
+ const timer = setTimeout(() => get.refreshSelf(), Math.max(0, state.releaseAt - now()));
190
+ get.addFinalizer(() => clearTimeout(timer));
191
+ }
192
+ return state;
193
+ }).pipe(Atom.withLabel("steady-shells"));
194
+
195
+ const snapshotAtom = Atom.family((environmentId: EnvironmentId) =>
196
+ Atom.make(
197
+ (get): OrchestrationV2ShellSnapshot | null =>
198
+ get(stateAtom).shells.get(environmentId)?.shown ?? null,
199
+ ).pipe(Atom.withLabel(`steady-shell-snapshot:${environmentId}`)),
200
+ );
201
+
202
+ // Reads the live snapshots too, so it is current when a handler reads it once.
203
+ const holdingAtom = Atom.make((get) => {
204
+ const { shells } = get(stateAtom);
205
+ for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
206
+ if (shells.get(environmentId)?.shown !== get(input.snapshotAtom(environmentId))) return true;
207
+ }
208
+ return false;
209
+ }).pipe(Atom.withLabel("steady-shells-holding"));
210
+
211
+ return {
212
+ /** The snapshot a thread list shows for an environment. */
213
+ snapshotAtom,
214
+ /** True while a list shows rows older than the server data the client holds. */
215
+ holdingAtom,
216
+ };
217
+}
packages/client-runtime/src/state/threadCommands.test.ts
+2
@@ -415,6 +415,8 @@ describe("remote thread lifecycle commands", () => {
415
});
416
const request = yield* Queue.take(h.requests);
417
expect(h.registry.get(h.commands.snapshotAtom(otherEnvironment))).toBe(SNAPSHOT);
418
+ expect(h.registry.get(h.commands.rowActionsAtom(ENVIRONMENT_ID))).toBe(1);
419
+ expect(h.registry.get(h.commands.rowActionsAtom(otherEnvironment))).toBe(0);
420
const removed = { ...SNAPSHOT, snapshotSequence: 2, threads: [] };
421
h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), removed);
422
expect(h.registry.get(h.visibleAtom)?.threads).toEqual([]);
packages/client-runtime/src/state/threadCommands.ts
+30
-1
@@ -13,6 +13,7 @@ import { createOptimisticThreadLifecycle } from "./threadLifecycle.ts";
13
import * as DateTime from "effect/DateTime";
14
15
import {
16
+ type AtomCommand,
17
createAtomCommandScheduler,
18
createEnvironmentCommand,
19
createEnvironmentRpcCommand,
@@ -119,7 +120,22 @@ export function createThreadEnvironmentAtoms<R, E>(
120
);
121
});
122
122
- const commands = {
123
+ // Counts the commands that move or remove a thread's row. A list that holds its rows while
124
+ // environments synchronize (`stepSteadyShells`) shows the user's own change at once.
125
+ const rowActionsAtom = Atom.family((_environmentId: EnvironmentId) =>
126
+ Atom.make(0).pipe(Atom.keepAlive),
127
+ );
128
+ const rowAction = <W extends { readonly environmentId: EnvironmentId }, A, E>(
129
+ command: AtomCommand<W, A, E>,
130
+ ): AtomCommand<W, A, E> => ({
131
+ label: command.label,
132
+ run: (registry, target) => {
133
+ registry.update(rowActionsAtom(target.environmentId), (count) => count + 1);
134
+ return command.run(registry, target);
135
+ },
136
+ });
137
+
138
+ const sent = {
139
create: createEnvironmentCommand(runtime, {
140
label: "environment-data:commands:thread:create",
141
execute: createThread,
@@ -382,9 +398,22 @@ export function createThreadEnvironmentAtoms<R, E>(
398
concurrency,
399
}),
400
};
401
+ const commands = {
402
+ ...sent,
403
+ delete: rowAction(sent.delete),
404
+ archive: rowAction(sent.archive),
405
+ unarchive: rowAction(sent.unarchive),
406
+ settle: rowAction(sent.settle),
407
+ unsettle: rowAction(sent.unsettle),
408
+ snooze: rowAction(sent.snooze),
409
+ unsnooze: rowAction(sent.unsnooze),
410
+ pin: rowAction(sent.pin),
411
+ unpin: rowAction(sent.unpin),
412
+ };
413
const optimistic = createOptimisticThreadLifecycle(snapshotAtom);
414
return {
415
...commands,
416
+ rowActionsAtom,
417
snapshotAtom: optimistic.snapshotAtom,
418
pendingThreadIdsAtom: optimistic.pendingThreadIdsAtom,
419
settle: optimistic.wrap(commands.settle, (thread, _input, now, accepted) =>
packages/client-runtime/src/state/threadInbox.test.ts
+20
@@ -79,6 +79,26 @@ describe("createInboxReturnTracker", () => {
79
unsubscribe();
80
});
81
82
+ it("moves a thread whose run ended long ago at once, as after a reconnect", () => {
83
+ const tracker = createInboxReturnTracker();
84
+ const finished = {
85
+ ...thread("a", false),
86
+ latestRun: {
87
+ runId: RunId.make("ended-while-away"),
88
+ status: "completed" as const,
89
+ requestedAt: "1970-01-01T00:00:02.000Z",
90
+ startedAt: "1970-01-01T00:00:02.000Z",
91
+ completedAt: "1970-01-01T00:00:09.000Z",
92
+ assistantMessageId: null,
93
+ },
94
+ };
95
+ tracker.observe([thread("a", true)]);
96
+ vi.setSystemTime(200_000);
97
+ tracker.observe([finished]);
98
+ expect(tracker.isWorking(finished)).toBe(false);
99
+ expect(tracker.returnedAt(finished)).toBe(200_000);
100
+ });
101
+
102
it("cancels a transient return on resume and grants a fresh grace after the next finish", () => {
103
const tracker = createInboxReturnTracker();
104
tracker.observe([thread("a", false)]);
packages/client-runtime/src/state/threadInbox.ts
+10
-1
@@ -133,6 +133,13 @@ type ThreadKeyInput = Pick<EnvironmentThreadShell, "environmentId" | "id">;
133
*/
134
const WORKING_EXIT_GRACE_MS = 2_000;
135
136
+/**
137
+ * A run that ended this long ago has no continuation about to start, so its thread gets no
138
+ * grace. A client sees this for work that ended while it was closed or disconnected; the
139
+ * margin is wide so a client clock that runs ahead of the server does not cancel the grace.
140
+ */
141
+const STALE_EXIT_MS = 60_000;
142
+
143
/**
144
* Keep one at module scope so placement survives routes that unmount the list. Call
145
* `observe` when the shells or the snapshot version change, or with null while the beta
@@ -234,8 +241,10 @@ export function createInboxReturnTracker() {
241
thread.settledOverride === "settled" ||
242
effectiveSnoozed(thread, { now: observedAt });
243
// Only shelf placement is held: execution state and attention requests stay authoritative.
244
+ const endedAt = toSortableTimestamp(thread.latestRun?.completedAt ?? undefined);
245
+ const endedLongAgo = endedAt !== null && endedAt <= at - STALE_EXIT_MS;
246
const deadline =
238
- !actual && previous?.working && !actionable && !moved && !excluded
247
+ !actual && previous?.working && !actionable && !moved && !excluded && !endedLongAgo
248
? (previous.deadline ?? at + WORKING_EXIT_GRACE_MS)
249
: null;
250
const working = actual || (deadline !== null && deadline > at);