Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions apps/mobile/src/features/home/HomeScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,7 @@ export function HomeScreen(props: HomeScreenProps) {
settledShelfExpanded,
snoozedShelfExpanded,
workingShelfEnabled,
sortByLastMessage,
workingShelfExpanded,
toggleSettledShelf,
toggleSnoozedShelf,
Expand Down Expand Up @@ -494,7 +495,7 @@ export function HomeScreen(props: HomeScreenProps) {
});
return new Map([
...sectionAvailability("pinned"),
...(workingShelfEnabled ? [] : sectionAvailability("active")),
...(workingShelfEnabled || sortByLastMessage ? [] : sectionAvailability("active")),
]);
})();
const threadListV2Layout = (() => {
Expand All @@ -512,6 +513,7 @@ export function HomeScreen(props: HomeScreenProps) {
settledLimit: settledVisibleCount,
now,
workingShelfEnabled,
sortByLastMessage,
workingShelfExpanded,
inboxReturnAt: threadListInboxReturns.returnedAt,
snoozedShelfExpanded,
Expand Down Expand Up @@ -674,7 +676,9 @@ export function HomeScreen(props: HomeScreenProps) {
reorderSupported={
item.item.pinned
? pinReorderEnvironmentIds.has(thread.environmentId)
: !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
: !workingShelfEnabled &&
!sortByLastMessage &&
activeReorderEnvironmentIds.has(thread.environmentId)
}
canMoveUp={item.canMoveUp}
canMoveDown={item.canMoveDown}
Expand Down Expand Up @@ -707,6 +711,7 @@ export function HomeScreen(props: HomeScreenProps) {
selectedThreadKey,
threadSearchMatchByKey,
workingShelfEnabled,
sortByLastMessage,
};

const hasAnyThreads =
Expand Down
23 changes: 23 additions & 0 deletions apps/mobile/src/features/home/useThreadListActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import type { ThreadMoveDestination } from "../threads/threadOrder";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
import { mobilePreferencesAtom } from "../../state/preferences";
import * as Cause from "effect/Cause";
import * as Haptics from "expo-haptics";
import { useRef } from "react";
Expand Down Expand Up @@ -536,6 +538,27 @@ export function useThreadListActions(): {
appAtomRegistry.set(threadDropBusyAtom, false);
return settled;
}
const preferences = appAtomRegistry.get(mobilePreferencesAtom);
if (
section === "active" &&
AsyncResult.isSuccess(preferences) &&
preferences.value.threadListSortByLastMessage === true
) {
const lifecycle = threadDropLifecycle(thread, section, new Date().toISOString());
if (!lifecycle.unpin && !lifecycle.unsettle && !lifecycle.unsnooze) return false;
if (lifecycle.unpin && !environmentSupportsPinning(thread.environmentId)) return false;
if (lifecycle.unsettle && !environmentSupportsSettlement(thread.environmentId)) return false;
if (lifecycle.unsnooze && !environmentSupportsSnooze(thread.environmentId)) return false;
appAtomRegistry.set(threadDropBusyAtom, true);
try {
if (lifecycle.unpin && !(await unpinThread(thread))) return false;
if (lifecycle.unsettle && !(await unsettleThread(thread))) return false;
if (lifecycle.unsnooze && !(await unsnoozeThread(thread))) return false;
return true;
} finally {
appAtomRegistry.set(threadDropBusyAtom, false);
}
}
const configs = appAtomRegistry.get(environmentServerConfigsAtom);
const supportsReorder = (environmentId: EnvironmentThreadShell["environmentId"]) => {
const capabilities = configs.get(environmentId)?.environment.capabilities;
Expand Down
26 changes: 26 additions & 0 deletions apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export function SettingsThreadsRouteScreen() {
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
>
<AutoSettleSettingsRows />
<ThreadSortSettingsSection />
<BetaSettingsSection />
<LegacySettingsSection />
</ScrollView>
Expand Down Expand Up @@ -290,3 +291,28 @@ function LegacySettingsSection() {
</View>
);
}

function ThreadSortSettingsSection() {
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const preferences = useAtomValue(mobilePreferencesAtom);
const loaded = AsyncResult.isSuccess(preferences);
const sortByLastMessage = loaded && preferences.value.threadListSortByLastMessage === true;
const workingShelfEnabled = loaded && preferences.value.workingShelfEnabled === true;
return (
<View className="gap-3">
<SettingsSection title="Thread order">
<SettingsSwitchRow
icon="line.3.horizontal"
label="Sort active threads by last message"
value={sortByLastMessage}
disabled={!loaded || workingShelfEnabled}
onValueChange={(value) => savePreferences({ threadListSortByLastMessage: value })}
/>
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
Show your most recent conversations first. Turn off to restore your saved arrangement. The
Working section uses return time while enabled. This choice applies to this device.
</Text>
</View>
);
}
19 changes: 15 additions & 4 deletions apps/mobile/src/features/threads/ThreadArrangementSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,8 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) {
const pendingOrder = useAtomValue(pendingThreadOrderAtom);
const dropBusy = useAtomValue(threadDropBusyAtom);
const { moveThread } = useThreadListActions();
const { workingShelfEnabled } = useThreadListV2ShelfPreferences();
const { workingShelfEnabled, sortByLastMessage, activeTimeOrdered } =
useThreadListV2ShelfPreferences();
const [now, setNow] = useState(() => new Date().toISOString());
const [expanded, setExpanded] = useState({ snoozed: false, settled: false });
useEffect(() => {
Expand All @@ -179,6 +180,7 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) {
now,
queuedThreadKeys,
pendingOrder,
sortByLastMessage,
settlementEnvironmentIds: new Set(
[...configs].flatMap(([id, config]) =>
config.environment.capabilities.threadSettlement ? [id] : [],
Expand All @@ -204,27 +206,36 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) {
snoozed: parked.filter((thread) => effectiveSnoozed(thread, { now })),
settled: parked.filter((thread) => !effectiveSnoozed(thread, { now })),
};
}, [threads, configs, now, queuedThreadKeys, pendingOrder, workingShelfEnabled]);
}, [
threads,
configs,
now,
queuedThreadKeys,
pendingOrder,
workingShelfEnabled,
sortByLastMessage,
]);
const planners = useMemo(() => {
const planner = (section: "pinned" | "active") =>
createThreadMovePlanner({
ordered: sections[section],
allThreads: threads,
section,
timeOrdered: section === "active" && sortByLastMessage,
reorderableEnvironmentIds: new Set(
[...configs].flatMap(([id, config]) =>
(
section === "pinned"
? config.environment.capabilities.threadPinReorder
: !workingShelfEnabled && config.environment.capabilities.threadActiveReorder
: !activeTimeOrdered && config.environment.capabilities.threadActiveReorder
)
? [id]
: [],
),
),
});
return { pinned: planner("pinned"), active: planner("active") };
}, [sections, threads, configs, workingShelfEnabled]);
}, [sections, threads, configs, activeTimeOrdered, sortByLastMessage]);
const rows = useMemo(() => {
const result: Row[] = [];
let offset = 0;
Expand Down
9 changes: 7 additions & 2 deletions apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ function ThreadNavigationSidebarPane(
settledShelfExpanded,
snoozedShelfExpanded,
workingShelfEnabled,
sortByLastMessage,
workingShelfExpanded,
toggleSettledShelf,
toggleSnoozedShelf,
Expand Down Expand Up @@ -318,7 +319,7 @@ function ThreadNavigationSidebarPane(
});
return new Map([
...sectionAvailability("pinned"),
...(workingShelfEnabled ? [] : sectionAvailability("active")),
...(workingShelfEnabled || sortByLastMessage ? [] : sectionAvailability("active")),
]);
})();
const threadListV2Layout = (() => {
Expand All @@ -336,6 +337,7 @@ function ThreadNavigationSidebarPane(
settledLimit: settledVisibleCount,
now,
workingShelfEnabled,
sortByLastMessage,
workingShelfExpanded,
inboxReturnAt: threadListInboxReturns.returnedAt,
snoozedShelfExpanded,
Expand Down Expand Up @@ -532,6 +534,7 @@ function ThreadNavigationSidebarPane(
listEnvironments,
threadSearchMatchByKey,
workingShelfEnabled,
sortByLastMessage,
};
useThreadJumpShortcuts(listItems, handleSelectThread);
const sidebarItemsAreEqual = (previous: SidebarListItem, item: SidebarListItem): boolean => {
Expand Down Expand Up @@ -635,7 +638,9 @@ function ThreadNavigationSidebarPane(
reorderSupported={
item.item.pinned
? pinReorderEnvironmentIds.has(thread.environmentId)
: !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
: !workingShelfEnabled &&
!sortByLastMessage &&
activeReorderEnvironmentIds.has(thread.environmentId)
}
canMoveUp={item.canMoveUp}
canMoveDown={item.canMoveDown}
Expand Down
76 changes: 76 additions & 0 deletions apps/mobile/src/features/threads/threadListV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2406,3 +2406,79 @@ describe("Working section beta", () => {
]);
});
});

describe("last-message active thread order", () => {
const rows = [
makeThread({
id: ThreadId.make("ten-hours"),
title: "Older message",
activeOrderKey: "f",
latestUserMessageAt: "2026-06-01T14:00:00Z",
}),
makeThread({
id: ThreadId.make("two-minutes"),
title: "Recent message",
activeOrderKey: "t",
latestUserMessageAt: "2026-06-01T23:58:00Z",
}),
];
it("sorts the phone/tablet list by messages and restores saved positions", () => {
const input = { threads: rows, now: NOW, environmentId: null, searchQuery: "" };
expect(
buildThreadListV2Items({ ...input, sortByLastMessage: true }).items.map(
(row) => row.thread.id,
),
).toEqual(["two-minutes", "ten-hours"]);
expect(buildThreadListV2Items(input).items.map((row) => row.thread.id)).toEqual([
"ten-hours",
"two-minutes",
]);
expect(
getThreadListV2OrderedSection({
threads: rows,
now: NOW,
section: "active",
sortByLastMessage: true,
}).map((row) => row.id),
).toEqual(["two-minutes", "ten-hours"]);
});

it("lets the Working section retain return-time order over the saved sort choice", () => {
const layout = buildThreadListV2Items({
threads: rows,
now: NOW,
environmentId: null,
searchQuery: "",
sortByLastMessage: true,
workingShelfEnabled: true,
inboxReturnAt: (thread) => (thread.id === rows[0]!.id ? Date.parse(NOW) : 0),
});
expect(layout.items.map((row) => row.thread.id)).toEqual(["ten-hours", "two-minutes"]);
});

it("allows lifecycle drops into message-sorted Active without rewriting saved keys", () => {
const parked = makeThread({ id: ThreadId.make("pinned"), title: "Pinned", pinnedAt: NOW });
const planner = createThreadMovePlanner({
ordered: rows,
allThreads: [...rows, parked],
section: "active",
timeOrdered: true,
reorderableEnvironmentIds: new Set(),
});
expect(
planner(`${environmentId}:${parked.id}`, {
section: "active",
targetId: null,
placement: "before",
}),
).toEqual([]);
expect(planner(`${environmentId}:${rows[0]!.id}`, "down")).toBeNull();
expect(
planner(`${environmentId}:${rows[0]!.id}`, {
section: "active",
targetId: `${environmentId}:${rows[1]!.id}`,
placement: "after",
}),
).toBeNull();
});
});
20 changes: 14 additions & 6 deletions apps/mobile/src/features/threads/threadListV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
sortWorkingThreadsBySend,
} from "@t3tools/client-runtime/state/thread-inbox";
import {
sortActiveThreadsByOrderKey,
sortActiveThreads,
resolveSettledThreadTimestamp,
sortPinnedThreadsByOrderKey,
sortSettledThreads,
Expand Down Expand Up @@ -187,18 +187,21 @@ export function sortThreadsForListV2<
T extends {
readonly id: string;
readonly createdAt: string;
readonly updatedAt?: string;
readonly latestUserMessageAt?: string | null;
readonly unsettledAt?: string | null | undefined;
readonly activeOrderKey?: string | null | undefined;
readonly environmentId?: string | undefined;
},
>(threads: readonly T[]): T[] {
return sortActiveThreadsByOrderKey(threads);
>(threads: readonly T[], sortByLastMessage = false): T[] {
return sortActiveThreads(threads, sortByLastMessage);
}

export function getThreadListV2OrderedSection(input: {
readonly threads: readonly EnvironmentThreadShell[];
readonly section: "pinned" | "active";
readonly pendingOrder?: PendingThreadOrder | null;
readonly sortByLastMessage?: boolean;
readonly now: string;
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
Expand Down Expand Up @@ -226,12 +229,14 @@ export function getThreadListV2OrderedSection(input: {
const ordered =
input.section === "pinned"
? sortPinnedThreadsByOrderKey(threads)
: sortActiveThreadsByOrderKey(threads);
: sortActiveThreads(threads, input.sortByLastMessage);
const pending =
input.pendingOrder?.section === input.section
? reconcilePendingThreadOrder(input.pendingOrder, ordered)
: null;
return applyPendingThreadOrder(ordered, input.section, pending);
return input.section === "active" && input.sortByLastMessage
? ordered
: applyPendingThreadOrder(ordered, input.section, pending);
}

export interface ThreadListV2Item {
Expand Down Expand Up @@ -544,6 +549,7 @@ function sortSettledThreadsReusingLast(

export function buildThreadListV2Items(input: {
readonly pendingOrder?: PendingThreadOrder | null;
readonly sortByLastMessage?: boolean;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly environmentId: EnvironmentId | null;
readonly projectRefs?: ReadonlyArray<{
Expand Down Expand Up @@ -638,7 +644,9 @@ export function buildThreadListV2Items(input: {

const orderedActive = workingShelfEnabled
? sortInboxThreadsByReturn(active, input.inboxReturnAt)
: applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending);
: input.sortByLastMessage
? sortActiveThreads(active, true)
: applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending);
const orderedWorking = sortWorkingThreadsBySend(working);
const orderedSnoozed = [...snoozed].sort(
(left, right) =>
Expand Down
9 changes: 9 additions & 0 deletions apps/mobile/src/features/threads/threadOrder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ export function createThreadMovePlanner(input: {
readonly ordered: readonly OrderRow[];
readonly allThreads?: readonly OrderRow[];
readonly section: PendingThreadOrder["section"];
readonly timeOrdered?: boolean;
readonly reorderableEnvironmentIds: ReadonlySet<EnvironmentId>;
}) {
const orderedIds = input.ordered.map(rowId);
Expand All @@ -95,6 +96,14 @@ export function createThreadMovePlanner(input: {
.map(rowId),
);
return (movedId: string, direction: ThreadMoveDestination) => {
if (input.timeOrdered) {
return keysById.has(movedId) &&
typeof direction === "object" &&
direction.section === input.section &&
!orderedIds.includes(movedId)
? []
: null;
}
if (!writableIds.has(movedId)) return null;
const nextIds = threadOrderAfterMove(orderedIds, movedId, direction);
if (nextIds === null) return null;
Expand Down
Loading
Loading