@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 170 lines 5.79 KB
Raw
1 import { m } from "../i18n/messages";
2 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3 import { AuthProvidersManageScope, PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts";
4 import {
5 isAtomCommandInterrupted,
6 settlePromise,
7 squashAtomCommandFailure,
8 } from "@t3tools/client-runtime/state/runtime";
9 import { useRef, useState } from "react";
10 import { T, useGT } from "gt-react";
11
12 import { useEnvironmentProviders, useEnvironments } from "~/state/environments";
13 import { serverEnvironment } from "~/state/server";
14 import { useEnvironmentsWithScope } from "~/state/session";
15 import { useAtomCommand } from "~/state/use-atom-command";
16 import {
17 canOneClickUpdateProviderCandidate,
18 collectProviderUpdateCandidates,
19 getProviderUpdateRunToastView,
20 type ProviderUpdateRun,
21 } from "./ProviderUpdateLaunchNotification.logic";
22 import { Button } from "./ui/button";
23 import { stackedThreadToast, toastManager } from "./ui/toast";
24 import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
25
26 // `refreshModels` always drops the server's hour-long latest-version cache. `modelCatalogOnly`
27 // drops it only when the model manifest changed.
28 export function useCheckProviderUpdates() {
29 const gt = useGT();
30 const { environments } = useEnvironments();
31 const manageableIds = useEnvironmentsWithScope(environments, AuthProvidersManageScope);
32 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
33 reportFailure: false,
34 });
35 const inFlight = useRef<Promise<void> | null>(null);
36
37 const check = async (quiet: boolean) => {
38 const failures = await Promise.all(
39 environments
40 .filter(
41 (environment) =>
42 environment.connection.phase === "connected" &&
43 manageableIds.has(environment.environmentId),
44 )
45 .map(async ({ environmentId, label }) => {
46 const result = await refreshProviders({ environmentId, input: { refreshModels: true } });
47 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return [];
48 const error = squashAtomCommandFailure(result);
49 return [`${label}: ${thrownErrorMessage(error, m) ?? gt("Refresh failed.")}`];
50 }),
51 );
52 const lines = failures.flat();
53 if (quiet || lines.length === 0) return;
54 toastManager.add(
55 stackedThreadToast({
56 type: "error",
57 title: gt("Could not check provider updates"),
58 description: <span className="whitespace-pre-line">{lines.join("\n")}</span>,
59 }),
60 );
61 };
62
63 // A repeat click must not start a second model rediscovery while one is running.
64 return ({ quiet = false }: { readonly quiet?: boolean } = {}) => {
65 if (inFlight.current) return inFlight.current;
66 const running = check(quiet).finally(() => {
67 inFlight.current = null;
68 });
69 inFlight.current = running;
70 return running;
71 };
72 }
73
74 export function useProviderUpdates() {
75 const { environments } = useEnvironments();
76 const manageableIds = useEnvironmentsWithScope(environments, AuthProvidersManageScope);
77 const providersByEnvironment = useEnvironmentProviders();
78 const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
79 reportFailure: false,
80 });
81 const machines = environments.flatMap((environment) => {
82 const providers = providersByEnvironment.get(environment.environmentId) ?? [];
83 if (
84 environment.connection.phase !== "connected" ||
85 !manageableIds.has(environment.environmentId)
86 ) {
87 return [];
88 }
89 const candidates = collectProviderUpdateCandidates(providers).filter((candidate) =>
90 canOneClickUpdateProviderCandidate(candidate, providers),
91 );
92 return candidates.length > 0
93 ? [{ environmentId: environment.environmentId, label: environment.label, candidates }]
94 : [];
95 });
96
97 const updateAll = async ({ quiet = false }: { readonly quiet?: boolean } = {}) => {
98 const runs = await Promise.all(
99 machines.flatMap(({ environmentId, label, candidates }) =>
100 candidates.map(async (candidate): Promise<ProviderUpdateRun> => ({
101 environmentId,
102 machineLabel: label,
103 driver: candidate.driver,
104 instanceId: candidate.instanceId,
105 result: await updateProvider({
106 environmentId,
107 input: { provider: candidate.driver, instanceId: candidate.instanceId },
108 }),
109 })),
110 ),
111 );
112 const view = quiet ? null : getProviderUpdateRunToastView(runs);
113 if (view) {
114 toastManager.add(
115 stackedThreadToast({
116 ...view,
117 description: <span className="whitespace-pre-line">{view.description}</span>,
118 }),
119 );
120 }
121 return runs;
122 };
123
124 return { machines, updateAll };
125 }
126
127 export function ProviderUpdatesAction() {
128 const { machines, updateAll } = useProviderUpdates();
129 const pending = useRef(false);
130 const [isPending, setIsPending] = useState(false);
131 if (machines.length === 0 && !isPending) {
132 return null;
133 }
134
135 const handleUpdate = async () => {
136 if (pending.current) return;
137 pending.current = true;
138 setIsPending(true);
139 await settlePromise(() => updateAll());
140 pending.current = false;
141 setIsPending(false);
142 };
143
144 return (
145 <Tooltip>
146 <TooltipTrigger
147 render={
148 <Button
149 size="xs"
150 variant="ghost-muted"
151 disabled={isPending}
152 onClick={() => void handleUpdate()}
153 >
154 {isPending ? <T>Updating…</T> : <T>Update all</T>}
155 </Button>
156 }
157 />
158 <TooltipPopup side="top">
159 {machines.map((machine) => (
160 <div key={machine.environmentId}>
161 {machine.label}:{" "}
162 {machine.candidates
163 .map((candidate) => PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver)
164 .join(", ")}
165 </div>
166 ))}
167 </TooltipPopup>
168 </Tooltip>
169 );
170 }