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

use-thread-selection.ts

176 lines5.9 KB

1import { useRoute, type RouteProp } from "@react-navigation/native";
2import { useMemo, useRef } from "react";
3import {
4 EnvironmentId,
5 ThreadId,
6 type OrchestrationV2ThreadProjection,
7 type OrchestrationV2ThreadShell,
8 type ScopedProjectRef,
9 type ScopedThreadRef,
10} from "@t3tools/contracts";
11import {
12 presentThreadShell,
13 type EnvironmentThreadShell,
14} from "@t3tools/client-runtime/state/shell";
15import {
16 deriveLatestThreadRun,
17 deriveThreadRuntime,
18} from "@t3tools/client-runtime/state/thread-execution";
19import * as Option from "effect/Option";
20​
21import { useProject, useThreadShell } from "../state/entities";
22import { useEnvironmentThread } from "../state/threads";
23import {
24 useRemoteEnvironmentRuntime,
25 useSavedRemoteConnection,
26} from "./use-remote-environment-registry";
27type ThreadSelectionRouteParams = {
28 readonly environmentId?: string | string[];
29 readonly threadId?: string | string[];
30};
31​
32function firstRouteParam(value: string | string[] | undefined): string | null {
33 if (Array.isArray(value)) {
34 return value[0] ?? null;
35 }
36​
37 return value ?? null;
39​
40function latestUserMessageAt(
41 projection: OrchestrationV2ThreadProjection,
42): OrchestrationV2ThreadShell["latestUserMessageAt"] {
43 for (let index = projection.messages.length - 1; index >= 0; index -= 1) {
44 const message = projection.messages[index];
45 if (message?.role === "user") {
46 return message.createdAt;
47 }
48 }
49​
50 return null;
52​
53/**
54 * Builds an optimistic thread shell from the detail projection for the window
55 * where the shell list has not materialized the thread yet (e.g. a thread that
56 * was just created from this device).
57 */
58function threadDetailToShell(
59 environmentId: EnvironmentId,
60 projection: OrchestrationV2ThreadProjection,
61): EnvironmentThreadShell {
62 const thread = projection.thread;
63 const latestRun = deriveLatestThreadRun(projection);
64 const runtime = deriveThreadRuntime(projection);
65 const pendingRequest =
66 projection.runtimeRequests.find((request) => request.status === "pending") ?? null;
67 return presentThreadShell(environmentId, {
68 id: thread.id,
69 projectId: thread.projectId,
70 title: thread.title,
71 providerInstanceId: thread.providerInstanceId,
72 modelSelection: thread.modelSelection,
73 runtimeMode: thread.runtimeMode,
74 interactionMode: thread.interactionMode,
75 branch: thread.branch,
76 worktreePath: thread.worktreePath,
77 activeProviderThreadId: thread.activeProviderThreadId,
78 lineage: thread.lineage,
79 forkedFrom: thread.forkedFrom,
80 createdBy: thread.createdBy,
81 creationSource: thread.creationSource,
82 latestRunId: latestRun?.runId ?? null,
83 activeRunId: runtime?.activeRunId ?? null,
84 status: runtime?.status ?? "idle",
85 pendingRuntimeRequest:
86 pendingRequest === null
87 ? null
88 : { id: pendingRequest.id, kind: pendingRequest.kind, createdAt: pendingRequest.createdAt },
89 latestVisibleMessage: null,
90 latestUserMessageAt: latestUserMessageAt(projection),
91 hasActionableProposedPlan: false,
92 itemCount: projection.turnItems.length,
93 visibleItemCount: projection.visibleTurnItems.length,
94 createdAt: thread.createdAt,
95 updatedAt: thread.updatedAt,
96 archivedAt: thread.archivedAt,
97 settledOverride: thread.settledOverride,
98 settledAt: thread.settledAt,
99 snoozedUntil: thread.snoozedUntil ?? null,
100 snoozedAt: thread.snoozedAt ?? null,
101 deletedAt: thread.deletedAt,
102 });
104​
105function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) {
106 const routeParams = params ?? {};
107 const routeThreadRef = useMemo<ScopedThreadRef | null>(() => {
108 const environmentId = firstRouteParam(routeParams.environmentId);
109 const threadId = firstRouteParam(routeParams.threadId);
110 if (!environmentId || !threadId) {
111 return null;
112 }
113​
114 return {
115 environmentId: EnvironmentId.make(environmentId),
116 threadId: ThreadId.make(threadId),
117 };
118 }, [routeParams.environmentId, routeParams.threadId]);
119 const lastRouteThreadRef = useRef<ScopedThreadRef | null>(null);
120 if (routeThreadRef !== null) {
121 lastRouteThreadRef.current = routeThreadRef;
122 }
123 const selectedThreadRef = routeThreadRef ?? lastRouteThreadRef.current;
124 const selectedThreadShell = useThreadShell(selectedThreadRef);
125 const selectedThreadDetailState = useEnvironmentThread(
126 selectedThreadRef?.environmentId ?? null,
127 selectedThreadRef?.threadId ?? null,
128 );
129 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
130 const selectedThread = useMemo(
131 () =>
132 selectedThreadShell ??
133 (selectedThreadRef !== null && selectedThreadDetail !== null
134 ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail)
135 : null),
136 [selectedThreadDetail, selectedThreadRef, selectedThreadShell],
137 );
138 const selectedProjectRef = useMemo<ScopedProjectRef | null>(
139 () =>
140 selectedThread === null
141 ? null
142 : {
143 environmentId: selectedThread.environmentId,
144 projectId: selectedThread.projectId,
145 },
146 [selectedThread],
147 );
148 const selectedThreadProject = useProject(selectedProjectRef);
149 const selectedEnvironmentId = selectedThread?.environmentId ?? null;
150 const selectedEnvironmentConnection = useSavedRemoteConnection(selectedEnvironmentId);
151 const selectedEnvironmentRuntime = useRemoteEnvironmentRuntime(selectedEnvironmentId);
152​
153 return useMemo(
154 () => ({
155 selectedThreadRef,
156 selectedThread,
157 selectedThreadProject,
158 selectedEnvironmentConnection,
159 selectedEnvironmentRuntime,
160 }),
161 [
162 selectedEnvironmentConnection,
163 selectedEnvironmentRuntime,
164 selectedThread,
165 selectedThreadProject,
166 selectedThreadRef,
167 ],
168 );
170​
171type ThreadSelectionState = ReturnType<typeof useResolvedThreadSelection>;
172​
173export function useThreadSelection(): ThreadSelectionState {
174 const route = useRoute<RouteProp<Record<string, ThreadSelectionRouteParams | undefined>>>();
175 return useResolvedThreadSelection(route.params);