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

useProviderWorkspaceSnapshotRefresh.ts

146 lines5.9 KB

1import {
2 type EnvironmentId,
3 PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS,
4 type ServerProvider,
5} from "@t3tools/contracts";
6import { type ProviderInstanceEntry } from "../../providerInstances";
7import {
8 hasCompleteProviderWorkspaceSnapshot,
9 hasCurrentProviderWorkspaceSnapshot,
10} from "@t3tools/client-runtime/providerSkills";
11import { serverEnvironment } from "../../state/server";
12import { useAtomCommand } from "../../state/use-atom-command";
13import { useEffect, useEffectEvent, useRef, useState } from "react";
14import { useStableCallback } from "../../hooks/useStableCallback";
15​
16const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
17// A cwd that never scans, such as a deleted worktree, would otherwise retry forever.
18const WORKSPACE_SNAPSHOT_MAX_ATTEMPTS = 3;
19​
20/**
21 * Keeps the selected provider's workspace snapshot fresh for the composer's
22 * cwd. Returns a check to run when the user types.
23 */
24export function useProviderWorkspaceSnapshotRefresh(input: {
25 readonly environmentId: EnvironmentId;
26 readonly gitCwd: string | null;
27 readonly selectedProviderEntry: ProviderInstanceEntry | undefined;
28 readonly selectedProviderStatus: ServerProvider | null;
29}) {
30 const { environmentId, gitCwd, selectedProviderEntry, selectedProviderStatus } = input;
31 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
32 reportFailure: false,
33 });
34 // The last scan this composer asked for. A request inside the TTL is not
35 // repeated, so a client clock ahead of the server's cannot loop rescans.
36 const workspaceRefreshKeyRef = useRef<{ key: string; requestedAt: number } | null>(null);
37 const failedRefreshesRef = useRef<{ key: string; count: number } | null>(null);
38 const [workspaceRefreshRetry, setWorkspaceRefreshRetry] = useState<{
39 key: string;
40 notBefore: number;
41 } | null>(null);
42 const workspaceRefreshScopeKey =
43 gitCwd && selectedProviderEntry
44 ? `${environmentId}:${selectedProviderEntry.instanceId}:${gitCwd}`
45 : null;
46 const workspaceSlashCommandsPending =
47 selectedProviderStatus?.workspaceSnapshots?.some(
48 (snapshot) => snapshot.cwd === gitCwd && snapshot.slashCommandsPending === true,
49 ) ?? false;
50 useEffect(() => {
51 if (
52 !workspaceSlashCommandsPending ||
53 !workspaceRefreshRetry ||
54 workspaceRefreshRetry.key !== workspaceRefreshScopeKey
55 )
56 return;
57 const timeout = setTimeout(
58 () => {
59 setWorkspaceRefreshRetry((current) => (current === workspaceRefreshRetry ? null : current));
60 },
61 Math.max(0, workspaceRefreshRetry.notBefore - Date.now()),
62 );
63 return () => clearTimeout(timeout);
64 }, [workspaceRefreshRetry, workspaceRefreshScopeKey, workspaceSlashCommandsPending]);
65 // Losing a snapshot (the server dropped it) lifts both the TTL and the retry
66 // cooldown so the next check rescans at once.
67 const hasWorkspaceSnapshot = hasCompleteProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd);
68 const [hadWorkspaceSnapshot, setHadWorkspaceSnapshot] = useState(hasWorkspaceSnapshot);
69 const [workspaceSnapshotLossCount, setWorkspaceSnapshotLossCount] = useState(0);
70 if (hadWorkspaceSnapshot !== hasWorkspaceSnapshot) {
71 setHadWorkspaceSnapshot(hasWorkspaceSnapshot);
72 if (!hasWorkspaceSnapshot) {
73 setWorkspaceSnapshotLossCount((count) => count + 1);
74 setWorkspaceRefreshRetry(null);
75 }
76 }
77 const lastWorkspaceSnapshotLossRef = useRef(workspaceSnapshotLossCount);
78 const refreshWorkspaceSnapshotIfStale = (
79 now: number,
80 key: string | null,
81 retry: { key: string; notBefore: number } | null,
82 snapshotLossCount: number,
83 ) => {
84 if (lastWorkspaceSnapshotLossRef.current !== snapshotLossCount) {
85 lastWorkspaceSnapshotLossRef.current = snapshotLossCount;
86 workspaceRefreshKeyRef.current = null;
87 }
88 if (key === null || !gitCwd || !selectedProviderEntry) return;
89 const lastRequest = workspaceRefreshKeyRef.current;
90 if (
91 lastRequest?.key === key &&
92 now - lastRequest.requestedAt < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS
93 )
94 return;
95 // A pending retry needs no clearing here: its cooldown lapses long before the TTL.
96 if (hasCurrentProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd, now)) return;
97 if (retry?.key === key && now < retry.notBefore) return;
98 const request = { key, requestedAt: now };
99 workspaceRefreshKeyRef.current = request;
100 const retryLater = () => {
101 if (workspaceRefreshKeyRef.current !== request) return;
102 const failed = failedRefreshesRef.current;
103 const count = failed?.key === key ? failed.count + 1 : 1;
104 failedRefreshesRef.current = { key, count };
105 // Keeping the request marker lets the TTL hold off the next scan.
106 if (count >= WORKSPACE_SNAPSHOT_MAX_ATTEMPTS) return;
107 workspaceRefreshKeyRef.current = null;
108 setWorkspaceRefreshRetry({
109 key,
110 notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
111 });
112 };
113 void refreshProviders({
114 environmentId,
115 input: { instanceId: selectedProviderEntry.instanceId, cwd: gitCwd },
116 }).then((result) => {
117 const refreshedSnapshot =
118 result._tag === "Success" &&
119 hasCompleteProviderWorkspaceSnapshot(
120 result.value.providers.find(
121 (provider) => provider.instanceId === selectedProviderEntry.instanceId,
122 ),
123 gitCwd,
124 );
125 if (!refreshedSnapshot) retryLater();
126 else failedRefreshesRef.current = null;
127 }, retryLater);
128 };
129 const refreshWorkspaceSnapshotOnChange = useEffectEvent(refreshWorkspaceSnapshotIfStale);
130 useEffect(() => {
131 refreshWorkspaceSnapshotOnChange(
132 Date.now(),
133 workspaceRefreshScopeKey,
134 workspaceRefreshRetry,
135 workspaceSnapshotLossCount,
136 );
137 }, [workspaceRefreshScopeKey, workspaceRefreshRetry, workspaceSnapshotLossCount]);
138 return useStableCallback(() =>
139 refreshWorkspaceSnapshotIfStale(
140 Date.now(),
141 workspaceRefreshScopeKey,
142 workspaceRefreshRetry,
143 workspaceSnapshotLossCount,
144 ),
145 );