Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useThreadVisitedMigration.ts

34 lines1.6 KB

1import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
2import { useEffect } from "react";
3​
4import { useThreadShells } from "../state/entities";
5import { threadEnvironment } from "../state/threads";
6import { useAtomCommand } from "../state/use-atom-command";
7import { useUiStateStore } from "../uiStateStore";
8​
9const migratedThreadKeys = new Set<string>();
10​
11export function useThreadVisitedMigration(): void {
12 const threads = useThreadShells();
13 const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
14 useEffect(() => {
15 for (const thread of threads) {
16 // Field absent → the environment's server has no visited tracking; keep
17 // the local value in play and reconsider if the server upgrades.
18 if (thread.lastVisitedAt === undefined) continue;
19 const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
20 if (migratedThreadKeys.has(threadKey)) continue;
21 migratedThreadKeys.add(threadKey);
22 const local = useUiStateStore.getState().threadLastVisitedAtById[threadKey];
23 if (!local) continue;
24 const localMs = Date.parse(local);
25 if (!Number.isFinite(localMs)) continue;
26 const serverMs = thread.lastVisitedAt === null ? null : Date.parse(thread.lastVisitedAt);
27 if (serverMs !== null && Number.isFinite(serverMs) && serverMs >= localMs) continue;
28 void visitThreadMutation({
29 environmentId: thread.environmentId,
30 input: { threadId: thread.id, visitedAt: local },
31 });
32 }
33 }, [threads, visitThreadMutation]);