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

wsNativeApi.ts

206 lines7.1 KB

1import {
2 OrchestrationEvent,
3 ORCHESTRATION_WS_CHANNELS,
4 ORCHESTRATION_WS_METHODS,
5 type NativeApi,
6 ServerConfigUpdatedPayload,
7 TerminalEvent,
8 WS_CHANNELS,
9 WS_METHODS,
10 WsWelcomePayload,
11} from "@t3tools/contracts";
12import { Cause, Schema } from "effect";
13​
14import { showContextMenuFallback } from "./contextMenuFallback";
15import { WsTransport } from "./wsTransport";
16​
17let instance: { api: NativeApi; transport: WsTransport } | null = null;
18const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
19const serverConfigUpdatedListeners = new Set<(payload: ServerConfigUpdatedPayload) => void>();
20let lastWelcome: WsWelcomePayload | null = null;
21let lastServerConfigUpdated: ServerConfigUpdatedPayload | null = null;
22​
23const decodeAndWarnOnFailure = <T>(
24 schema: Schema.Schema<T> & { readonly DecodingServices: never },
25 raw: unknown,
26): T | null => {
27 const decoded = Schema.decodeUnknownExit(schema)(raw);
28 if (decoded._tag === "Failure") {
29 console.warn("Dropped inbound WebSocket push payload", {
30 reason: "decode-failed",
31 raw,
32 issue: Cause.pretty(decoded.cause),
33 });
34 return null;
35 }
36 return decoded.value;
37};
38​
39/**
40 * Subscribe to the server welcome message. If a welcome was already received
41 * before this call, the listener fires synchronously with the cached payload.
42 * This avoids the race between WebSocket connect and React effect registration.
43 */
44export function onServerWelcome(listener: (payload: WsWelcomePayload) => void): () => void {
45 welcomeListeners.add(listener);
46​
47 // Replay cached welcome for late subscribers
48 if (lastWelcome) {
49 try {
50 listener(lastWelcome);
51 } catch {
52 // Swallow listener errors
53 }
54 }
55​
56 return () => {
57 welcomeListeners.delete(listener);
58 };
60​
61/**
62 * Subscribe to server config update events. Replays the latest update for
63 * late subscribers to avoid missing config validation feedback.
64 */
65export function onServerConfigUpdated(
66 listener: (payload: ServerConfigUpdatedPayload) => void,
67): () => void {
68 serverConfigUpdatedListeners.add(listener);
69​
70 if (lastServerConfigUpdated) {
71 try {
72 listener(lastServerConfigUpdated);
73 } catch {
74 // Swallow listener errors
75 }
76 }
77​
78 return () => {
79 serverConfigUpdatedListeners.delete(listener);
80 };
82​
83export function createWsNativeApi(): NativeApi {
84 if (instance) return instance.api;
85​
86 const transport = new WsTransport();
87​
88 // Listen for server welcome and forward to registered listeners.
89 // Also cache it so late subscribers (React effects) get it immediately.
90 transport.subscribe(WS_CHANNELS.serverWelcome, (data) => {
91 const payload = decodeAndWarnOnFailure(WsWelcomePayload, data);
92 if (!payload) return;
93 lastWelcome = payload;
94 for (const listener of welcomeListeners) {
95 try {
96 listener(payload);
97 } catch {
98 // Swallow listener errors
99 }
100 }
101 });
102 transport.subscribe(WS_CHANNELS.serverConfigUpdated, (data) => {
103 const payload = decodeAndWarnOnFailure(ServerConfigUpdatedPayload, data);
104 if (!payload) return;
105 lastServerConfigUpdated = payload;
106 for (const listener of serverConfigUpdatedListeners) {
107 try {
108 listener(payload);
109 } catch {
110 // Swallow listener errors
111 }
112 }
113 });
114​
115 const api: NativeApi = {
116 dialogs: {
117 pickFolder: async () => {
118 if (!window.desktopBridge) return null;
119 return window.desktopBridge.pickFolder();
120 },
121 confirm: async (message) => {
122 if (window.desktopBridge) {
123 return window.desktopBridge.confirm(message);
124 }
125 return window.confirm(message);
126 },
127 },
128 terminal: {
129 open: (input) => transport.request(WS_METHODS.terminalOpen, input),
130 write: (input) => transport.request(WS_METHODS.terminalWrite, input),
131 resize: (input) => transport.request(WS_METHODS.terminalResize, input),
132 clear: (input) => transport.request(WS_METHODS.terminalClear, input),
133 restart: (input) => transport.request(WS_METHODS.terminalRestart, input),
134 close: (input) => transport.request(WS_METHODS.terminalClose, input),
135 onEvent: (callback) =>
136 transport.subscribe(WS_CHANNELS.terminalEvent, (data) => {
137 const payload = decodeAndWarnOnFailure(TerminalEvent, data);
138 if (payload) callback(payload);
139 }),
140 },
141 projects: {
142 searchEntries: (input) => transport.request(WS_METHODS.projectsSearchEntries, input),
143 },
144 shell: {
145 openInEditor: (cwd, editor) =>
146 transport.request(WS_METHODS.shellOpenInEditor, { cwd, editor }),
147 openExternal: async (url) => {
148 if (window.desktopBridge) {
149 const opened = await window.desktopBridge.openExternal(url);
150 if (!opened) {
151 throw new Error("Unable to open link.");
152 }
153 return;
154 }
155​
156 // Some mobile browsers can return null here even when the tab opens.
157 // Avoid false negatives and let the browser handle popup policy.
158 window.open(url, "_blank", "noopener,noreferrer");
159 },
160 },
161 git: {
162 pull: (input) => transport.request(WS_METHODS.gitPull, input),
163 status: (input) => transport.request(WS_METHODS.gitStatus, input),
164 runStackedAction: (input) => transport.request(WS_METHODS.gitRunStackedAction, input),
165 listBranches: (input) => transport.request(WS_METHODS.gitListBranches, input),
166 createWorktree: (input) => transport.request(WS_METHODS.gitCreateWorktree, input),
167 removeWorktree: (input) => transport.request(WS_METHODS.gitRemoveWorktree, input),
168 createBranch: (input) => transport.request(WS_METHODS.gitCreateBranch, input),
169 checkout: (input) => transport.request(WS_METHODS.gitCheckout, input),
170 init: (input) => transport.request(WS_METHODS.gitInit, input),
171 },
172 contextMenu: {
173 show: async <T extends string>(
174 items: readonly { id: T; label: string }[],
175 position?: { x: number; y: number },
176 ): Promise<T | null> => {
177 if (window.desktopBridge) {
178 return window.desktopBridge.showContextMenu(items) as Promise<T | null>;
179 }
180 return showContextMenuFallback(items, position);
181 },
182 },
183 server: {
184 getConfig: () => transport.request(WS_METHODS.serverGetConfig),
185 upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
186 },
187 orchestration: {
188 getSnapshot: () => transport.request(ORCHESTRATION_WS_METHODS.getSnapshot),
189 dispatchCommand: (command) =>
190 transport.request(ORCHESTRATION_WS_METHODS.dispatchCommand, { command }),
191 getTurnDiff: (input) => transport.request(ORCHESTRATION_WS_METHODS.getTurnDiff, input),
192 getFullThreadDiff: (input) =>
193 transport.request(ORCHESTRATION_WS_METHODS.getFullThreadDiff, input),
194 replayEvents: (fromSequenceExclusive) =>
195 transport.request(ORCHESTRATION_WS_METHODS.replayEvents, { fromSequenceExclusive }),
196 onDomainEvent: (callback) =>
197 transport.subscribe(ORCHESTRATION_WS_CHANNELS.domainEvent, (data) => {
198 const payload = decodeAndWarnOnFailure(OrchestrationEvent, data);
199 if (payload) callback(payload);
200 }),
201 },
202 };
203​
204 instance = { api, transport };
205 return api;