@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
ts 396 lines 15.7 KB
Raw
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, describe, it } from "@effect/vitest";
3 import * as Deferred from "effect/Deferred";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
7
8 import type { DesktopUpdateCheckResult, DesktopUpdateState } from "@t3tools/contracts";
9 import * as Electron from "electron";
10 import { vi } from "vite-plus/test";
11
12 vi.mock("electron", () => ({
13 webContents: { getAllWebContents: vi.fn(() => []) },
14 }));
15
16 import * as ElectronApp from "../electron/ElectronApp.ts";
17 import * as ElectronDialog from "../electron/ElectronDialog.ts";
18 import * as ElectronMenu from "../electron/ElectronMenu.ts";
19 import * as DesktopApplicationMenu from "./DesktopApplicationMenu.ts";
20 import * as DesktopConfig from "../app/DesktopConfig.ts";
21 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
22 import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
23 import { createInitialDesktopUpdateState } from "../updates/updateMachine.ts";
24 import * as DesktopWindow from "./DesktopWindow.ts";
25
26 const environmentInput = {
27 dirname: "/repo/apps/desktop/dist-electron",
28 homeDirectory: "/Users/alice",
29 platform: "linux",
30 processArch: "arm64",
31 appVersion: "1.2.3",
32 appPath: "/repo",
33 isPackaged: false,
34 resourcesPath: "/repo/resources",
35 runningUnderArm64Translation: false,
36 } satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
37
38 const layerElectronApp = Layer.succeed(ElectronApp.ElectronApp, {
39 metadata: Effect.die("unexpected metadata read"),
40 name: Effect.succeed("T3 Code"),
41 systemLocale: Effect.succeed("en-US"),
42 preferredSystemLanguages: Effect.succeed(["en-US"]),
43 whenReady: Effect.void,
44 requestSingleInstanceLock: Effect.succeed(true),
45 quit: Effect.void,
46 exit: () => Effect.void,
47 relaunch: () => Effect.void,
48 setPath: () => Effect.void,
49 setName: () => Effect.void,
50 setAboutPanelOptions: () => Effect.void,
51 setAppUserModelId: () => Effect.void,
52 getAppMetrics: Effect.succeed([]),
53 setAsDefaultProtocolClient: () => Effect.succeed(true),
54 setDesktopName: () => Effect.void,
55 setDockIcon: () => Effect.void,
56 appendCommandLineSwitch: () => Effect.void,
57 onBeforeQuitForUpdate: () => Effect.void,
58 removeCommandLineSwitch: () => Effect.void,
59 on: () => Effect.void,
60 } satisfies ElectronApp.ElectronApp["Service"]);
61
62 interface MenuServices {
63 readonly checkResult?: DesktopUpdateCheckResult;
64 readonly shownMessageBox?: Deferred.Deferred<Electron.MessageBoxOptions>;
65 }
66
67 const layerElectronDialog = ({ shownMessageBox }: MenuServices) =>
68 Layer.succeed(ElectronDialog.ElectronDialog, {
69 pickFolder: () => Effect.succeedNone,
70 pickFiles: () => Effect.succeed([]),
71 showMessageBox: (options) =>
72 (shownMessageBox ? Deferred.succeed(shownMessageBox, options) : Effect.void).pipe(
73 Effect.as({ response: options.cancelId ?? 0, checkboxChecked: false }),
74 ),
75 showErrorBox: () => Effect.void,
76 } satisfies ElectronDialog.ElectronDialog["Service"]);
77
78 const layerDesktopUpdates = ({ checkResult }: MenuServices) =>
79 Layer.succeed(DesktopUpdates.DesktopUpdates, {
80 getState: Effect.die("unexpected getState"),
81 isActionActive: Effect.succeed(false),
82 isInstallActive: Effect.succeed(false),
83 subscribe: Effect.die("unexpected subscribe"),
84 emitState: Effect.void,
85 disabledReason: Effect.succeedNone,
86 configure: Effect.void,
87 setChannel: () => Effect.die("unexpected setChannel"),
88 check: () => (checkResult ? Effect.succeed(checkResult) : Effect.die("unexpected check")),
89 download: Effect.die("unexpected download"),
90 install: Effect.die("unexpected install"),
91 installPrepared: () => Effect.die("unexpected installPrepared"),
92 } satisfies DesktopUpdates.DesktopUpdates["Service"]);
93
94 const layerDesktopWindow = (selectedAction: Deferred.Deferred<string>) =>
95 Layer.succeed(DesktopWindow.DesktopWindow, {
96 createMain: Effect.die("unexpected createMain"),
97 ensureMain: Effect.die("unexpected ensureMain"),
98 revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"),
99 activate: Effect.void,
100 createMainIfBackendReady: Effect.void,
101 showConnectingSplash: Effect.void,
102 handleBackendReady: () => Effect.void,
103 handleBackendNotReady: Effect.void,
104 flushMainWindowBounds: Effect.void,
105 prepareCaptureReveal: Effect.void,
106 dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
107 dispatchSnapShotEvent: () => Effect.void,
108 zoomMain: (direction) =>
109 Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid),
110 runMainContentsCommand: (command) =>
111 Deferred.succeed(selectedAction, `main-${command}`).pipe(Effect.asVoid),
112 syncAppearance: Effect.void,
113 } satisfies DesktopWindow.DesktopWindow["Service"]);
114
115 const layerElectronMenu = (
116 applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
117 ) =>
118 Layer.succeed(ElectronMenu.ElectronMenu, {
119 setApplicationMenu: (template) =>
120 Deferred.succeed(applicationMenuTemplate, template).pipe(Effect.asVoid),
121 popupTemplate: () => Effect.void,
122 showContextMenu: () => Effect.succeedNone,
123 } satisfies ElectronMenu.ElectronMenu["Service"]);
124
125 const configureMenu = (
126 selectedAction: Deferred.Deferred<string>,
127 applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
128 environment: Partial<DesktopEnvironment.MakeDesktopEnvironmentInput> = {},
129 services: MenuServices = {},
130 ) =>
131 Effect.gen(function* () {
132 const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
133 yield* menu.configure;
134 }).pipe(
135 Effect.provide(
136 DesktopApplicationMenu.layer.pipe(
137 Layer.provideMerge(layerElectronMenu(applicationMenuTemplate)),
138 Layer.provideMerge(layerDesktopWindow(selectedAction)),
139 Layer.provideMerge(layerDesktopUpdates(services)),
140 Layer.provideMerge(layerElectronDialog(services)),
141 Layer.provideMerge(layerElectronApp),
142 Layer.provideMerge(
143 DesktopEnvironment.layer({ ...environmentInput, ...environment }).pipe(
144 Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
145 ),
146 ),
147 ),
148 ),
149 );
150
151 const checkForUpdatesFromMacMenu = (state: Partial<DesktopUpdateState>) =>
152 Effect.gen(function* () {
153 const applicationMenuTemplate =
154 yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
155 const shownMessageBox = yield* Deferred.make<Electron.MessageBoxOptions>();
156 yield* configureMenu(
157 yield* Deferred.make<string>(),
158 applicationMenuTemplate,
159 { platform: "darwin" },
160 {
161 checkResult: {
162 checked: true,
163 state: {
164 ...createInitialDesktopUpdateState(
165 "0.1.5",
166 { hostArch: "arm64", appArch: "arm64", runningUnderArm64Translation: false },
167 "latest",
168 ),
169 enabled: true,
170 ...state,
171 },
172 },
173 shownMessageBox,
174 },
175 );
176
177 const appMenu = (yield* Deferred.await(applicationMenuTemplate))[0];
178 if (!Array.isArray(appMenu?.submenu)) {
179 throw new Error("Expected the macOS app menu submenu to be an array.");
180 }
181 const checkForUpdates = appMenu.submenu.find((item) => item.label === "Check for Updates...");
182 if (typeof checkForUpdates?.click !== "function") {
183 throw new Error("Expected Check for Updates... menu item to have a click handler.");
184 }
185
186 // Every stub completes synchronously, so the menu action has finished when click returns.
187 checkForUpdates.click(
188 {} as Electron.MenuItem,
189 {} as Electron.BrowserWindow,
190 {} as KeyboardEvent,
191 );
192 const dialog = yield* Deferred.poll(shownMessageBox);
193 if (Option.isNone(dialog)) {
194 throw new Error("Check for Updates... finished without showing any dialog.");
195 }
196 return yield* dialog.value;
197 });
198
199 describe("DesktopApplicationMenu", () => {
200 it.effect("leaves the accelerator to Chromium instead of injecting a paste", () =>
201 Effect.gen(function* () {
202 const selectedAction = yield* Deferred.make<string>();
203 const applicationMenuTemplate =
204 yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
205
206 yield* configureMenu(selectedAction, applicationMenuTemplate);
207
208 const template = yield* Deferred.await(applicationMenuTemplate);
209 const editMenu = template.find((item) => item.label === "Edit");
210 if (!Array.isArray(editMenu?.submenu)) {
211 throw new Error("Expected Edit menu submenu to be an array.");
212 }
213 const pasteAsTextItem = editMenu.submenu.find((item) => item.label === "Paste as Text");
214 if (typeof pasteAsTextItem?.click !== "function") {
215 throw new Error("Expected Paste as Text menu item to have a click handler.");
216 }
217
218 pasteAsTextItem.click(
219 {} as Electron.MenuItem,
220 {} as Electron.BrowserWindow,
221 {
222 triggeredByAccelerator: true,
223 } as unknown as KeyboardEvent,
224 );
225 assert.isFalse(yield* Deferred.isDone(selectedAction));
226 }),
227 );
228
229 it.effect("registers macOS command-plus once and routes it through main-window zoom", () =>
230 Effect.gen(function* () {
231 const selectedAction = yield* Deferred.make<string>();
232 const applicationMenuTemplate =
233 yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
234
235 yield* configureMenu(selectedAction, applicationMenuTemplate, { platform: "darwin" });
236
237 const template = yield* Deferred.await(applicationMenuTemplate);
238 const viewMenu = template.find((item) => item.label === "View");
239 assert.isDefined(viewMenu);
240 if (!Array.isArray(viewMenu.submenu)) {
241 throw new Error("Expected View menu submenu to be an array.");
242 }
243
244 assert.isUndefined(
245 viewMenu.submenu.find((item) =>
246 ["zoom", "reload", "devtools"].some((role) => item.role?.toLowerCase().includes(role)),
247 ),
248 );
249
250 const shiftedEqual = viewMenu.submenu.filter(
251 (item) => item.accelerator === "CmdOrCtrl+Shift+=",
252 );
253 assert.lengthOf(shiftedEqual, 1);
254 assert.lengthOf(
255 viewMenu.submenu.filter((item) => item.accelerator === "CmdOrCtrl+numadd"),
256 1,
257 );
258 const zoomIn = shiftedEqual[0];
259 assert.isDefined(zoomIn);
260 assert.isFalse(zoomIn.visible);
261 if (typeof zoomIn.click !== "function") {
262 throw new Error("Expected Zoom In menu item to have a click handler.");
263 }
264
265 zoomIn.click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
266 assert.equal(yield* Deferred.await(selectedAction), "zoom-in");
267 }),
268 );
269
270 it.effect("never binds Cmd/Ctrl+W to closing the window", () =>
271 Effect.gen(function* () {
272 for (const platform of ["darwin", "linux", "win32"] as const) {
273 const applicationMenuTemplate =
274 yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
275 yield* configureMenu(yield* Deferred.make<string>(), applicationMenuTemplate, {
276 platform,
277 });
278
279 const items: Electron.MenuItemConstructorOptions[] = [];
280 const collect = (template: readonly Electron.MenuItemConstructorOptions[]) => {
281 for (const item of template) {
282 items.push(item);
283 if (Array.isArray(item.submenu)) collect(item.submenu);
284 }
285 };
286 collect(yield* Deferred.await(applicationMenuTemplate));
287
288 assert.isUndefined(
289 items.find((item) => item.role === "close"),
290 platform,
291 );
292 // Electron's default windowMenu submenu includes a close role.
293 assert.isUndefined(
294 items.find((item) => item.role === "windowMenu" && item.submenu === undefined),
295 platform,
296 );
297 const closeTools = items.find((item) => item.accelerator === "CmdOrCtrl+W");
298 assert.equal(closeTools?.label, "Close Developer Tools", platform);
299 assert.isFunction(closeTools?.click);
300 const appContents = {
301 isDestroyed: () => false,
302 isDevToolsFocused: () => false,
303 closeDevTools: vi.fn(),
304 };
305 const inspectedContents = {
306 ...appContents,
307 isDevToolsFocused: () => true,
308 closeDevTools: vi.fn(),
309 };
310 using allContents = vi
311 .spyOn(Electron.webContents, "getAllWebContents")
312 .mockReturnValue([
313 appContents as unknown as Electron.WebContents,
314 inspectedContents as unknown as Electron.WebContents,
315 ]);
316 closeTools?.click?.({} as Electron.MenuItem, undefined, {} as KeyboardEvent);
317 assert.equal(inspectedContents.closeDevTools.mock.calls.length, 1);
318 assert.equal(appContents.closeDevTools.mock.calls.length, 0);
319
320 allContents.mockReturnValue([appContents as unknown as Electron.WebContents]);
321 closeTools?.click?.({} as Electron.MenuItem, undefined, {} as KeyboardEvent);
322 assert.equal(appContents.closeDevTools.mock.calls.length, 0);
323 }
324 }),
325 );
326
327 it.effect("reloads the main window even while a browser page has focus", () =>
328 Effect.gen(function* () {
329 const selectedAction = yield* Deferred.make<string>();
330 const applicationMenuTemplate =
331 yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
332
333 yield* configureMenu(selectedAction, applicationMenuTemplate);
334
335 const template = yield* Deferred.await(applicationMenuTemplate);
336 const viewMenu = template.find((item) => item.label === "View");
337 if (!Array.isArray(viewMenu?.submenu)) {
338 throw new Error("Expected View menu submenu to be an array.");
339 }
340 const reload = viewMenu.submenu.find((item) => item.label === "Reload");
341 assert.equal(reload?.accelerator, "CmdOrCtrl+R");
342 if (typeof reload?.click !== "function") {
343 throw new Error("Expected Reload menu item to have a click handler.");
344 }
345
346 reload.click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
347 assert.equal(yield* Deferred.await(selectedAction), "main-reload");
348 }),
349 );
350 it.effect("tells the user which update the menu check found", () =>
351 Effect.gen(function* () {
352 const dialog = yield* checkForUpdatesFromMacMenu({
353 status: "available",
354 availableVersion: "0.1.7",
355 });
356 assert.include(`${dialog.title ?? ""} ${dialog.message} ${dialog.detail ?? ""}`, "0.1.7");
357 }),
358 );
359
360 it.effect("tells the user a downloaded update is ready when the menu check runs", () =>
361 Effect.gen(function* () {
362 const dialog = yield* checkForUpdatesFromMacMenu({
363 status: "downloaded",
364 availableVersion: "0.1.7",
365 downloadedVersion: "0.1.7",
366 downloadPercent: 100,
367 });
368 assert.include(`${dialog.title ?? ""} ${dialog.message} ${dialog.detail ?? ""}`, "0.1.7");
369 }),
370 );
371
372 it.effect("labels every role item so the menu follows the UI language", () =>
373 Effect.gen(function* () {
374 // Electron's role defaults are English on every platform, so each role item needs a label.
375 for (const platform of ["darwin", "linux", "win32"] as const) {
376 const applicationMenuTemplate =
377 yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
378 yield* configureMenu(yield* Deferred.make<string>(), applicationMenuTemplate, {
379 platform,
380 });
381
382 const unlabeled: string[] = [];
383 const collect = (template: readonly Electron.MenuItemConstructorOptions[]) => {
384 for (const item of template) {
385 if (item.role !== undefined && typeof item.label !== "string") {
386 unlabeled.push(item.role);
387 }
388 if (Array.isArray(item.submenu)) collect(item.submenu);
389 }
390 };
391 collect(yield* Deferred.await(applicationMenuTemplate));
392 assert.deepStrictEqual(unlabeled, [], platform);
393 }
394 }),
395 );
396 });