TypeScript
fix: keep offline environments out of thread reorder writes (#22887)
Devesh Sangwan503bcaaf99f1
diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsxindex 1edb92f0d55..192755ec435 100644--- a/apps/mobile/src/features/home/HomeScreen.tsx+++ b/apps/mobile/src/features/home/HomeScreen.tsx@@ -53,7 +53,7 @@ import { useThreadListV2 } from "../threads/useThreadListV2";import { useThreadListNow } from "../threads/use-thread-list-now";import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";import { usePendingThreadOrder } from "../../state/thread-order";-import { threadListEnvironmentsAtom } from "../../state/server";+import { threadListEnvironmentsAtom } from "../../state/presentation";import type { PendingNewTask } from "../../state/use-pending-new-tasks";import { useQueuedThreadKeys } from "../../state/use-thread-outbox";import {diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.tsindex ec0f6a14558..9313aef2998 100644--- a/apps/mobile/src/features/home/useThreadListActions.test.ts+++ b/apps/mobile/src/features/home/useThreadListActions.test.ts@@ -13,6 +13,7 @@ import { AsyncResult } from "effect/reactivity";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";const state = vi.hoisted(() => ({+ connectedEnvironmentIds: [] as EnvironmentId[],pendingOrder: null as object | null,dropBusy: false,failedAction: null as string | null,@@ -60,6 +61,9 @@ vi.mock("../../state/session", () => ({readEnvironmentScope: (environmentId: string, scope: string) =>state.scopes.get(environmentId)?.has(scope) === true,}));+vi.mock("../../state/presentation", () => ({+ connectedEnvironmentIdsAtom: "connected-environments",+}));vi.mock("../../state/server", () => ({environmentServerConfigsAtom: "server-configs",}));@@ -69,28 +73,30 @@ vi.mock("../../state/atom-registry", () => ({state.dropBusy = value;},get: (atom: string) =>- atom === "thread-drop-busy"- ? state.dropBusy- : atom === "thread-shells"- ? state.shells- : atom === "queued-thread-keys"- ? new Set<string>()- : new Map(- [...state.scopes.keys()].map((environmentId) => [- environmentId,- {- environment: {- capabilities: {- threadSettlement: true,- threadSnooze: true,- threadPinning: true,- threadPinReorder: true,- threadTitleRegeneration: true,+ atom === "connected-environments"+ ? state.connectedEnvironmentIds+ : atom === "thread-drop-busy"+ ? state.dropBusy+ : atom === "thread-shells"+ ? state.shells+ : atom === "queued-thread-keys"+ ? new Set<string>()+ : new Map(+ [...state.scopes.keys()].map((environmentId) => [+ environmentId,+ {+ environment: {+ capabilities: {+ threadSettlement: true,+ threadSnooze: true,+ threadPinning: true,+ threadPinReorder: true,+ threadTitleRegeneration: true,+ },},},- },- ]),- ),+ ]),+ ),},}));vi.mock("../../state/use-atom-command", () => ({@@ -130,6 +136,7 @@ vi.mock("../../state/threads", () => ({"pin","unpin","reorderPin",+ "reorderActive","updateMetadata",].map((action) => [action,@@ -179,6 +186,7 @@ const mutationCases = [] as const;beforeEach(() => {+ state.connectedEnvironmentIds = [primaryEnvironmentId, otherEnvironmentId];state.failedAction = null;state.archivedRefreshes = [];state.pendingOrder = null;@@ -286,6 +294,76 @@ describe("pinned thread operation permissions", () => {});});+describe("thread reorder connection availability", () => {+ it.each(["active", "pinned"] as const)(+ "rejects %s materialization involving a cached capable offline neighbor",+ async (section) => {+ const moved = makeThread({+ pinnedAt: section === "pinned" ? "2026-09-02T00:00:00.000Z" : null,+ });+ state.shells = [+ moved,+ makeThread({+ id: ThreadId.make("offline-neighbor"),+ environmentId: otherEnvironmentId,+ createdAt: "2026-09-02T00:00:00.000Z",+ pinnedAt: moved.pinnedAt,+ }),+ ];+ state.scopes.get(otherEnvironmentId)?.add(AuthOrchestrationOperateScope);+ state.connectedEnvironmentIds = [primaryEnvironmentId];++ const { moveThread } = useThreadListActions();+ expect(await moveThread(moved, "up")).toBe(false);+ expect(state.requests).toEqual([]);++ state.connectedEnvironmentIds = [primaryEnvironmentId, otherEnvironmentId];++ expect(await moveThread(moved, "up")).toBe(true);+ expect(state.requests).toHaveLength(2);+ expect(new Set(state.requests.map(({ environmentId }) => environmentId))).toEqual(+ new Set([primaryEnvironmentId, otherEnvironmentId]),+ );+ },+ );++ it.each(["active", "pinned"] as const)(+ "uses the latest connection state in a retained %s move callback",+ async (section) => {+ const moved = makeThread({+ pinnedAt: section === "pinned" ? "2026-09-02T00:00:00.000Z" : null,+ pinOrderKey: section === "pinned" ? "m" : null,+ activeOrderKey: section === "active" ? "m" : null,+ });+ state.shells = [+ moved,+ makeThread({+ id: ThreadId.make("offline-neighbor"),+ environmentId: otherEnvironmentId,+ pinnedAt: moved.pinnedAt,+ pinOrderKey: section === "pinned" ? "g" : null,+ activeOrderKey: section === "active" ? "g" : null,+ }),+ ];+ const { moveThread } = useThreadListActions();+ state.connectedEnvironmentIds = [];++ expect(await moveThread(moved, "up")).toBe(false);+ expect(state.requests).toEqual([]);++ state.connectedEnvironmentIds = [primaryEnvironmentId];++ expect(await moveThread(moved, "up")).toBe(true);+ expect(state.requests).toEqual([+ expect.objectContaining({+ action: section === "pinned" ? "reorderPin" : "reorderActive",+ environmentId: primaryEnvironmentId,+ }),+ ]);+ },+ );+});+describe("thread action undo", () => {it.each([["settleThread", "settle", "Settled", "unsettle"],diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.tsindex cac37f05528..248c4369053 100644--- a/apps/mobile/src/features/home/useThreadListActions.ts+++ b/apps/mobile/src/features/home/useThreadListActions.ts@@ -15,6 +15,7 @@ import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThreimport { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";import { appAtomRegistry } from "../../state/atom-registry";import { environmentServerConfigsAtom } from "../../state/server";+import { connectedEnvironmentIdsAtom } from "../../state/presentation";import { readEnvironmentScope } from "../../state/session";import { environmentThreadShells, threadEnvironment } from "../../state/threads";import { queuedThreadKeysAtom } from "../../state/use-thread-outbox";@@ -591,6 +592,10 @@ export function useThreadListActions(): {return settled;}const configs = appAtomRegistry.get(environmentServerConfigsAtom);+ const connectedEnvironmentIds = new Set(appAtomRegistry.get(connectedEnvironmentIdsAtom));++ if (!connectedEnvironmentIds.has(thread.environmentId)) return false;+if (!configs.has(thread.environmentId)) {Dialog.alert("Could not move thread",@@ -610,7 +615,9 @@ export function useThreadListActions(): {allThreads: shells,ordered,section,- reorderableEnvironmentIds: new Set(configs.keys()),+ reorderableEnvironmentIds: new Set(+ [...configs.keys()].filter((environmentId) => connectedEnvironmentIds.has(environmentId)),+ ),})(scopedThreadKey(thread.environmentId, thread.id), direction);if (assignments === null) return false;const lifecycle = threadDropLifecycle(thread, section, new Date().toISOString());diff --git a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsxindex 5b9afb49341..603fac3d00f 100644--- a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx+++ b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx@@ -15,6 +15,7 @@ import { AppText as Text } from "../../components/ui/AppText";import { SymbolView } from "../../components/ui/AppSymbol";import { scopedThreadKey } from "../../lib/scopedEntities";import { environmentServerConfigsAtom } from "../../state/server";+import { threadListEnvironmentsAtom } from "../../state/presentation";import { environmentThreadShells } from "../../state/threads";import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort";import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../../state/olderSettledShelf";@@ -164,6 +165,7 @@ function DragHandle(props: {function ThreadArrangementSheet(props: { onClose: () => void }) {const threads = useAtomValue(environmentThreadShells.navigationThreadShellsAtom);const configs = useAtomValue(environmentServerConfigsAtom);+ const listEnvironments = useAtomValue(threadListEnvironmentsAtom);const queuedThreadKeys = useAtomValue(queuedThreadKeysAtom);const pendingOrder = useAtomValue(pendingThreadOrderAtom);const dropBusy = useAtomValue(threadDropBusyAtom);@@ -214,12 +216,15 @@ function ThreadArrangementSheet(props: { onClose: () => void }) {ordered: sections[section],allThreads: threads,section,- reorderableEnvironmentIds: new Set(- section === "pinned" || !workingShelfEnabled ? configs.keys() : [],- ),+ reorderableEnvironmentIds:+ section === "pinned"+ ? listEnvironments.pinReorderEnvironmentIds+ : workingShelfEnabled+ ? new Set()+ : listEnvironments.activeReorderEnvironmentIds,});return { pinned: planner("pinned"), active: planner("active") };- }, [sections, threads, configs, workingShelfEnabled]);+ }, [sections, threads, listEnvironments, workingShelfEnabled]);const rows = useMemo(() => {const result: Row[] = [];let offset = 0;@@ -468,7 +473,12 @@ function ThreadArrangementSheet(props: { onClose: () => void }) {disabled={dropBusy ||pendingOrder !== null ||- !configs.has(thread.environmentId)+ (!listEnvironments.pinReorderEnvironmentIds.has(+ thread.environmentId,+ ) &&+ !listEnvironments.activeReorderEnvironmentIds.has(+ thread.environmentId,+ ))}sectionActions={sectionActions}onSectionMove={(section) => {diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsxindex 6ba0583a7a5..7975097f6a9 100644--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx@@ -37,7 +37,7 @@ import { useThreadSearch } from "../../state/queries";import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";import { useThreadListNow } from "./use-thread-list-now";import { usePendingThreadOrder } from "../../state/thread-order";-import { threadListEnvironmentsAtom } from "../../state/server";+import { threadListEnvironmentsAtom } from "../../state/presentation";import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";import { useQueuedThreadKeys } from "../../state/use-thread-outbox";import { useWorkspaceState } from "../../state/workspace";diff --git a/apps/mobile/src/features/threads/thread-provider-instance.test.ts b/apps/mobile/src/features/threads/thread-provider-instance.test.tsindex be63be589b9..56ddec3ab15 100644--- a/apps/mobile/src/features/threads/thread-provider-instance.test.ts+++ b/apps/mobile/src/features/threads/thread-provider-instance.test.ts@@ -9,6 +9,8 @@ import {import { describe, expect, it } from "vite-plus/test";import { Atom, AtomRegistry } from "effect/reactivity";+import { computeThreadMoveAvailability, createThreadMovePlanner } from "./threadOrder";+import { makeThreadShellFixture } from "../../test-fixtures";import { createThreadListEnvironmentsAtom } from "../../state/thread-list-environments";import {@@ -127,7 +129,7 @@ describe("createThreadRowProviderInstanceResolver", () => {const configs = Atom.make<ReadonlyMap<EnvironmentId, ServerConfig>>(new Map([[environmentId, config]]),);- const environments = createThreadListEnvironmentsAtom(configs);+ const environments = createThreadListEnvironmentsAtom(configs, Atom.make([environmentId]));const registry = AtomRegistry.make();registry.mount(environments);try {@@ -168,3 +170,133 @@ describe("createThreadRowProviderInstanceResolver", () => {}});});++describe("thread list reorder availability", () => {+ it.each(["active", "pinned"] as const)(+ "updates %s moves on disconnect and reconnect without changing cached config",+ (section) => {+ const onlineId = EnvironmentId.make("online");+ const offlineId = EnvironmentId.make("offline");+ const config = makeConfig([{ instanceId: "codex", driver: "codex" }]);+ const configs = Atom.make<ReadonlyMap<EnvironmentId, ServerConfig>>(+ new Map([+ [onlineId, config],+ [offlineId, config],+ ]),+ );+ const connected = Atom.make<ReadonlyArray<EnvironmentId>>([onlineId, offlineId]);+ const environments = createThreadListEnvironmentsAtom(configs, connected);+ const registry = AtomRegistry.make();+ registry.mount(environments);+ try {+ const ordered = [onlineId, offlineId].map((environmentId, index) =>+ makeThreadShellFixture({+ environmentId,+ id: ThreadId.make(`thread-${index}`),+ pinnedAt: section === "pinned" ? "2026-09-02T00:00:00.000Z" : null,+ }),+ );+ const movedId = `${onlineId}:thread-0`;+ const plannerInput = () => {+ const current = registry.get(environments);+ return {+ ordered,+ section,+ reorderableEnvironmentIds:+ section === "pinned"+ ? current.pinReorderEnvironmentIds+ : current.activeReorderEnvironmentIds,+ };+ };+ expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toHaveLength(2);+ const before = registry.get(environments);++ registry.set(connected, [onlineId]);++ expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull();+ expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(false);+ expect(registry.get(environments).pinningEnvironmentIds.has(offlineId)).toBe(true);+ expect(registry.get(environments).settlementEnvironmentIds.has(offlineId)).toBe(true);+ expect(registry.get(environments).providersByEnvironmentId.get(offlineId)).toBe(+ before.providersByEnvironmentId.get(offlineId),+ );++ const keyedInput = {+ ...plannerInput(),+ ordered: ordered.map((row, index) => ({+ ...row,+ pinOrderKey: section === "pinned" ? (index === 0 ? "bb" : "dd") : null,+ activeOrderKey: section === "active" ? (index === 0 ? "bb" : "dd") : null,+ })),+ };+ expect(createThreadMovePlanner(keyedInput)(movedId, "down")).toEqual([+ expect.objectContaining({ id: movedId }),+ ]);+ expect(createThreadMovePlanner(keyedInput)(`${offlineId}:thread-1`, "up")).toBeNull();+ expect(computeThreadMoveAvailability(keyedInput).get(movedId)?.canMoveDown).toBe(true);+ expect(computeThreadMoveAvailability(keyedInput).get(`${offlineId}:thread-1`)).toEqual({+ canMoveUp: false,+ canMoveDown: false,+ });++ const updatedConfig = {+ ...config,+ settings: {+ ...config.settings,+ snoozePresets: [{ kind: "after" as const, minutes: 90 }],+ },+ };+ registry.set(+ configs,+ new Map([+ [onlineId, config],+ [offlineId, updatedConfig],+ ]),+ );++ const updated = registry.get(environments);+ expect(updated.snoozePresetsByEnvironmentId.get(offlineId)).toEqual(+ updatedConfig.settings.snoozePresets,+ );+ expect(updated.pinReorderEnvironmentIds.has(offlineId)).toBe(false);+ expect(updated.activeReorderEnvironmentIds.has(offlineId)).toBe(false);+ expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull();++ registry.set(+ configs,+ new Map([+ [onlineId, config],+ [+ offlineId,+ {+ ...updatedConfig,+ settings: {+ ...updatedConfig.settings,+ snoozePresets: updatedConfig.settings.snoozePresets.map((preset) => ({+ ...preset,+ })),+ },+ },+ ],+ ]),+ );+ expect(registry.get(environments)).toBe(updated);++ registry.set(connected, [onlineId, offlineId]);++ expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toHaveLength(2);+ expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(true);+ expect(registry.get(environments).snoozePresetsByEnvironmentId.get(offlineId)).toBe(+ updated.snoozePresetsByEnvironmentId.get(offlineId),+ );++ registry.set(configs, new Map([[onlineId, config]]));++ expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull();+ expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(false);+ } finally {+ registry.dispose();+ }+ },+ );+});diff --git a/apps/mobile/src/state/presentation.ts b/apps/mobile/src/state/presentation.tsindex 437a4b7ccb6..68b2d278cd9 100644--- a/apps/mobile/src/state/presentation.ts+++ b/apps/mobile/src/state/presentation.ts@@ -1,11 +1,15 @@import { useAtomValue } from "@effect/atom-react";import type { EnvironmentPresentation } from "@t3tools/client-runtime/connection";-import { createEnvironmentPresentationAtoms } from "@t3tools/client-runtime/state/presentation";+import {+ createEnvironmentPresentationAtoms,+ createEnvironmentSummaryAtoms,+} from "@t3tools/client-runtime/state/presentation";import type { EnvironmentId } from "@t3tools/contracts";import { Atom } from "effect/reactivity";import { environmentCatalog } from "../connection/catalog";-import { serverEnvironment } from "./server";+import { environmentServerConfigsAtom, serverEnvironment } from "./server";+import { createThreadListEnvironmentsAtom } from "./thread-list-environments";export const environmentPresentations = createEnvironmentPresentationAtoms({catalogValueAtom: environmentCatalog.catalogValueAtom,@@ -13,6 +17,16 @@ export const environmentPresentations = createEnvironmentPresentationAtoms({serverConfigValueAtom: serverEnvironment.configValueAtom,});+export const { connectedEnvironmentIdsAtom } = createEnvironmentSummaryAtoms({+ catalogValueAtom: environmentCatalog.catalogValueAtom,+ presentationAtom: environmentPresentations.presentationAtom,+});++export const threadListEnvironmentsAtom = createThreadListEnvironmentsAtom(+ environmentServerConfigsAtom,+ connectedEnvironmentIdsAtom,+);+const EMPTY_ENVIRONMENT_PRESENTATION_ATOM = Atom.make<EnvironmentPresentation | null>(null).pipe(Atom.withLabel("mobile-environment-presentation:empty"),);diff --git a/apps/mobile/src/state/server.ts b/apps/mobile/src/state/server.tsindex 991fd72fdba..8de9354d385 100644--- a/apps/mobile/src/state/server.ts+++ b/apps/mobile/src/state/server.ts@@ -8,7 +8,6 @@ import { createEnvironmentServerConfigsAtom } from "@t3tools/client-runtime/statimport { environmentCatalog } from "../connection/catalog";import { connectionAtomRuntime } from "../connection/runtime";import { environmentSession } from "./session";-import { createThreadListEnvironmentsAtom } from "./thread-list-environments";export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRuntime, {initialConfigValueAtom: environmentSession.initialConfigValueAtom,@@ -21,7 +20,3 @@ export const environmentServerConfigsAtom = createEnvironmentServerConfigsAtom({catalogValueAtom: environmentCatalog.catalogValueAtom,serverConfigValueAtom: serverEnvironment.configValueAtom,});--export const threadListEnvironmentsAtom = createThreadListEnvironmentsAtom(- environmentServerConfigsAtom,-);diff --git a/apps/mobile/src/state/thread-list-environments.ts b/apps/mobile/src/state/thread-list-environments.tsindex 0bf3fff4e35..9a2a6f42990 100644--- a/apps/mobile/src/state/thread-list-environments.ts+++ b/apps/mobile/src/state/thread-list-environments.ts@@ -14,8 +14,9 @@ export type ThreadListProvider = Pick<const capabilityKeys = ["threadAutoSettleOptOut"] as const;-function selectEnvironment(config: ServerConfig) {+function selectEnvironment(config: ServerConfig, isConnected: boolean) {return {+ isConnected,providers: config.providers.map(({ instanceId, driver, enabled, displayName, accentColor, iconUrl }) => ({instanceId,@@ -60,13 +61,18 @@ function collectEnvironments(environments: ReadonlyMap<EnvironmentId, ListEnviro// Every protocol-2 server supports these thread actions; they only wait for its config.const loadedEnvironmentIds = new Set<EnvironmentId>();const autoSettleOptOutEnvironmentIds = new Set<EnvironmentId>();+ const reorderableEnvironmentIds = new Set<EnvironmentId>();const snoozePresetsByEnvironmentId = new Map<EnvironmentId, ListEnvironment["snoozePresets"]>();- for (const [id, { providers, machineKind, capabilities, snoozePresets }] of environments) {+ for (const [+ id,+ { providers, machineKind, capabilities, isConnected, snoozePresets },+ ] of environments) {providersByEnvironmentId.set(id, providers);snoozePresetsByEnvironmentId.set(id, snoozePresets);machineByEnvironmentId.set(id, machineKind);loadedEnvironmentIds.add(id);if (capabilities.threadAutoSettleOptOut === true) autoSettleOptOutEnvironmentIds.add(id);+ if (isConnected) reorderableEnvironmentIds.add(id);}return {providersByEnvironmentId,@@ -75,8 +81,8 @@ function collectEnvironments(environments: ReadonlyMap<EnvironmentId, ListEnvirosnoozeEnvironmentIds: loadedEnvironmentIds,pinningEnvironmentIds: loadedEnvironmentIds,autoSettleOptOutEnvironmentIds,- pinReorderEnvironmentIds: loadedEnvironmentIds,- activeReorderEnvironmentIds: loadedEnvironmentIds,+ pinReorderEnvironmentIds: reorderableEnvironmentIds,+ activeReorderEnvironmentIds: reorderableEnvironmentIds,titleRegenerationEnvironmentIds: loadedEnvironmentIds,snoozePresetsByEnvironmentId,};@@ -84,15 +90,17 @@ function collectEnvironments(environments: ReadonlyMap<EnvironmentId, ListEnviroexport function createThreadListEnvironmentsAtom(configsAtom: Atom.Atom<ReadonlyMap<EnvironmentId, ServerConfig>>,+ connectedEnvironmentIdsAtom: Atom.Atom<ReadonlyArray<EnvironmentId>>,) {let previous = new Map<EnvironmentId, ListEnvironment>();let result = collectEnvironments(previous);return Atom.make((get) => {const configs = get(configsAtom);+ const connectedEnvironmentIds = new Set(get(connectedEnvironmentIdsAtom));const next = new Map<EnvironmentId, ListEnvironment>();let changed = configs.size !== previous.size;for (const [id, config] of configs) {- const selected = selectEnvironment(config);+ const selected = selectEnvironment(config, connectedEnvironmentIds.has(id));const prior = previous.get(id);if (prior && sameProviders(prior.providers, selected.providers)) {selected.providers = prior.providers;@@ -104,6 +112,7 @@ export function createThreadListEnvironmentsAtom(prior &&prior.providers === selected.providers &&prior.machineKind === selected.machineKind &&+ prior.isConnected === selected.isConnected &&prior.snoozePresets === selected.snoozePresets &&capabilityKeys.every((key) => (prior.capabilities[key] === true) === (selected.capabilities[key] === true),diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.tsindex e4fa68a6520..68d85776906 100644--- a/apps/web/src/components/Sidebar.logic.test.ts+++ b/apps/web/src/components/Sidebar.logic.test.ts@@ -23,6 +23,7 @@ import {sortInboxThreadsByReturn,resolveSidebarDropTarget,planSidebarThreadDrop,+ resolveSidebarReorderableThreadKeys,sortPinnedThreadsForSidebar,sortProjectsForSidebar,sortScopedProjectsForSidebar,@@ -36,6 +37,11 @@ import {resolveSidebarFolderDot,sidebarFolderExpansionKeys,} from "./Sidebar.logic";+import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";+import {+ sortActiveThreadsByOrderKey,+ sortPinnedThreadsByOrderKey,+} from "@t3tools/client-runtime/state/thread-sort";import { resolveProjectExpanded } from "../uiStateStore";import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";import { EnvironmentId, ProjectId, ProviderInstanceId, RunId, ThreadId } from "@t3tools/contracts";@@ -1230,6 +1236,240 @@ describe("Working shelf (beta)", () => {expect(above.kind === "move-active" && above.assignments[0]!.orderKey < "m").toBe(true);});+ describe("reordering with cached offline configuration", () => {+ const onlineEnvironmentId = EnvironmentId.make("online");+ const offlineEnvironmentId = EnvironmentId.make("offline");+ const capabilities = {+ repositoryIdentity: true,+ threadPinning: true,+ threadPinReorder: true,+ threadActiveReorder: true,+ };+ const config = (environmentId: EnvironmentId) => ({+ environment: {+ environmentId,+ label: environmentId,+ platform: { os: "linux" as const, arch: "x64" as const },+ serverVersion: "0.1.1",+ capabilities,+ },+ });+ const serverConfigs = new Map([+ [onlineEnvironmentId, config(onlineEnvironmentId)],+ [offlineEnvironmentId, config(offlineEnvironmentId)],+ ]);+ const thread = (+ id: string,+ environmentId = onlineEnvironmentId,+ key: string | null = null,+ ) => ({+ id: ThreadId.make(id),+ environmentId,+ createdAt: `2026-03-09T${id === "offline" ? "12" : id === "online" ? "11" : "10"}:00:00.000Z`,+ activeOrderKey: key,+ pinOrderKey: key,+ });+ const keyOf = (entry: ReturnType<typeof thread>) =>+ scopedThreadKey(scopeThreadRef(entry.environmentId, entry.id));+ const online = thread("online");+ const offline = thread("offline", offlineEnvironmentId);+ const membership = (connectedEnvironmentIds = [onlineEnvironmentId]) =>+ resolveSidebarReorderableThreadKeys({+ threads: [online, offline],+ serverConfigs,+ connectedEnvironmentIds,+ });+ const planDrop = (input: {+ section: "active" | "pinned";+ rows: ReturnType<typeof thread>[];+ moved: ReturnType<typeof thread>;+ order: ReturnType<typeof thread>[];+ from?: "active" | "pinned";+ connectedEnvironmentIds?: EnvironmentId[];+ }) => {+ const writable = resolveSidebarReorderableThreadKeys({+ threads: input.rows,+ serverConfigs,+ connectedEnvironmentIds: input.connectedEnvironmentIds ?? [onlineEnvironmentId],+ });+ const sort = (rows: typeof input.rows) =>+ input.section === "active"+ ? sortActiveThreadsByOrderKey(rows)+ : sortPinnedThreadsByOrderKey(rows);+ const originalOrder = sort(input.rows).map(keyOf);+ const targetOrder = input.order.map(keyOf);+ const keysById = new Map(input.rows.map((entry) => [keyOf(entry), entry.activeOrderKey]));+ const plan = planSidebarThreadDrop({+ activeKey: keyOf(input.moved),+ activeSection: input.from ?? input.section,+ target: { section: input.section, pinnedOrder: targetOrder, activeOrder: targetOrder },+ pinnedOrder: originalOrder,+ activeOrder: originalOrder,+ pinnedKeysById: keysById,+ activeKeysById: keysById,+ reorderableKeys: writable.draggableThreadKeys,+ activeReorderableKeys: writable.activeReorderableThreadKeys,+ });+ const assignments =+ plan.kind === "move-active" || plan.kind === "reorder-pinned"+ ? plan.assignments+ : plan.kind === "pin"+ ? [+ ...plan.extraAssignments,+ ...(plan.orderKey === undefined+ ? []+ : [{ id: keyOf(input.moved), orderKey: plan.orderKey }]),+ ]+ : [];+ const assignedKeys = new Map(assignments.map(({ id, orderKey }) => [id, orderKey]));+ const actualOrder = sort(+ input.rows.map((entry) => ({+ ...entry,+ activeOrderKey: assignedKeys.get(keyOf(entry)) ?? entry.activeOrderKey,+ pinOrderKey: assignedKeys.get(keyOf(entry)) ?? entry.pinOrderKey,+ })),+ ).map(keyOf);++ return { plan, assignments, actualOrder, targetOrder };+ };++ it("excludes cached capable offline rows from both writable sets", () => {+ const writable = membership();++ expect([...writable.draggableThreadKeys]).toEqual([keyOf(online)]);+ expect([...writable.activeReorderableThreadKeys]).toEqual([keyOf(online)]);+ expect(serverConfigs.has(offlineEnvironmentId)).toBe(true);+ });++ it("updates membership through disconnect, reconnect, and missing configuration", () => {+ expect(membership([]).draggableThreadKeys.size).toBe(0);+ const connected = membership([onlineEnvironmentId, offlineEnvironmentId]);+ expect(connected.draggableThreadKeys.size).toBe(2);+ expect(connected.activeReorderableThreadKeys.size).toBe(2);++ const changed = resolveSidebarReorderableThreadKeys({+ threads: [online, offline],+ connectedEnvironmentIds: [onlineEnvironmentId, offlineEnvironmentId],+ serverConfigs: new Map([[onlineEnvironmentId, config(onlineEnvironmentId)]]),+ });+ expect([...changed.draggableThreadKeys]).toEqual([keyOf(online)]);+ expect([...changed.activeReorderableThreadKeys]).toEqual([keyOf(online)]);+ });++ it.each(["active", "pinned"] as const)(+ "replans a disconnected drag source in %s",+ (section) => {+ const bound = thread("offline", offlineEnvironmentId, "m");+ const moved = thread("online", onlineEnvironmentId, "t");+ const input = { section, rows: [bound, moved], moved, order: [moved, bound] };+ expect(planDrop(input).plan.kind).toBe(+ section === "active" ? "move-active" : "reorder-pinned",+ );++ const disconnected = planDrop({ ...input, connectedEnvironmentIds: [] });++ expect(disconnected.plan).toEqual({ kind: "none" });+ expect(disconnected.assignments).toEqual([]);+ },+ );++ it.each(["active", "pinned"] as const)("preserves a keyed offline bound in %s", (section) => {+ const bound = thread("offline", offlineEnvironmentId, "m");+ const moved = thread("online", onlineEnvironmentId, "t");+ const result = planDrop({ section, rows: [bound, moved], moved, order: [moved, bound] });++ expect(result.plan.kind).toBe(section === "active" ? "move-active" : "reorder-pinned");+ expect(result.assignments.map(({ id }) => id)).toEqual([keyOf(moved)]);+ expect(result.actualOrder).toEqual(result.targetOrder);+ });++ it.each(["active", "pinned"] as const)(+ "rejects rebalancing a keyed offline bound in %s",+ (section) => {+ const bound = thread("offline", offlineEnvironmentId, "m");+ const neighbor = thread("neighbor");+ const result = planDrop({+ section,+ rows: [bound, online, neighbor],+ moved: online,+ order: [bound, neighbor, online],+ });++ expect(result.plan).toEqual({ kind: "none" });+ expect(result.assignments).toEqual([]);+ },+ );++ it.each(["active", "pinned"] as const)(+ "rejects crossing the frozen keyless boundary in %s",+ (section) => {+ const bound = {+ ...offline,+ createdAt:+ section === "active" ? "2026-03-09T12:00:00.000Z" : "2026-03-09T10:00:00.000Z",+ };+ const order = section === "active" ? [online, bound] : [bound, online];+ const result = planDrop({ section, rows: [bound, online], moved: online, order });++ expect(result.plan).toEqual({ kind: "none" });+ expect(result.assignments).toEqual([]);+ },+ );++ it.each(["active", "pinned"] as const)(+ "allows realizable moves beside a frozen keyless row in %s",+ (section) => {+ const neighbor = thread("neighbor");+ const order =+ section === "active" ? [offline, neighbor, online] : [online, neighbor, offline];+ const result = planDrop({+ section,+ rows: [offline, online, neighbor],+ moved: online,+ order,+ });++ expect(result.plan.kind).toBe(section === "active" ? "move-active" : "reorder-pinned");+ expect(result.assignments.length).toBeGreaterThan(0);+ expect(result.assignments.every(({ id }) => id !== keyOf(offline))).toBe(true);+ expect(result.actualOrder).toEqual(result.targetOrder);+ },+ );++ it.each(["active", "pinned"] as const)(+ "checks fallback assignments to other rows at the %s boundary",+ (section) => {+ const neighbor = thread("neighbor");+ const order =+ section === "active" ? [neighbor, offline, online] : [online, offline, neighbor];+ const result = planDrop({+ section,+ rows: [offline, online, neighbor],+ moved: online,+ order,+ });++ expect(result.plan).toEqual({ kind: "none" });+ },+ );++ it.each(["active", "pinned"] as const)(+ "rejects impossible pin/unpin placement across the %s boundary",+ (section) => {+ const order = section === "active" ? [online, offline] : [offline, online];+ const result = planDrop({+ section,+ rows: [offline, online],+ moved: online,+ order,+ from: section === "active" ? "pinned" : "active",+ });++ expect(result.plan).toEqual({ kind: "none" });+ },+ );+ });+it("only changes lifecycle when the inbox is time-ordered", () => {const base = {pinnedOrder: ["p1"],diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex efd8244f8c2..43c87f530e4 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -1,3 +1,5 @@+import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";+import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";@@ -309,6 +311,32 @@ export function sidebarThreadKeyAtY(list: HTMLElement, y: number): string | nullreturn key;}+export function resolveSidebarReorderableThreadKeys(input: {+ readonly threads: ReadonlyArray<Pick<SidebarThreadSummary, "environmentId" | "id">>;+ readonly serverConfigs: ReadonlyMap<EnvironmentId, Pick<EnvironmentServerConfig, "environment">>;+ readonly connectedEnvironmentIds: readonly EnvironmentId[];+}) {+ const connectedEnvironmentIds = new Set(input.connectedEnvironmentIds);+ const draggableThreadKeys = new Set<string>();+ const activeReorderableThreadKeys = new Set<string>();++ for (const thread of input.threads) {+ // Config is cached for offline rendering, so its presence does not make a row writable.+ if (+ !connectedEnvironmentIds.has(thread.environmentId) ||+ !input.serverConfigs.has(thread.environmentId)+ ) {+ continue;+ }++ const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));+ activeReorderableThreadKeys.add(threadKey);+ draggableThreadKeys.add(threadKey);+ }++ return { draggableThreadKeys, activeReorderableThreadKeys };+}+export function planSidebarThreadDrop(input: {readonly activeKey: string;readonly activeSection: SidebarSection;@@ -353,7 +381,28 @@ export function planSidebarThreadDrop(input: {keysById,movedId: activeKey,});- return assignments.every(({ id }) => writable.has(id)) ? assignments : null;+ if (assignments.some(({ id }) => !writable.has(id))) return null;++ // Keyless Active rows sort before keyed rows; keyless Pinned rows sort after them.+ // Materializing any row across a frozen keyless boundary cannot persist that position.+ const assignedIds = new Set(assignments.map(({ id }) => id));+ let hasFrozenKeylessBefore = false;+ let hasAssignedBefore = false;+ for (const id of order) {+ const isFrozenKeyless = !writable.has(id) && keysById.get(id) == null;+ const isAssigned = assignedIds.has(id);+ if (+ (target.section === "active" && isFrozenKeyless && hasAssignedBefore) ||+ (target.section === "pinned" && isAssigned && hasFrozenKeylessBefore)+ ) {+ return null;+ }++ hasFrozenKeylessBefore ||= isFrozenKeyless;+ hasAssignedBefore ||= isAssigned;+ }++ return assignments;};switch (target.section) {case "active": {diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex de16be6d2dc..3c09b32bd2d 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -189,6 +189,7 @@ import {resolveSidebarDropTarget,resolveSidebarDropVerb,resolveSidebarThreadSection,+ resolveSidebarReorderableThreadKeys,searchSidebarThreads,shouldCreateNewThreadInCurrentProject,shouldNavigateAfterThreadPark,@@ -339,6 +340,7 @@ interface SidebarThreadPartitionInput {/** Tasks linked environments run for a listed thread; they show under it. */readonly delegatedUnderParent: ReadonlySet<string>;readonly serverConfigs: ReadonlyMap<EnvironmentId, EnvironmentServerConfig>;+ readonly connectedEnvironmentIds: readonly EnvironmentId[];readonly optimisticDrop: SidebarOptimisticDrop | null;readonly workingShelfEnabled: boolean;/** Boring mode: folders list active threads by the user's latest message. */@@ -399,6 +401,7 @@ function useSidebarThreads(input: {readonly projectScopeKey: string | null;readonly scopedProjectKeys: ReadonlySet<string> | null;readonly serverConfigs: ReadonlyMap<EnvironmentId, EnvironmentServerConfig>;+ readonly connectedEnvironmentIds: readonly EnvironmentId[];readonly optimisticDrop: SidebarOptimisticDrop | null;readonly threads: readonly EnvironmentThreadShell[];readonly delegatedUnderParent: ReadonlySet<string>;@@ -412,6 +415,7 @@ function useSidebarThreads(input: {projectScopeKey,scopedProjectKeys,serverConfigs,+ connectedEnvironmentIds,optimisticDrop,threads,delegatedUnderParent,@@ -462,6 +466,7 @@ function useSidebarThreads(input: {scopedProjectKeys,delegatedUnderParent,serverConfigs,+ connectedEnvironmentIds,optimisticDrop,workingShelfEnabled,sortActiveBySend: folderGroups !== null,@@ -614,15 +619,14 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {: active;const snoozed: EnvironmentThreadShell[] = [];const settled: EnvironmentThreadShell[] = [];- const draggable = new Set<string>();- const activeReorderable = new Set<string>();+ const { draggableThreadKeys, activeReorderableThreadKeys } = resolveSidebarReorderableThreadKeys({+ threads: visible,+ serverConfigs,+ connectedEnvironmentIds: input.connectedEnvironmentIds,+ });for (const thread of visible) {const configLoaded = serverConfigs.has(thread.environmentId);const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));- if (configLoaded) {- activeReorderable.add(threadKey);- draggable.add(threadKey);- }if (optimisticDrop?.key === threadKey) {const projected = applySidebarThreadDrop(thread,@@ -656,7 +660,7 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {).push(thread);}}- // A loaded config gates dragging only; the sort must not depend on it, so web and mobile agree.+ // Availability gates dragging only; sorting must stay consistent across clients.const sortedPinned = sortPinnedThreadsForSidebar(pinned);const sortedActive = sortActiveBySend? sortWorkingThreadsBySend(active)@@ -672,8 +676,8 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {preferredIds: optimisticDrop.order,getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),}),- draggableThreadKeys: draggable,- activeReorderableThreadKeys: activeReorderable,+ draggableThreadKeys,+ activeReorderableThreadKeys,activeThreads:optimisticDrop?.section !== "active" || optimisticDrop.order === null? sortedActive@@ -1001,7 +1005,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveconst threadSearchInputRef = useRef<HTMLInputElement>(null);const [threadSearchQuery, setThreadSearchQuery] = useState("");const [searchHighlightKey, setSearchHighlightKey] = useState<string | null>(null);- const searchEnvironmentIds = useConnectedEnvironmentIds();+ const connectedEnvironmentIds = useConnectedEnvironmentIds();const queuePendingFileDrop = useSidebarPendingFileDropStore((s) => s.queuePendingFileDrop);const clearPendingFileDrop = useSidebarPendingFileDropStore((s) => s.clearPendingFileDrop);const [renamingThreadRef, setRenamingThreadRef] = useState<ScopedThreadRef | null>(null);@@ -1145,7 +1149,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveconst scopedProjectRefs = scopedProjectGroups.flatMap((project) => project.memberProjectRefs);const scopedProjectKeys = revealWidensScope ? null : chosenScopeProjectKeys;const threadSearch = useThreadSearch(- searchEnvironmentIds,+ connectedEnvironmentIds,threadSearchQuery,scopedProjectGroups.length === 0? {}@@ -1277,6 +1281,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveprojectScopeKey,scopedProjectKeys,serverConfigs,+ connectedEnvironmentIds,optimisticDrop,threads,delegatedUnderParent,