@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 214 lines 7.88 KB
Raw
1 import {
2 AuthTerminalOperateScope,
3 type DesktopPortForward,
4 type EnvironmentId,
5 type ThreadId,
6 } from "@t3tools/contracts";
7 import { useAtomValue } from "@effect/atom-react";
8 import { useGT } from "gt-react";
9 import { CableIcon, ClipboardCopyIcon, ExternalLinkIcon, SquareIcon } from "lucide-react";
10
11 import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
12 import { readLocalApi } from "../localApi";
13 import { useThreadDiscoveredPorts } from "../portDiscoveryState";
14 import { useEnvironments } from "../state/environments";
15 import {
16 canForwardPorts,
17 findPortForward,
18 forwardedUrl,
19 forwardPort,
20 forwardLocalitiesAtom,
21 stopPortForward,
22 usePortForwards,
23 } from "../state/portForwards";
24 import { environmentIdsKey } from "../state/environmentAtomList";
25 import { useEnvironmentsWithScope } from "../state/session";
26 import {
27 ADDON_ICON_CLASS,
28 ITEM_ICON_CLASS,
29 type CommandPaletteActionItem,
30 type CommandPaletteGroup,
31 type CommandPaletteSubmenuItem,
32 } from "./CommandPalette.logic";
33 import { toastManager } from "./ui/toast";
34
35 /** Prefix of this submenu's group values; the palette rebuilds them live while it is open. */
36 export const PORT_FORWARD_GROUP_PREFIX = "port-forwards:";
37
38 const parsePort = (query: string) => {
39 const trimmed = query.trim();
40 if (!/^\d{1,5}$/.test(trimmed)) return null;
41 const port = Number(trimmed);
42 return port >= 1 && port <= 65_535 ? port : null;
43 };
44
45 /** "Forwarded ports": each forward with its actions, then ports to forward from the thread or the query. */
46 export function useCommandPalettePortForwardItem(input: {
47 readonly activeThread: {
48 readonly environmentId: EnvironmentId;
49 readonly id: ThreadId;
50 } | null;
51 readonly query: string;
52 }): CommandPaletteSubmenuItem | null {
53 const gt = useGT();
54 const forwards = usePortForwards();
55 const { environments } = useEnvironments();
56 const reachable = environments.filter(
57 (environment) => environment.connection.phase === "connected" && canForwardPorts(environment),
58 );
59 const tunnelling = useEnvironmentsWithScope(reachable, AuthTerminalOperateScope);
60 const tunnelled = reachable.filter((environment) => tunnelling.has(environment.environmentId));
61 const localities = useAtomValue(
62 forwardLocalitiesAtom(environmentIdsKey(tunnelled.map(({ environmentId }) => environmentId))),
63 );
64 const sources = tunnelled.filter((_, index) => localities[index] === "remote");
65 // Only a forwardable thread's servers are listed, so other clients never subscribe to them.
66 const threadEnvironmentId = sources.some(
67 (environment) => environment.environmentId === input.activeThread?.environmentId,
68 )
69 ? (input.activeThread?.environmentId ?? null)
70 : null;
71 const threadServers = useThreadDiscoveredPorts({
72 environmentId: threadEnvironmentId,
73 threadId: threadEnvironmentId === null ? null : (input.activeThread?.id ?? null),
74 });
75 if (forwards.length === 0 && sources.length === 0) return null;
76
77 const labelOf = (environmentId: EnvironmentId) =>
78 environments.find((environment) => environment.environmentId === environmentId)?.label ??
79 environmentId;
80
81 const start = async (environmentId: EnvironmentId, remotePort: number) => {
82 const forward = await forwardPort(environmentId, remotePort);
83 toastManager.add({
84 type: "success",
85 title: gt("Forwarded port {port}", { port: remotePort }),
86 description: gt("Apps on this machine reach it at localhost:{port}.", {
87 port: forward.localPort,
88 }),
89 });
90 };
91
92 const forwardedItem = (forward: DesktopPortForward): CommandPaletteSubmenuItem => {
93 const address = `localhost:${forward.localPort}`;
94 const environment = labelOf(forward.environmentId);
95 return {
96 kind: "submenu",
97 value: `port-forward:${forward.environmentId}:${forward.remotePort}`,
98 title: address,
99 description: gt("Port {port} on {environment}", { port: forward.remotePort, environment }),
100 searchTerms: [address, String(forward.remotePort), environment, "forwarded port"],
101 icon: <CableIcon className={ITEM_ICON_CLASS} />,
102 addonIcon: <CableIcon className={ADDON_ICON_CLASS} />,
103 groups: [
104 {
105 value: "port-forward-actions",
106 label: address,
107 items: [
108 {
109 kind: "action",
110 value: "port-forward:open",
111 title: gt("Open in browser"),
112 searchTerms: ["open", "browser"],
113 icon: <ExternalLinkIcon className={ITEM_ICON_CLASS} />,
114 run: async () => {
115 await readLocalApi()?.shell.openExternal(forwardedUrl(forward));
116 },
117 },
118 {
119 kind: "action",
120 value: "port-forward:copy",
121 title: gt("Copy address"),
122 searchTerms: ["copy", "address", "url"],
123 icon: <ClipboardCopyIcon className={ITEM_ICON_CLASS} />,
124 run: async () => {
125 await writeTextToClipboard(forwardedUrl(forward));
126 },
127 },
128 {
129 kind: "action",
130 value: "port-forward:stop",
131 title: gt("Stop forwarding"),
132 searchTerms: ["stop", "remove", "close"],
133 icon: <SquareIcon className={ITEM_ICON_CLASS} />,
134 run: () => stopPortForward(forward.environmentId, forward.remotePort),
135 },
136 ],
137 },
138 ],
139 };
140 };
141
142 const startItems: CommandPaletteActionItem[] = [];
143 for (const server of threadServers) {
144 const environmentId = threadEnvironmentId;
145 if (environmentId === null) break;
146 if (findPortForward(forwards, environmentId, server.port)) continue;
147 startItems.push({
148 kind: "action",
149 value: `port-forward:start:${environmentId}:${server.port}`,
150 title: gt("Forward localhost:{port}", { port: server.port }),
151 description: [labelOf(environmentId), server.processName].filter(Boolean).join(" · "),
152 searchTerms: [String(server.port), server.processName ?? "", "forward"],
153 icon: <CableIcon className={ITEM_ICON_CLASS} />,
154 run: () => start(environmentId, server.port),
155 });
156 }
157 const typedPort = parsePort(input.query);
158 if (typedPort !== null) {
159 for (const environment of sources) {
160 if (findPortForward(forwards, environment.environmentId, typedPort)) continue;
161 if (
162 startItems.some((item) => item.value.endsWith(`:${environment.environmentId}:${typedPort}`))
163 )
164 continue;
165 startItems.push({
166 kind: "action",
167 value: `port-forward:start:${environment.environmentId}:${typedPort}`,
168 title: gt("Forward port {port} from {environment}", {
169 port: typedPort,
170 environment: environment.label,
171 }),
172 searchTerms: [String(typedPort), "forward"],
173 icon: <CableIcon className={ITEM_ICON_CLASS} />,
174 run: () => start(environment.environmentId, typedPort),
175 });
176 }
177 }
178
179 const groups: CommandPaletteGroup[] = [];
180 if (forwards.length > 0) {
181 groups.push({
182 value: `${PORT_FORWARD_GROUP_PREFIX}forwarded`,
183 label: gt("Forwarded"),
184 items: forwards.map(forwardedItem),
185 });
186 }
187 if (startItems.length === 0 && sources.length > 0) {
188 startItems.push({
189 kind: "action",
190 value: "port-forward:hint",
191 title: gt("Type a port number to forward it"),
192 searchTerms: [],
193 icon: <CableIcon className={ITEM_ICON_CLASS} />,
194 disabled: true,
195 run: async () => {},
196 });
197 }
198 // Always present, so the open submenu keeps a group to be recognized by.
199 groups.push({
200 value: `${PORT_FORWARD_GROUP_PREFIX}start`,
201 label: startItems.length > 0 ? gt("Forward a port") : "",
202 items: startItems,
203 });
204
205 return {
206 kind: "submenu",
207 value: "action:port-forwards",
208 title: gt("Forwarded ports"),
209 searchTerms: ["forward port", "port forwarding", "forwarded ports", "ports", "tunnel"],
210 icon: <CableIcon className={ITEM_ICON_CLASS} />,
211 addonIcon: <CableIcon className={ADDON_ICON_CLASS} />,
212 groups,
213 };
214 }