Open History to see the last commit
1import { RegistryContext } from "@effect/atom-react";
2import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
3import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4import { useContext, useEffect, useEffectEvent } from "react";
5
6import { environmentThreadShells, threadEnvironment } from "../state/threads";
7import { useAtomCommand } from "../state/use-atom-command";
8import { useUiStateStore } from "../uiStateStore";
9
10const migratedThreadKeys = new Set<string>();
11
12// Subscribes outside render: the migration only acts on threads it has not
13// seen, so a shell update must not re-render the layout that mounts it.
14export function useThreadVisitedMigration(): void {
15 const registry = useContext(RegistryContext);
16 const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
17 const migrate = useEffectEvent((threads: ReadonlyArray<EnvironmentThreadShell>) => {
18 for (const thread of threads) {
19 // Field absent → the environment's server has no visited tracking; keep
20 // the local value in play and reconsider if the server upgrades.
21 if (thread.lastVisitedAt === undefined) continue;
22 const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
23 if (migratedThreadKeys.has(threadKey)) continue;
24 migratedThreadKeys.add(threadKey);
25 const local = useUiStateStore.getState().threadLastVisitedAtById[threadKey];
26 if (!local) continue;
27 const localMs = Date.parse(local);
28 if (!Number.isFinite(localMs)) continue;
29 const serverMs = thread.lastVisitedAt === null ? null : Date.parse(thread.lastVisitedAt);
30 if (serverMs !== null && Number.isFinite(serverMs) && serverMs >= localMs) continue;
31 void visitThreadMutation({
32 environmentId: thread.environmentId,
33 input: { threadId: thread.id, visitedAt: local },
34 });
35 }
36 });
37 useEffect(
38 () =>
39 registry.subscribe(environmentThreadShells.threadShellsAtom, migrate, { immediate: true }),
40 [registry],
41 );
42}