Skip to content

Commit 3059976

Browse files
committed
feat(clients): add last-message sorting for active threads
1 parent 9d4038f commit 3059976

19 files changed

Lines changed: 386 additions & 23 deletions

‎apps/mobile/src/features/home/HomeScreen.tsx‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,7 @@ export function HomeScreen(props: HomeScreenProps) {
441441
settledShelfExpanded,
442442
snoozedShelfExpanded,
443443
workingShelfEnabled,
444+
sortByLastMessage,
444445
workingShelfExpanded,
445446
toggleSettledShelf,
446447
toggleSnoozedShelf,
@@ -494,7 +495,7 @@ export function HomeScreen(props: HomeScreenProps) {
494495
});
495496
return new Map([
496497
...sectionAvailability("pinned"),
497-
...(workingShelfEnabled ? [] : sectionAvailability("active")),
498+
...(workingShelfEnabled || sortByLastMessage ? [] : sectionAvailability("active")),
498499
]);
499500
})();
500501
const threadListV2Layout = (() => {
@@ -512,6 +513,7 @@ export function HomeScreen(props: HomeScreenProps) {
512513
settledLimit: settledVisibleCount,
513514
now,
514515
workingShelfEnabled,
516+
sortByLastMessage,
515517
workingShelfExpanded,
516518
inboxReturnAt: threadListInboxReturns.returnedAt,
517519
snoozedShelfExpanded,
@@ -674,7 +676,9 @@ export function HomeScreen(props: HomeScreenProps) {
674676
reorderSupported={
675677
item.item.pinned
676678
? pinReorderEnvironmentIds.has(thread.environmentId)
677-
: !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
679+
: !workingShelfEnabled &&
680+
!sortByLastMessage &&
681+
activeReorderEnvironmentIds.has(thread.environmentId)
678682
}
679683
canMoveUp={item.canMoveUp}
680684
canMoveDown={item.canMoveDown}
@@ -707,6 +711,7 @@ export function HomeScreen(props: HomeScreenProps) {
707711
selectedThreadKey,
708712
threadSearchMatchByKey,
709713
workingShelfEnabled,
714+
sortByLastMessage,
710715
};
711716

712717
const hasAnyThreads =

‎apps/mobile/src/features/home/useThreadListActions.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import type { ThreadMoveDestination } from "../threads/threadOrder";
22
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
33
import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
44
import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
5+
import { AsyncResult } from "effect/reactivity";
6+
import { mobilePreferencesAtom } from "../../state/preferences";
57
import * as Cause from "effect/Cause";
68
import * as Haptics from "expo-haptics";
79
import { useRef } from "react";
@@ -536,6 +538,27 @@ export function useThreadListActions(): {
536538
appAtomRegistry.set(threadDropBusyAtom, false);
537539
return settled;
538540
}
541+
const preferences = appAtomRegistry.get(mobilePreferencesAtom);
542+
if (
543+
section === "active" &&
544+
AsyncResult.isSuccess(preferences) &&
545+
preferences.value.threadListSortByLastMessage === true
546+
) {
547+
const lifecycle = threadDropLifecycle(thread, section, new Date().toISOString());
548+
if (!lifecycle.unpin && !lifecycle.unsettle && !lifecycle.unsnooze) return false;
549+
if (lifecycle.unpin && !environmentSupportsPinning(thread.environmentId)) return false;
550+
if (lifecycle.unsettle && !environmentSupportsSettlement(thread.environmentId)) return false;
551+
if (lifecycle.unsnooze && !environmentSupportsSnooze(thread.environmentId)) return false;
552+
appAtomRegistry.set(threadDropBusyAtom, true);
553+
try {
554+
if (lifecycle.unpin && !(await unpinThread(thread))) return false;
555+
if (lifecycle.unsettle && !(await unsettleThread(thread))) return false;
556+
if (lifecycle.unsnooze && !(await unsnoozeThread(thread))) return false;
557+
return true;
558+
} finally {
559+
appAtomRegistry.set(threadDropBusyAtom, false);
560+
}
561+
}
539562
const configs = appAtomRegistry.get(environmentServerConfigsAtom);
540563
const supportsReorder = (environmentId: EnvironmentThreadShell["environmentId"]) => {
541564
const capabilities = configs.get(environmentId)?.environment.capabilities;

‎apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ export function SettingsThreadsRouteScreen() {
4747
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
4848
>
4949
<AutoSettleSettingsRows />
50+
<ThreadSortSettingsSection />
5051
<BetaSettingsSection />
5152
<LegacySettingsSection />
5253
</ScrollView>
@@ -290,3 +291,28 @@ function LegacySettingsSection() {
290291
</View>
291292
);
292293
}
294+
295+
function ThreadSortSettingsSection() {
296+
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
297+
const preferences = useAtomValue(mobilePreferencesAtom);
298+
const loaded = AsyncResult.isSuccess(preferences);
299+
const sortByLastMessage = loaded && preferences.value.threadListSortByLastMessage === true;
300+
const workingShelfEnabled = loaded && preferences.value.workingShelfEnabled === true;
301+
return (
302+
<View className="gap-3">
303+
<SettingsSection title="Thread order">
304+
<SettingsSwitchRow
305+
icon="line.3.horizontal"
306+
label="Sort active threads by last message"
307+
value={sortByLastMessage}
308+
disabled={!loaded || workingShelfEnabled}
309+
onValueChange={(value) => savePreferences({ threadListSortByLastMessage: value })}
310+
/>
311+
</SettingsSection>
312+
<Text className="px-2 text-sm text-foreground-muted">
313+
Show your most recent conversations first. Turn off to restore your saved arrangement. The
314+
Working section uses return time while enabled. This choice applies to this device.
315+
</Text>
316+
</View>
317+
);
318+
}

‎apps/mobile/src/features/threads/ThreadArrangementSheet.tsx‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,8 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) {
156156
const pendingOrder = useAtomValue(pendingThreadOrderAtom);
157157
const dropBusy = useAtomValue(threadDropBusyAtom);
158158
const { moveThread } = useThreadListActions();
159-
const { workingShelfEnabled } = useThreadListV2ShelfPreferences();
159+
const { workingShelfEnabled, sortByLastMessage, activeTimeOrdered } =
160+
useThreadListV2ShelfPreferences();
160161
const [now, setNow] = useState(() => new Date().toISOString());
161162
const [expanded, setExpanded] = useState({ snoozed: false, settled: false });
162163
useEffect(() => {
@@ -179,6 +180,7 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) {
179180
now,
180181
queuedThreadKeys,
181182
pendingOrder,
183+
sortByLastMessage,
182184
settlementEnvironmentIds: new Set(
183185
[...configs].flatMap(([id, config]) =>
184186
config.environment.capabilities.threadSettlement ? [id] : [],
@@ -204,27 +206,36 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) {
204206
snoozed: parked.filter((thread) => effectiveSnoozed(thread, { now })),
205207
settled: parked.filter((thread) => !effectiveSnoozed(thread, { now })),
206208
};
207-
}, [threads, configs, now, queuedThreadKeys, pendingOrder, workingShelfEnabled]);
209+
}, [
210+
threads,
211+
configs,
212+
now,
213+
queuedThreadKeys,
214+
pendingOrder,
215+
workingShelfEnabled,
216+
sortByLastMessage,
217+
]);
208218
const planners = useMemo(() => {
209219
const planner = (section: "pinned" | "active") =>
210220
createThreadMovePlanner({
211221
ordered: sections[section],
212222
allThreads: threads,
213223
section,
224+
timeOrdered: section === "active" && sortByLastMessage,
214225
reorderableEnvironmentIds: new Set(
215226
[...configs].flatMap(([id, config]) =>
216227
(
217228
section === "pinned"
218229
? config.environment.capabilities.threadPinReorder
219-
: !workingShelfEnabled && config.environment.capabilities.threadActiveReorder
230+
: !activeTimeOrdered && config.environment.capabilities.threadActiveReorder
220231
)
221232
? [id]
222233
: [],
223234
),
224235
),
225236
});
226237
return { pinned: planner("pinned"), active: planner("active") };
227-
}, [sections, threads, configs, workingShelfEnabled]);
238+
}, [sections, threads, configs, activeTimeOrdered, sortByLastMessage]);
228239
const rows = useMemo(() => {
229240
const result: Row[] = [];
230241
let offset = 0;

‎apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,7 @@ function ThreadNavigationSidebarPane(
265265
settledShelfExpanded,
266266
snoozedShelfExpanded,
267267
workingShelfEnabled,
268+
sortByLastMessage,
268269
workingShelfExpanded,
269270
toggleSettledShelf,
270271
toggleSnoozedShelf,
@@ -318,7 +319,7 @@ function ThreadNavigationSidebarPane(
318319
});
319320
return new Map([
320321
...sectionAvailability("pinned"),
321-
...(workingShelfEnabled ? [] : sectionAvailability("active")),
322+
...(workingShelfEnabled || sortByLastMessage ? [] : sectionAvailability("active")),
322323
]);
323324
})();
324325
const threadListV2Layout = (() => {
@@ -336,6 +337,7 @@ function ThreadNavigationSidebarPane(
336337
settledLimit: settledVisibleCount,
337338
now,
338339
workingShelfEnabled,
340+
sortByLastMessage,
339341
workingShelfExpanded,
340342
inboxReturnAt: threadListInboxReturns.returnedAt,
341343
snoozedShelfExpanded,
@@ -532,6 +534,7 @@ function ThreadNavigationSidebarPane(
532534
listEnvironments,
533535
threadSearchMatchByKey,
534536
workingShelfEnabled,
537+
sortByLastMessage,
535538
};
536539
useThreadJumpShortcuts(listItems, handleSelectThread);
537540
const sidebarItemsAreEqual = (previous: SidebarListItem, item: SidebarListItem): boolean => {
@@ -635,7 +638,9 @@ function ThreadNavigationSidebarPane(
635638
reorderSupported={
636639
item.item.pinned
637640
? pinReorderEnvironmentIds.has(thread.environmentId)
638-
: !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
641+
: !workingShelfEnabled &&
642+
!sortByLastMessage &&
643+
activeReorderEnvironmentIds.has(thread.environmentId)
639644
}
640645
canMoveUp={item.canMoveUp}
641646
canMoveDown={item.canMoveDown}

‎apps/mobile/src/features/threads/threadListV2.test.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2406,3 +2406,79 @@ describe("Working section beta", () => {
24062406
]);
24072407
});
24082408
});
2409+
2410+
describe("last-message active thread order", () => {
2411+
const rows = [
2412+
makeThread({
2413+
id: ThreadId.make("ten-hours"),
2414+
title: "Older message",
2415+
activeOrderKey: "f",
2416+
latestUserMessageAt: "2026-06-01T14:00:00Z",
2417+
}),
2418+
makeThread({
2419+
id: ThreadId.make("two-minutes"),
2420+
title: "Recent message",
2421+
activeOrderKey: "t",
2422+
latestUserMessageAt: "2026-06-01T23:58:00Z",
2423+
}),
2424+
];
2425+
it("sorts the phone/tablet list by messages and restores saved positions", () => {
2426+
const input = { threads: rows, now: NOW, environmentId: null, searchQuery: "" };
2427+
expect(
2428+
buildThreadListV2Items({ ...input, sortByLastMessage: true }).items.map(
2429+
(row) => row.thread.id,
2430+
),
2431+
).toEqual(["two-minutes", "ten-hours"]);
2432+
expect(buildThreadListV2Items(input).items.map((row) => row.thread.id)).toEqual([
2433+
"ten-hours",
2434+
"two-minutes",
2435+
]);
2436+
expect(
2437+
getThreadListV2OrderedSection({
2438+
threads: rows,
2439+
now: NOW,
2440+
section: "active",
2441+
sortByLastMessage: true,
2442+
}).map((row) => row.id),
2443+
).toEqual(["two-minutes", "ten-hours"]);
2444+
});
2445+
2446+
it("lets the Working section retain return-time order over the saved sort choice", () => {
2447+
const layout = buildThreadListV2Items({
2448+
threads: rows,
2449+
now: NOW,
2450+
environmentId: null,
2451+
searchQuery: "",
2452+
sortByLastMessage: true,
2453+
workingShelfEnabled: true,
2454+
inboxReturnAt: (thread) => (thread.id === rows[0]!.id ? Date.parse(NOW) : 0),
2455+
});
2456+
expect(layout.items.map((row) => row.thread.id)).toEqual(["ten-hours", "two-minutes"]);
2457+
});
2458+
2459+
it("allows lifecycle drops into message-sorted Active without rewriting saved keys", () => {
2460+
const parked = makeThread({ id: ThreadId.make("pinned"), title: "Pinned", pinnedAt: NOW });
2461+
const planner = createThreadMovePlanner({
2462+
ordered: rows,
2463+
allThreads: [...rows, parked],
2464+
section: "active",
2465+
timeOrdered: true,
2466+
reorderableEnvironmentIds: new Set(),
2467+
});
2468+
expect(
2469+
planner(`${environmentId}:${parked.id}`, {
2470+
section: "active",
2471+
targetId: null,
2472+
placement: "before",
2473+
}),
2474+
).toEqual([]);
2475+
expect(planner(`${environmentId}:${rows[0]!.id}`, "down")).toBeNull();
2476+
expect(
2477+
planner(`${environmentId}:${rows[0]!.id}`, {
2478+
section: "active",
2479+
targetId: `${environmentId}:${rows[1]!.id}`,
2480+
placement: "after",
2481+
}),
2482+
).toBeNull();
2483+
});
2484+
});

‎apps/mobile/src/features/threads/threadListV2.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import {
1818
sortWorkingThreadsBySend,
1919
} from "@t3tools/client-runtime/state/thread-inbox";
2020
import {
21-
sortActiveThreadsByOrderKey,
21+
sortActiveThreads,
2222
resolveSettledThreadTimestamp,
2323
sortPinnedThreadsByOrderKey,
2424
sortSettledThreads,
@@ -187,18 +187,21 @@ export function sortThreadsForListV2<
187187
T extends {
188188
readonly id: string;
189189
readonly createdAt: string;
190+
readonly updatedAt?: string;
191+
readonly latestUserMessageAt?: string | null;
190192
readonly unsettledAt?: string | null | undefined;
191193
readonly activeOrderKey?: string | null | undefined;
192194
readonly environmentId?: string | undefined;
193195
},
194-
>(threads: readonly T[]): T[] {
195-
return sortActiveThreadsByOrderKey(threads);
196+
>(threads: readonly T[], sortByLastMessage = false): T[] {
197+
return sortActiveThreads(threads, sortByLastMessage);
196198
}
197199

198200
export function getThreadListV2OrderedSection(input: {
199201
readonly threads: readonly EnvironmentThreadShell[];
200202
readonly section: "pinned" | "active";
201203
readonly pendingOrder?: PendingThreadOrder | null;
204+
readonly sortByLastMessage?: boolean;
202205
readonly now: string;
203206
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
204207
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
@@ -226,12 +229,14 @@ export function getThreadListV2OrderedSection(input: {
226229
const ordered =
227230
input.section === "pinned"
228231
? sortPinnedThreadsByOrderKey(threads)
229-
: sortActiveThreadsByOrderKey(threads);
232+
: sortActiveThreads(threads, input.sortByLastMessage);
230233
const pending =
231234
input.pendingOrder?.section === input.section
232235
? reconcilePendingThreadOrder(input.pendingOrder, ordered)
233236
: null;
234-
return applyPendingThreadOrder(ordered, input.section, pending);
237+
return input.section === "active" && input.sortByLastMessage
238+
? ordered
239+
: applyPendingThreadOrder(ordered, input.section, pending);
235240
}
236241

237242
export interface ThreadListV2Item {
@@ -544,6 +549,7 @@ function sortSettledThreadsReusingLast(
544549

545550
export function buildThreadListV2Items(input: {
546551
readonly pendingOrder?: PendingThreadOrder | null;
552+
readonly sortByLastMessage?: boolean;
547553
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
548554
readonly environmentId: EnvironmentId | null;
549555
readonly projectRefs?: ReadonlyArray<{
@@ -638,7 +644,9 @@ export function buildThreadListV2Items(input: {
638644

639645
const orderedActive = workingShelfEnabled
640646
? sortInboxThreadsByReturn(active, input.inboxReturnAt)
641-
: applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending);
647+
: input.sortByLastMessage
648+
? sortActiveThreads(active, true)
649+
: applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending);
642650
const orderedWorking = sortWorkingThreadsBySend(working);
643651
const orderedSnoozed = [...snoozed].sort(
644652
(left, right) =>

‎apps/mobile/src/features/threads/threadOrder.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ export function createThreadMovePlanner(input: {
8080
readonly ordered: readonly OrderRow[];
8181
readonly allThreads?: readonly OrderRow[];
8282
readonly section: PendingThreadOrder["section"];
83+
readonly timeOrdered?: boolean;
8384
readonly reorderableEnvironmentIds: ReadonlySet<EnvironmentId>;
8485
}) {
8586
const orderedIds = input.ordered.map(rowId);
@@ -95,6 +96,14 @@ export function createThreadMovePlanner(input: {
9596
.map(rowId),
9697
);
9798
return (movedId: string, direction: ThreadMoveDestination) => {
99+
if (input.timeOrdered) {
100+
return keysById.has(movedId) &&
101+
typeof direction === "object" &&
102+
direction.section === input.section &&
103+
!orderedIds.includes(movedId)
104+
? []
105+
: null;
106+
}
98107
if (!writableIds.has(movedId)) return null;
99108
const nextIds = threadOrderAfterMove(orderedIds, movedId, direction);
100109
if (nextIds === null) return null;

0 commit comments

Comments
 (0)