@devries-cameron20 / t3code Mirror · read-only / commits / 503bcaaf99
Fork 0

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 22, 12:00 UTC

fix: keep offline environments out of thread reorder writes (#22887)

Co-authored-by: maria-rcks <maria@kuuro.net>

Devesh Sangwan committed Oct 31, 2026 at 02:13 UTC 503bcaaf99f1c24292fa972033143a6faaa9c5aa
12 files changed +592 -53
apps/mobile/src/features/home/HomeScreen.tsx
+1 -1
@@ -53,7 +53,7 @@ import { useThreadListV2 } from "../threads/useThreadListV2";
53 import { useThreadListNow } from "../threads/use-thread-list-now";
54 import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
55 import { usePendingThreadOrder } from "../../state/thread-order";
56 -import { threadListEnvironmentsAtom } from "../../state/server";
56 +import { threadListEnvironmentsAtom } from "../../state/presentation";
57 import type { PendingNewTask } from "../../state/use-pending-new-tasks";
58 import { useQueuedThreadKeys } from "../../state/use-thread-outbox";
59 import {
apps/mobile/src/features/home/useThreadListActions.test.ts
+98 -20
@@ -13,6 +13,7 @@ import { AsyncResult } from "effect/reactivity";
13 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
14
15 const state = vi.hoisted(() => ({
16 + connectedEnvironmentIds: [] as EnvironmentId[],
17 pendingOrder: null as object | null,
18 dropBusy: false,
19 failedAction: null as string | null,
@@ -60,6 +61,9 @@ vi.mock("../../state/session", () => ({
61 readEnvironmentScope: (environmentId: string, scope: string) =>
62 state.scopes.get(environmentId)?.has(scope) === true,
63 }));
64 +vi.mock("../../state/presentation", () => ({
65 + connectedEnvironmentIdsAtom: "connected-environments",
66 +}));
67 vi.mock("../../state/server", () => ({
68 environmentServerConfigsAtom: "server-configs",
69 }));
@@ -69,28 +73,30 @@ vi.mock("../../state/atom-registry", () => ({
73 state.dropBusy = value;
74 },
75 get: (atom: string) =>
72 - atom === "thread-drop-busy"
73 - ? state.dropBusy
74 - : atom === "thread-shells"
75 - ? state.shells
76 - : atom === "queued-thread-keys"
77 - ? new Set<string>()
78 - : new Map(
79 - [...state.scopes.keys()].map((environmentId) => [
80 - environmentId,
81 - {
82 - environment: {
83 - capabilities: {
84 - threadSettlement: true,
85 - threadSnooze: true,
86 - threadPinning: true,
87 - threadPinReorder: true,
88 - threadTitleRegeneration: true,
76 + atom === "connected-environments"
77 + ? state.connectedEnvironmentIds
78 + : atom === "thread-drop-busy"
79 + ? state.dropBusy
80 + : atom === "thread-shells"
81 + ? state.shells
82 + : atom === "queued-thread-keys"
83 + ? new Set<string>()
84 + : new Map(
85 + [...state.scopes.keys()].map((environmentId) => [
86 + environmentId,
87 + {
88 + environment: {
89 + capabilities: {
90 + threadSettlement: true,
91 + threadSnooze: true,
92 + threadPinning: true,
93 + threadPinReorder: true,
94 + threadTitleRegeneration: true,
95 + },
96 },
97 },
91 - },
92 - ]),
93 - ),
98 + ]),
99 + ),
100 },
101 }));
102 vi.mock("../../state/use-atom-command", () => ({
@@ -130,6 +136,7 @@ vi.mock("../../state/threads", () => ({
136 "pin",
137 "unpin",
138 "reorderPin",
139 + "reorderActive",
140 "updateMetadata",
141 ].map((action) => [
142 action,
@@ -179,6 +186,7 @@ const mutationCases = [
186 ] as const;
187
188 beforeEach(() => {
189 + state.connectedEnvironmentIds = [primaryEnvironmentId, otherEnvironmentId];
190 state.failedAction = null;
191 state.archivedRefreshes = [];
192 state.pendingOrder = null;
@@ -286,6 +294,76 @@ describe("pinned thread operation permissions", () => {
294 });
295 });
296
297 +describe("thread reorder connection availability", () => {
298 + it.each(["active", "pinned"] as const)(
299 + "rejects %s materialization involving a cached capable offline neighbor",
300 + async (section) => {
301 + const moved = makeThread({
302 + pinnedAt: section === "pinned" ? "2026-09-02T00:00:00.000Z" : null,
303 + });
304 + state.shells = [
305 + moved,
306 + makeThread({
307 + id: ThreadId.make("offline-neighbor"),
308 + environmentId: otherEnvironmentId,
309 + createdAt: "2026-09-02T00:00:00.000Z",
310 + pinnedAt: moved.pinnedAt,
311 + }),
312 + ];
313 + state.scopes.get(otherEnvironmentId)?.add(AuthOrchestrationOperateScope);
314 + state.connectedEnvironmentIds = [primaryEnvironmentId];
315 +
316 + const { moveThread } = useThreadListActions();
317 + expect(await moveThread(moved, "up")).toBe(false);
318 + expect(state.requests).toEqual([]);
319 +
320 + state.connectedEnvironmentIds = [primaryEnvironmentId, otherEnvironmentId];
321 +
322 + expect(await moveThread(moved, "up")).toBe(true);
323 + expect(state.requests).toHaveLength(2);
324 + expect(new Set(state.requests.map(({ environmentId }) => environmentId))).toEqual(
325 + new Set([primaryEnvironmentId, otherEnvironmentId]),
326 + );
327 + },
328 + );
329 +
330 + it.each(["active", "pinned"] as const)(
331 + "uses the latest connection state in a retained %s move callback",
332 + async (section) => {
333 + const moved = makeThread({
334 + pinnedAt: section === "pinned" ? "2026-09-02T00:00:00.000Z" : null,
335 + pinOrderKey: section === "pinned" ? "m" : null,
336 + activeOrderKey: section === "active" ? "m" : null,
337 + });
338 + state.shells = [
339 + moved,
340 + makeThread({
341 + id: ThreadId.make("offline-neighbor"),
342 + environmentId: otherEnvironmentId,
343 + pinnedAt: moved.pinnedAt,
344 + pinOrderKey: section === "pinned" ? "g" : null,
345 + activeOrderKey: section === "active" ? "g" : null,
346 + }),
347 + ];
348 + const { moveThread } = useThreadListActions();
349 + state.connectedEnvironmentIds = [];
350 +
351 + expect(await moveThread(moved, "up")).toBe(false);
352 + expect(state.requests).toEqual([]);
353 +
354 + state.connectedEnvironmentIds = [primaryEnvironmentId];
355 +
356 + expect(await moveThread(moved, "up")).toBe(true);
357 + expect(state.requests).toEqual([
358 + expect.objectContaining({
359 + action: section === "pinned" ? "reorderPin" : "reorderActive",
360 + environmentId: primaryEnvironmentId,
361 + }),
362 + ]);
363 + },
364 + );
365 +});
366 +
367 describe("thread action undo", () => {
368 it.each([
369 ["settleThread", "settle", "Settled", "unsettle"],
apps/mobile/src/features/home/useThreadListActions.ts
+8 -1
@@ -15,6 +15,7 @@ import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThre
15 import { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
16 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";
21 import { queuedThreadKeysAtom } from "../../state/use-thread-outbox";
@@ -591,6 +592,10 @@ export function useThreadListActions(): {
592 return settled;
593 }
594 const configs = appAtomRegistry.get(environmentServerConfigsAtom);
595 + const connectedEnvironmentIds = new Set(appAtomRegistry.get(connectedEnvironmentIdsAtom));
596 +
597 + if (!connectedEnvironmentIds.has(thread.environmentId)) return false;
598 +
599 if (!configs.has(thread.environmentId)) {
600 Dialog.alert(
601 "Could not move thread",
@@ -610,7 +615,9 @@ export function useThreadListActions(): {
615 allThreads: shells,
616 ordered,
617 section,
613 - reorderableEnvironmentIds: new Set(configs.keys()),
618 + reorderableEnvironmentIds: new Set(
619 + [...configs.keys()].filter((environmentId) => connectedEnvironmentIds.has(environmentId)),
620 + ),
621 })(scopedThreadKey(thread.environmentId, thread.id), direction);
622 if (assignments === null) return false;
623 const lifecycle = threadDropLifecycle(thread, section, new Date().toISOString());
apps/mobile/src/features/threads/ThreadArrangementSheet.tsx
+15 -5
@@ -15,6 +15,7 @@ import { AppText as Text } from "../../components/ui/AppText";
15 import { SymbolView } from "../../components/ui/AppSymbol";
16 import { scopedThreadKey } from "../../lib/scopedEntities";
17 import { environmentServerConfigsAtom } from "../../state/server";
18 +import { threadListEnvironmentsAtom } from "../../state/presentation";
19 import { environmentThreadShells } from "../../state/threads";
20 import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort";
21 import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../../state/olderSettledShelf";
@@ -164,6 +165,7 @@ function DragHandle(props: {
165 function ThreadArrangementSheet(props: { onClose: () => void }) {
166 const threads = useAtomValue(environmentThreadShells.navigationThreadShellsAtom);
167 const configs = useAtomValue(environmentServerConfigsAtom);
168 + const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
169 const queuedThreadKeys = useAtomValue(queuedThreadKeysAtom);
170 const pendingOrder = useAtomValue(pendingThreadOrderAtom);
171 const dropBusy = useAtomValue(threadDropBusyAtom);
@@ -214,12 +216,15 @@ function ThreadArrangementSheet(props: { onClose: () => void }) {
216 ordered: sections[section],
217 allThreads: threads,
218 section,
217 - reorderableEnvironmentIds: new Set(
218 - section === "pinned" || !workingShelfEnabled ? configs.keys() : [],
219 - ),
219 + reorderableEnvironmentIds:
220 + section === "pinned"
221 + ? listEnvironments.pinReorderEnvironmentIds
222 + : workingShelfEnabled
223 + ? new Set()
224 + : listEnvironments.activeReorderEnvironmentIds,
225 });
226 return { pinned: planner("pinned"), active: planner("active") };
222 - }, [sections, threads, configs, workingShelfEnabled]);
227 + }, [sections, threads, listEnvironments, workingShelfEnabled]);
228 const rows = useMemo(() => {
229 const result: Row[] = [];
230 let offset = 0;
@@ -468,7 +473,12 @@ function ThreadArrangementSheet(props: { onClose: () => void }) {
473 disabled={
474 dropBusy ||
475 pendingOrder !== null ||
471 - !configs.has(thread.environmentId)
476 + (!listEnvironments.pinReorderEnvironmentIds.has(
477 + thread.environmentId,
478 + ) &&
479 + !listEnvironments.activeReorderEnvironmentIds.has(
480 + thread.environmentId,
481 + ))
482 }
483 sectionActions={sectionActions}
484 onSectionMove={(section) => {
apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+1 -1
@@ -37,7 +37,7 @@ import { useThreadSearch } from "../../state/queries";
37 import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
38 import { useThreadListNow } from "./use-thread-list-now";
39 import { usePendingThreadOrder } from "../../state/thread-order";
40 -import { threadListEnvironmentsAtom } from "../../state/server";
40 +import { threadListEnvironmentsAtom } from "../../state/presentation";
41 import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
42 import { useQueuedThreadKeys } from "../../state/use-thread-outbox";
43 import { useWorkspaceState } from "../../state/workspace";
apps/mobile/src/features/threads/thread-provider-instance.test.ts
+133 -1
@@ -9,6 +9,8 @@ import {
9 import { describe, expect, it } from "vite-plus/test";
10 import { Atom, AtomRegistry } from "effect/reactivity";
11
12 +import { computeThreadMoveAvailability, createThreadMovePlanner } from "./threadOrder";
13 +import { makeThreadShellFixture } from "../../test-fixtures";
14 import { createThreadListEnvironmentsAtom } from "../../state/thread-list-environments";
15
16 import {
@@ -127,7 +129,7 @@ describe("createThreadRowProviderInstanceResolver", () => {
129 const configs = Atom.make<ReadonlyMap<EnvironmentId, ServerConfig>>(
130 new Map([[environmentId, config]]),
131 );
130 - const environments = createThreadListEnvironmentsAtom(configs);
132 + const environments = createThreadListEnvironmentsAtom(configs, Atom.make([environmentId]));
133 const registry = AtomRegistry.make();
134 registry.mount(environments);
135 try {
@@ -168,3 +170,133 @@ describe("createThreadRowProviderInstanceResolver", () => {
170 }
171 });
172 });
173 +
174 +describe("thread list reorder availability", () => {
175 + it.each(["active", "pinned"] as const)(
176 + "updates %s moves on disconnect and reconnect without changing cached config",
177 + (section) => {
178 + const onlineId = EnvironmentId.make("online");
179 + const offlineId = EnvironmentId.make("offline");
180 + const config = makeConfig([{ instanceId: "codex", driver: "codex" }]);
181 + const configs = Atom.make<ReadonlyMap<EnvironmentId, ServerConfig>>(
182 + new Map([
183 + [onlineId, config],
184 + [offlineId, config],
185 + ]),
186 + );
187 + const connected = Atom.make<ReadonlyArray<EnvironmentId>>([onlineId, offlineId]);
188 + const environments = createThreadListEnvironmentsAtom(configs, connected);
189 + const registry = AtomRegistry.make();
190 + registry.mount(environments);
191 + try {
192 + const ordered = [onlineId, offlineId].map((environmentId, index) =>
193 + makeThreadShellFixture({
194 + environmentId,
195 + id: ThreadId.make(`thread-${index}`),
196 + pinnedAt: section === "pinned" ? "2026-09-02T00:00:00.000Z" : null,
197 + }),
198 + );
199 + const movedId = `${onlineId}:thread-0`;
200 + const plannerInput = () => {
201 + const current = registry.get(environments);
202 + return {
203 + ordered,
204 + section,
205 + reorderableEnvironmentIds:
206 + section === "pinned"
207 + ? current.pinReorderEnvironmentIds
208 + : current.activeReorderEnvironmentIds,
209 + };
210 + };
211 + expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toHaveLength(2);
212 + const before = registry.get(environments);
213 +
214 + registry.set(connected, [onlineId]);
215 +
216 + expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull();
217 + expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(false);
218 + expect(registry.get(environments).pinningEnvironmentIds.has(offlineId)).toBe(true);
219 + expect(registry.get(environments).settlementEnvironmentIds.has(offlineId)).toBe(true);
220 + expect(registry.get(environments).providersByEnvironmentId.get(offlineId)).toBe(
221 + before.providersByEnvironmentId.get(offlineId),
222 + );
223 +
224 + const keyedInput = {
225 + ...plannerInput(),
226 + ordered: ordered.map((row, index) => ({
227 + ...row,
228 + pinOrderKey: section === "pinned" ? (index === 0 ? "bb" : "dd") : null,
229 + activeOrderKey: section === "active" ? (index === 0 ? "bb" : "dd") : null,
230 + })),
231 + };
232 + expect(createThreadMovePlanner(keyedInput)(movedId, "down")).toEqual([
233 + expect.objectContaining({ id: movedId }),
234 + ]);
235 + expect(createThreadMovePlanner(keyedInput)(`${offlineId}:thread-1`, "up")).toBeNull();
236 + expect(computeThreadMoveAvailability(keyedInput).get(movedId)?.canMoveDown).toBe(true);
237 + expect(computeThreadMoveAvailability(keyedInput).get(`${offlineId}:thread-1`)).toEqual({
238 + canMoveUp: false,
239 + canMoveDown: false,
240 + });
241 +
242 + const updatedConfig = {
243 + ...config,
244 + settings: {
245 + ...config.settings,
246 + snoozePresets: [{ kind: "after" as const, minutes: 90 }],
247 + },
248 + };
249 + registry.set(
250 + configs,
251 + new Map([
252 + [onlineId, config],
253 + [offlineId, updatedConfig],
254 + ]),
255 + );
256 +
257 + const updated = registry.get(environments);
258 + expect(updated.snoozePresetsByEnvironmentId.get(offlineId)).toEqual(
259 + updatedConfig.settings.snoozePresets,
260 + );
261 + expect(updated.pinReorderEnvironmentIds.has(offlineId)).toBe(false);
262 + expect(updated.activeReorderEnvironmentIds.has(offlineId)).toBe(false);
263 + expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull();
264 +
265 + registry.set(
266 + configs,
267 + new Map([
268 + [onlineId, config],
269 + [
270 + offlineId,
271 + {
272 + ...updatedConfig,
273 + settings: {
274 + ...updatedConfig.settings,
275 + snoozePresets: updatedConfig.settings.snoozePresets.map((preset) => ({
276 + ...preset,
277 + })),
278 + },
279 + },
280 + ],
281 + ]),
282 + );
283 + expect(registry.get(environments)).toBe(updated);
284 +
285 + registry.set(connected, [onlineId, offlineId]);
286 +
287 + expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toHaveLength(2);
288 + expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(true);
289 + expect(registry.get(environments).snoozePresetsByEnvironmentId.get(offlineId)).toBe(
290 + updated.snoozePresetsByEnvironmentId.get(offlineId),
291 + );
292 +
293 + registry.set(configs, new Map([[onlineId, config]]));
294 +
295 + expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull();
296 + expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(false);
297 + } finally {
298 + registry.dispose();
299 + }
300 + },
301 + );
302 +});
apps/mobile/src/state/presentation.ts
+16 -2
@@ -1,11 +1,15 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import type { EnvironmentPresentation } from "@t3tools/client-runtime/connection";
3 -import { createEnvironmentPresentationAtoms } from "@t3tools/client-runtime/state/presentation";
3 +import {
4 + createEnvironmentPresentationAtoms,
5 + createEnvironmentSummaryAtoms,
6 +} from "@t3tools/client-runtime/state/presentation";
7 import type { EnvironmentId } from "@t3tools/contracts";
8 import { Atom } from "effect/reactivity";
9
10 import { environmentCatalog } from "../connection/catalog";
8 -import { serverEnvironment } from "./server";
11 +import { environmentServerConfigsAtom, serverEnvironment } from "./server";
12 +import { createThreadListEnvironmentsAtom } from "./thread-list-environments";
13
14 export const environmentPresentations = createEnvironmentPresentationAtoms({
15 catalogValueAtom: environmentCatalog.catalogValueAtom,
@@ -13,6 +17,16 @@ export const environmentPresentations = createEnvironmentPresentationAtoms({
17 serverConfigValueAtom: serverEnvironment.configValueAtom,
18 });
19
20 +export const { connectedEnvironmentIdsAtom } = createEnvironmentSummaryAtoms({
21 + catalogValueAtom: environmentCatalog.catalogValueAtom,
22 + presentationAtom: environmentPresentations.presentationAtom,
23 +});
24 +
25 +export const threadListEnvironmentsAtom = createThreadListEnvironmentsAtom(
26 + environmentServerConfigsAtom,
27 + connectedEnvironmentIdsAtom,
28 +);
29 +
30 const EMPTY_ENVIRONMENT_PRESENTATION_ATOM = Atom.make<EnvironmentPresentation | null>(null).pipe(
31 Atom.withLabel("mobile-environment-presentation:empty"),
32 );
apps/mobile/src/state/server.ts
-5
@@ -8,7 +8,6 @@ import { createEnvironmentServerConfigsAtom } from "@t3tools/client-runtime/stat
8 import { environmentCatalog } from "../connection/catalog";
9 import { connectionAtomRuntime } from "../connection/runtime";
10 import { environmentSession } from "./session";
11 -import { createThreadListEnvironmentsAtom } from "./thread-list-environments";
11
12 export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRuntime, {
13 initialConfigValueAtom: environmentSession.initialConfigValueAtom,
@@ -21,7 +20,3 @@ export const environmentServerConfigsAtom = createEnvironmentServerConfigsAtom({
20 catalogValueAtom: environmentCatalog.catalogValueAtom,
21 serverConfigValueAtom: serverEnvironment.configValueAtom,
22 });
24 -
25 -export const threadListEnvironmentsAtom = createThreadListEnvironmentsAtom(
26 - environmentServerConfigsAtom,
27 -);
apps/mobile/src/state/thread-list-environments.ts
+14 -5
@@ -14,8 +14,9 @@ export type ThreadListProvider = Pick<
14
15 const capabilityKeys = ["threadAutoSettleOptOut"] as const;
16
17 -function selectEnvironment(config: ServerConfig) {
17 +function selectEnvironment(config: ServerConfig, isConnected: boolean) {
18 return {
19 + isConnected,
20 providers: config.providers.map(
21 ({ instanceId, driver, enabled, displayName, accentColor, iconUrl }) => ({
22 instanceId,
@@ -60,13 +61,18 @@ function collectEnvironments(environments: ReadonlyMap<EnvironmentId, ListEnviro
61 // Every protocol-2 server supports these thread actions; they only wait for its config.
62 const loadedEnvironmentIds = new Set<EnvironmentId>();
63 const autoSettleOptOutEnvironmentIds = new Set<EnvironmentId>();
64 + const reorderableEnvironmentIds = new Set<EnvironmentId>();
65 const snoozePresetsByEnvironmentId = new Map<EnvironmentId, ListEnvironment["snoozePresets"]>();
64 - for (const [id, { providers, machineKind, capabilities, snoozePresets }] of environments) {
66 + for (const [
67 + id,
68 + { providers, machineKind, capabilities, isConnected, snoozePresets },
69 + ] of environments) {
70 providersByEnvironmentId.set(id, providers);
71 snoozePresetsByEnvironmentId.set(id, snoozePresets);
72 machineByEnvironmentId.set(id, machineKind);
73 loadedEnvironmentIds.add(id);
74 if (capabilities.threadAutoSettleOptOut === true) autoSettleOptOutEnvironmentIds.add(id);
75 + if (isConnected) reorderableEnvironmentIds.add(id);
76 }
77 return {
78 providersByEnvironmentId,
@@ -75,8 +81,8 @@ function collectEnvironments(environments: ReadonlyMap<EnvironmentId, ListEnviro
81 snoozeEnvironmentIds: loadedEnvironmentIds,
82 pinningEnvironmentIds: loadedEnvironmentIds,
83 autoSettleOptOutEnvironmentIds,
78 - pinReorderEnvironmentIds: loadedEnvironmentIds,
79 - activeReorderEnvironmentIds: loadedEnvironmentIds,
84 + pinReorderEnvironmentIds: reorderableEnvironmentIds,
85 + activeReorderEnvironmentIds: reorderableEnvironmentIds,
86 titleRegenerationEnvironmentIds: loadedEnvironmentIds,
87 snoozePresetsByEnvironmentId,
88 };
@@ -84,15 +90,17 @@ function collectEnvironments(environments: ReadonlyMap<EnvironmentId, ListEnviro
90
91 export function createThreadListEnvironmentsAtom(
92 configsAtom: Atom.Atom<ReadonlyMap<EnvironmentId, ServerConfig>>,
93 + connectedEnvironmentIdsAtom: Atom.Atom<ReadonlyArray<EnvironmentId>>,
94 ) {
95 let previous = new Map<EnvironmentId, ListEnvironment>();
96 let result = collectEnvironments(previous);
97 return Atom.make((get) => {
98 const configs = get(configsAtom);
99 + const connectedEnvironmentIds = new Set(get(connectedEnvironmentIdsAtom));
100 const next = new Map<EnvironmentId, ListEnvironment>();
101 let changed = configs.size !== previous.size;
102 for (const [id, config] of configs) {
95 - const selected = selectEnvironment(config);
103 + const selected = selectEnvironment(config, connectedEnvironmentIds.has(id));
104 const prior = previous.get(id);
105 if (prior && sameProviders(prior.providers, selected.providers)) {
106 selected.providers = prior.providers;
@@ -104,6 +112,7 @@ export function createThreadListEnvironmentsAtom(
112 prior &&
113 prior.providers === selected.providers &&
114 prior.machineKind === selected.machineKind &&
115 + prior.isConnected === selected.isConnected &&
116 prior.snoozePresets === selected.snoozePresets &&
117 capabilityKeys.every(
118 (key) => (prior.capabilities[key] === true) === (selected.capabilities[key] === true),
apps/web/src/components/Sidebar.logic.test.ts
+240
@@ -23,6 +23,7 @@ import {
23 sortInboxThreadsByReturn,
24 resolveSidebarDropTarget,
25 planSidebarThreadDrop,
26 + resolveSidebarReorderableThreadKeys,
27 sortPinnedThreadsForSidebar,
28 sortProjectsForSidebar,
29 sortScopedProjectsForSidebar,
@@ -36,6 +37,11 @@ import {
37 resolveSidebarFolderDot,
38 sidebarFolderExpansionKeys,
39 } from "./Sidebar.logic";
40 +import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
41 +import {
42 + sortActiveThreadsByOrderKey,
43 + sortPinnedThreadsByOrderKey,
44 +} from "@t3tools/client-runtime/state/thread-sort";
45 import { resolveProjectExpanded } from "../uiStateStore";
46 import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
47 import { EnvironmentId, ProjectId, ProviderInstanceId, RunId, ThreadId } from "@t3tools/contracts";
@@ -1230,6 +1236,240 @@ describe("Working shelf (beta)", () => {
1236 expect(above.kind === "move-active" && above.assignments[0]!.orderKey < "m").toBe(true);
1237 });
1238
1239 + describe("reordering with cached offline configuration", () => {
1240 + const onlineEnvironmentId = EnvironmentId.make("online");
1241 + const offlineEnvironmentId = EnvironmentId.make("offline");
1242 + const capabilities = {
1243 + repositoryIdentity: true,
1244 + threadPinning: true,
1245 + threadPinReorder: true,
1246 + threadActiveReorder: true,
1247 + };
1248 + const config = (environmentId: EnvironmentId) => ({
1249 + environment: {
1250 + environmentId,
1251 + label: environmentId,
1252 + platform: { os: "linux" as const, arch: "x64" as const },
1253 + serverVersion: "0.1.1",
1254 + capabilities,
1255 + },
1256 + });
1257 + const serverConfigs = new Map([
1258 + [onlineEnvironmentId, config(onlineEnvironmentId)],
1259 + [offlineEnvironmentId, config(offlineEnvironmentId)],
1260 + ]);
1261 + const thread = (
1262 + id: string,
1263 + environmentId = onlineEnvironmentId,
1264 + key: string | null = null,
1265 + ) => ({
1266 + id: ThreadId.make(id),
1267 + environmentId,
1268 + createdAt: `2026-03-09T${id === "offline" ? "12" : id === "online" ? "11" : "10"}:00:00.000Z`,
1269 + activeOrderKey: key,
1270 + pinOrderKey: key,
1271 + });
1272 + const keyOf = (entry: ReturnType<typeof thread>) =>
1273 + scopedThreadKey(scopeThreadRef(entry.environmentId, entry.id));
1274 + const online = thread("online");
1275 + const offline = thread("offline", offlineEnvironmentId);
1276 + const membership = (connectedEnvironmentIds = [onlineEnvironmentId]) =>
1277 + resolveSidebarReorderableThreadKeys({
1278 + threads: [online, offline],
1279 + serverConfigs,
1280 + connectedEnvironmentIds,
1281 + });
1282 + const planDrop = (input: {
1283 + section: "active" | "pinned";
1284 + rows: ReturnType<typeof thread>[];
1285 + moved: ReturnType<typeof thread>;
1286 + order: ReturnType<typeof thread>[];
1287 + from?: "active" | "pinned";
1288 + connectedEnvironmentIds?: EnvironmentId[];
1289 + }) => {
1290 + const writable = resolveSidebarReorderableThreadKeys({
1291 + threads: input.rows,
1292 + serverConfigs,
1293 + connectedEnvironmentIds: input.connectedEnvironmentIds ?? [onlineEnvironmentId],
1294 + });
1295 + const sort = (rows: typeof input.rows) =>
1296 + input.section === "active"
1297 + ? sortActiveThreadsByOrderKey(rows)
1298 + : sortPinnedThreadsByOrderKey(rows);
1299 + const originalOrder = sort(input.rows).map(keyOf);
1300 + const targetOrder = input.order.map(keyOf);
1301 + const keysById = new Map(input.rows.map((entry) => [keyOf(entry), entry.activeOrderKey]));
1302 + const plan = planSidebarThreadDrop({
1303 + activeKey: keyOf(input.moved),
1304 + activeSection: input.from ?? input.section,
1305 + target: { section: input.section, pinnedOrder: targetOrder, activeOrder: targetOrder },
1306 + pinnedOrder: originalOrder,
1307 + activeOrder: originalOrder,
1308 + pinnedKeysById: keysById,
1309 + activeKeysById: keysById,
1310 + reorderableKeys: writable.draggableThreadKeys,
1311 + activeReorderableKeys: writable.activeReorderableThreadKeys,
1312 + });
1313 + const assignments =
1314 + plan.kind === "move-active" || plan.kind === "reorder-pinned"
1315 + ? plan.assignments
1316 + : plan.kind === "pin"
1317 + ? [
1318 + ...plan.extraAssignments,
1319 + ...(plan.orderKey === undefined
1320 + ? []
1321 + : [{ id: keyOf(input.moved), orderKey: plan.orderKey }]),
1322 + ]
1323 + : [];
1324 + const assignedKeys = new Map(assignments.map(({ id, orderKey }) => [id, orderKey]));
1325 + const actualOrder = sort(
1326 + input.rows.map((entry) => ({
1327 + ...entry,
1328 + activeOrderKey: assignedKeys.get(keyOf(entry)) ?? entry.activeOrderKey,
1329 + pinOrderKey: assignedKeys.get(keyOf(entry)) ?? entry.pinOrderKey,
1330 + })),
1331 + ).map(keyOf);
1332 +
1333 + return { plan, assignments, actualOrder, targetOrder };
1334 + };
1335 +
1336 + it("excludes cached capable offline rows from both writable sets", () => {
1337 + const writable = membership();
1338 +
1339 + expect([...writable.draggableThreadKeys]).toEqual([keyOf(online)]);
1340 + expect([...writable.activeReorderableThreadKeys]).toEqual([keyOf(online)]);
1341 + expect(serverConfigs.has(offlineEnvironmentId)).toBe(true);
1342 + });
1343 +
1344 + it("updates membership through disconnect, reconnect, and missing configuration", () => {
1345 + expect(membership([]).draggableThreadKeys.size).toBe(0);
1346 + const connected = membership([onlineEnvironmentId, offlineEnvironmentId]);
1347 + expect(connected.draggableThreadKeys.size).toBe(2);
1348 + expect(connected.activeReorderableThreadKeys.size).toBe(2);
1349 +
1350 + const changed = resolveSidebarReorderableThreadKeys({
1351 + threads: [online, offline],
1352 + connectedEnvironmentIds: [onlineEnvironmentId, offlineEnvironmentId],
1353 + serverConfigs: new Map([[onlineEnvironmentId, config(onlineEnvironmentId)]]),
1354 + });
1355 + expect([...changed.draggableThreadKeys]).toEqual([keyOf(online)]);
1356 + expect([...changed.activeReorderableThreadKeys]).toEqual([keyOf(online)]);
1357 + });
1358 +
1359 + it.each(["active", "pinned"] as const)(
1360 + "replans a disconnected drag source in %s",
1361 + (section) => {
1362 + const bound = thread("offline", offlineEnvironmentId, "m");
1363 + const moved = thread("online", onlineEnvironmentId, "t");
1364 + const input = { section, rows: [bound, moved], moved, order: [moved, bound] };
1365 + expect(planDrop(input).plan.kind).toBe(
1366 + section === "active" ? "move-active" : "reorder-pinned",
1367 + );
1368 +
1369 + const disconnected = planDrop({ ...input, connectedEnvironmentIds: [] });
1370 +
1371 + expect(disconnected.plan).toEqual({ kind: "none" });
1372 + expect(disconnected.assignments).toEqual([]);
1373 + },
1374 + );
1375 +
1376 + it.each(["active", "pinned"] as const)("preserves a keyed offline bound in %s", (section) => {
1377 + const bound = thread("offline", offlineEnvironmentId, "m");
1378 + const moved = thread("online", onlineEnvironmentId, "t");
1379 + const result = planDrop({ section, rows: [bound, moved], moved, order: [moved, bound] });
1380 +
1381 + expect(result.plan.kind).toBe(section === "active" ? "move-active" : "reorder-pinned");
1382 + expect(result.assignments.map(({ id }) => id)).toEqual([keyOf(moved)]);
1383 + expect(result.actualOrder).toEqual(result.targetOrder);
1384 + });
1385 +
1386 + it.each(["active", "pinned"] as const)(
1387 + "rejects rebalancing a keyed offline bound in %s",
1388 + (section) => {
1389 + const bound = thread("offline", offlineEnvironmentId, "m");
1390 + const neighbor = thread("neighbor");
1391 + const result = planDrop({
1392 + section,
1393 + rows: [bound, online, neighbor],
1394 + moved: online,
1395 + order: [bound, neighbor, online],
1396 + });
1397 +
1398 + expect(result.plan).toEqual({ kind: "none" });
1399 + expect(result.assignments).toEqual([]);
1400 + },
1401 + );
1402 +
1403 + it.each(["active", "pinned"] as const)(
1404 + "rejects crossing the frozen keyless boundary in %s",
1405 + (section) => {
1406 + const bound = {
1407 + ...offline,
1408 + createdAt:
1409 + section === "active" ? "2026-03-09T12:00:00.000Z" : "2026-03-09T10:00:00.000Z",
1410 + };
1411 + const order = section === "active" ? [online, bound] : [bound, online];
1412 + const result = planDrop({ section, rows: [bound, online], moved: online, order });
1413 +
1414 + expect(result.plan).toEqual({ kind: "none" });
1415 + expect(result.assignments).toEqual([]);
1416 + },
1417 + );
1418 +
1419 + it.each(["active", "pinned"] as const)(
1420 + "allows realizable moves beside a frozen keyless row in %s",
1421 + (section) => {
1422 + const neighbor = thread("neighbor");
1423 + const order =
1424 + section === "active" ? [offline, neighbor, online] : [online, neighbor, offline];
1425 + const result = planDrop({
1426 + section,
1427 + rows: [offline, online, neighbor],
1428 + moved: online,
1429 + order,
1430 + });
1431 +
1432 + expect(result.plan.kind).toBe(section === "active" ? "move-active" : "reorder-pinned");
1433 + expect(result.assignments.length).toBeGreaterThan(0);
1434 + expect(result.assignments.every(({ id }) => id !== keyOf(offline))).toBe(true);
1435 + expect(result.actualOrder).toEqual(result.targetOrder);
1436 + },
1437 + );
1438 +
1439 + it.each(["active", "pinned"] as const)(
1440 + "checks fallback assignments to other rows at the %s boundary",
1441 + (section) => {
1442 + const neighbor = thread("neighbor");
1443 + const order =
1444 + section === "active" ? [neighbor, offline, online] : [online, offline, neighbor];
1445 + const result = planDrop({
1446 + section,
1447 + rows: [offline, online, neighbor],
1448 + moved: online,
1449 + order,
1450 + });
1451 +
1452 + expect(result.plan).toEqual({ kind: "none" });
1453 + },
1454 + );
1455 +
1456 + it.each(["active", "pinned"] as const)(
1457 + "rejects impossible pin/unpin placement across the %s boundary",
1458 + (section) => {
1459 + const order = section === "active" ? [online, offline] : [offline, online];
1460 + const result = planDrop({
1461 + section,
1462 + rows: [offline, online],
1463 + moved: online,
1464 + order,
1465 + from: section === "active" ? "pinned" : "active",
1466 + });
1467 +
1468 + expect(result.plan).toEqual({ kind: "none" });
1469 + },
1470 + );
1471 + });
1472 +
1473 it("only changes lifecycle when the inbox is time-ordered", () => {
1474 const base = {
1475 pinnedOrder: ["p1"],
apps/web/src/components/Sidebar.logic.ts
+50 -1
@@ -1,3 +1,5 @@
1 +import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
2 +import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
3 import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
4 import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
5 import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
@@ -309,6 +311,32 @@ export function sidebarThreadKeyAtY(list: HTMLElement, y: number): string | null
311 return key;
312 }
313
314 +export function resolveSidebarReorderableThreadKeys(input: {
315 + readonly threads: ReadonlyArray<Pick<SidebarThreadSummary, "environmentId" | "id">>;
316 + readonly serverConfigs: ReadonlyMap<EnvironmentId, Pick<EnvironmentServerConfig, "environment">>;
317 + readonly connectedEnvironmentIds: readonly EnvironmentId[];
318 +}) {
319 + const connectedEnvironmentIds = new Set(input.connectedEnvironmentIds);
320 + const draggableThreadKeys = new Set<string>();
321 + const activeReorderableThreadKeys = new Set<string>();
322 +
323 + for (const thread of input.threads) {
324 + // Config is cached for offline rendering, so its presence does not make a row writable.
325 + if (
326 + !connectedEnvironmentIds.has(thread.environmentId) ||
327 + !input.serverConfigs.has(thread.environmentId)
328 + ) {
329 + continue;
330 + }
331 +
332 + const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
333 + activeReorderableThreadKeys.add(threadKey);
334 + draggableThreadKeys.add(threadKey);
335 + }
336 +
337 + return { draggableThreadKeys, activeReorderableThreadKeys };
338 +}
339 +
340 export function planSidebarThreadDrop(input: {
341 readonly activeKey: string;
342 readonly activeSection: SidebarSection;
@@ -353,7 +381,28 @@ export function planSidebarThreadDrop(input: {
381 keysById,
382 movedId: activeKey,
383 });
356 - return assignments.every(({ id }) => writable.has(id)) ? assignments : null;
384 + if (assignments.some(({ id }) => !writable.has(id))) return null;
385 +
386 + // Keyless Active rows sort before keyed rows; keyless Pinned rows sort after them.
387 + // Materializing any row across a frozen keyless boundary cannot persist that position.
388 + const assignedIds = new Set(assignments.map(({ id }) => id));
389 + let hasFrozenKeylessBefore = false;
390 + let hasAssignedBefore = false;
391 + for (const id of order) {
392 + const isFrozenKeyless = !writable.has(id) && keysById.get(id) == null;
393 + const isAssigned = assignedIds.has(id);
394 + if (
395 + (target.section === "active" && isFrozenKeyless && hasAssignedBefore) ||
396 + (target.section === "pinned" && isAssigned && hasFrozenKeylessBefore)
397 + ) {
398 + return null;
399 + }
400 +
401 + hasFrozenKeylessBefore ||= isFrozenKeyless;
402 + hasAssignedBefore ||= isAssigned;
403 + }
404 +
405 + return assignments;
406 };
407 switch (target.section) {
408 case "active": {
apps/web/src/components/Sidebar.tsx
+16 -11
@@ -189,6 +189,7 @@ import {
189 resolveSidebarDropTarget,
190 resolveSidebarDropVerb,
191 resolveSidebarThreadSection,
192 + resolveSidebarReorderableThreadKeys,
193 searchSidebarThreads,
194 shouldCreateNewThreadInCurrentProject,
195 shouldNavigateAfterThreadPark,
@@ -339,6 +340,7 @@ interface SidebarThreadPartitionInput {
340 /** Tasks linked environments run for a listed thread; they show under it. */
341 readonly delegatedUnderParent: ReadonlySet<string>;
342 readonly serverConfigs: ReadonlyMap<EnvironmentId, EnvironmentServerConfig>;
343 + readonly connectedEnvironmentIds: readonly EnvironmentId[];
344 readonly optimisticDrop: SidebarOptimisticDrop | null;
345 readonly workingShelfEnabled: boolean;
346 /** Boring mode: folders list active threads by the user's latest message. */
@@ -399,6 +401,7 @@ function useSidebarThreads(input: {
401 readonly projectScopeKey: string | null;
402 readonly scopedProjectKeys: ReadonlySet<string> | null;
403 readonly serverConfigs: ReadonlyMap<EnvironmentId, EnvironmentServerConfig>;
404 + readonly connectedEnvironmentIds: readonly EnvironmentId[];
405 readonly optimisticDrop: SidebarOptimisticDrop | null;
406 readonly threads: readonly EnvironmentThreadShell[];
407 readonly delegatedUnderParent: ReadonlySet<string>;
@@ -412,6 +415,7 @@ function useSidebarThreads(input: {
415 projectScopeKey,
416 scopedProjectKeys,
417 serverConfigs,
418 + connectedEnvironmentIds,
419 optimisticDrop,
420 threads,
421 delegatedUnderParent,
@@ -462,6 +466,7 @@ function useSidebarThreads(input: {
466 scopedProjectKeys,
467 delegatedUnderParent,
468 serverConfigs,
469 + connectedEnvironmentIds,
470 optimisticDrop,
471 workingShelfEnabled,
472 sortActiveBySend: folderGroups !== null,
@@ -614,15 +619,14 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {
619 : active;
620 const snoozed: EnvironmentThreadShell[] = [];
621 const settled: EnvironmentThreadShell[] = [];
617 - const draggable = new Set<string>();
618 - const activeReorderable = new Set<string>();
622 + const { draggableThreadKeys, activeReorderableThreadKeys } = resolveSidebarReorderableThreadKeys({
623 + threads: visible,
624 + serverConfigs,
625 + connectedEnvironmentIds: input.connectedEnvironmentIds,
626 + });
627 for (const thread of visible) {
628 const configLoaded = serverConfigs.has(thread.environmentId);
629 const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
622 - if (configLoaded) {
623 - activeReorderable.add(threadKey);
624 - draggable.add(threadKey);
625 - }
630 if (optimisticDrop?.key === threadKey) {
631 const projected = applySidebarThreadDrop(
632 thread,
@@ -656,7 +660,7 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {
660 ).push(thread);
661 }
662 }
659 - // A loaded config gates dragging only; the sort must not depend on it, so web and mobile agree.
663 + // Availability gates dragging only; sorting must stay consistent across clients.
664 const sortedPinned = sortPinnedThreadsForSidebar(pinned);
665 const sortedActive = sortActiveBySend
666 ? sortWorkingThreadsBySend(active)
@@ -672,8 +676,8 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {
676 preferredIds: optimisticDrop.order,
677 getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
678 }),
675 - draggableThreadKeys: draggable,
676 - activeReorderableThreadKeys: activeReorderable,
679 + draggableThreadKeys,
680 + activeReorderableThreadKeys,
681 activeThreads:
682 optimisticDrop?.section !== "active" || optimisticDrop.order === null
683 ? sortedActive
@@ -1001,7 +1005,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1005 const threadSearchInputRef = useRef<HTMLInputElement>(null);
1006 const [threadSearchQuery, setThreadSearchQuery] = useState("");
1007 const [searchHighlightKey, setSearchHighlightKey] = useState<string | null>(null);
1004 - const searchEnvironmentIds = useConnectedEnvironmentIds();
1008 + const connectedEnvironmentIds = useConnectedEnvironmentIds();
1009 const queuePendingFileDrop = useSidebarPendingFileDropStore((s) => s.queuePendingFileDrop);
1010 const clearPendingFileDrop = useSidebarPendingFileDropStore((s) => s.clearPendingFileDrop);
1011 const [renamingThreadRef, setRenamingThreadRef] = useState<ScopedThreadRef | null>(null);
@@ -1145,7 +1149,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1149 const scopedProjectRefs = scopedProjectGroups.flatMap((project) => project.memberProjectRefs);
1150 const scopedProjectKeys = revealWidensScope ? null : chosenScopeProjectKeys;
1151 const threadSearch = useThreadSearch(
1148 - searchEnvironmentIds,
1152 + connectedEnvironmentIds,
1153 threadSearchQuery,
1154 scopedProjectGroups.length === 0
1155 ? {}
@@ -1277,6 +1281,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1281 projectScopeKey,
1282 scopedProjectKeys,
1283 serverConfigs,
1284 + connectedEnvironmentIds,
1285 optimisticDrop,
1286 threads,
1287 delegatedUnderParent,