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
| 1 | import { assert, describe, it } from "@effect/vitest"; |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import type { ManagedPolicyLimits } from "@t3tools/contracts"; |
| 4 | import { EDITORS, REMOTE_CAPABLE_EDITOR_IDS } from "@t3tools/contracts"; |
| 5 | import { resolveEditorCommand } from "@t3tools/shared/editor"; |
| 6 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 7 | import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile"; |
| 8 | import * as FileSystem from "effect/FileSystem"; |
| 9 | import * as Path from "effect/Path"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Layer from "effect/Layer"; |
| 12 | import * as Option from "effect/Option"; |
| 13 | import * as Stream from "effect/Stream"; |
| 14 | import { vi } from "vite-plus/test"; |
| 15 | import type * as Electron from "electron"; |
| 16 | |
| 17 | const { focusedWebContents, ownerWindow } = vi.hoisted(() => ({ |
| 18 | focusedWebContents: vi.fn(), |
| 19 | ownerWindow: vi.fn(), |
| 20 | })); |
| 21 | vi.mock("electron", () => ({ |
| 22 | webContents: { getFocusedWebContents: focusedWebContents }, |
| 23 | BrowserWindow: { fromWebContents: ownerWindow }, |
| 24 | })); |
| 25 | |
| 26 | import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts"; |
| 27 | import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; |
| 28 | import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; |
| 29 | import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; |
| 30 | import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts"; |
| 31 | import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; |
| 32 | import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; |
| 33 | import * as ElectronDialog from "../../electron/ElectronDialog.ts"; |
| 34 | import * as ElectronWindow from "../../electron/ElectronWindow.ts"; |
| 35 | import * as IpcChannels from "../channels.ts"; |
| 36 | import * as DesktopIpc from "../DesktopIpc.ts"; |
| 37 | import { |
| 38 | getLocalEnvironmentBootstraps, |
| 39 | installRelayTelemetryEnabled, |
| 40 | pickProjectFavicon, |
| 41 | probeRemoteEditors, |
| 42 | readMedia, |
| 43 | syncHtmlFullscreen, |
| 44 | toLocalBackendPath, |
| 45 | } from "./window.ts"; |
| 46 | |
| 47 | const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = { |
| 48 | executablePath: "wsl.exe", |
| 49 | args: ["-d", "Ubuntu", "--", "node", "/app/bin.mjs"], |
| 50 | entryPath: "/app/bin.mjs", |
| 51 | cwd: "/app", |
| 52 | env: {}, |
| 53 | extendEnv: false, |
| 54 | bootstrap: { |
| 55 | mode: "desktop", |
| 56 | noBrowser: true, |
| 57 | port: 3774, |
| 58 | host: "0.0.0.0", |
| 59 | desktopBootstrapToken: "bootstrap-token", |
| 60 | tailscaleServeEnabled: false, |
| 61 | tailscaleServePort: 443, |
| 62 | }, |
| 63 | bootstrapDelivery: "stdin", |
| 64 | httpBaseUrl: new URL("http://127.0.0.1:3774"), |
| 65 | captureOutput: true, |
| 66 | preflightFailure: Option.none(), |
| 67 | runningDistro: "Ubuntu", |
| 68 | }; |
| 69 | |
| 70 | const defaultWslInstance: DesktopBackendManager.DesktopBackendInstance = { |
| 71 | id: DesktopBackendManager.BackendInstanceId("wsl:default"), |
| 72 | label: Effect.succeed("WSL (default distro)"), |
| 73 | start: Effect.void, |
| 74 | stop: () => Effect.void, |
| 75 | currentConfig: Effect.succeedSome(readyWslConfig), |
| 76 | snapshot: Effect.succeed({ |
| 77 | desiredRunning: true, |
| 78 | ready: true, |
| 79 | activePid: Option.some(123), |
| 80 | restartAttempt: 0, |
| 81 | restartScheduled: false, |
| 82 | }), |
| 83 | waitForReady: () => Effect.succeed(true), |
| 84 | }; |
| 85 | |
| 86 | const backendConfigurationLayer = Layer.succeed( |
| 87 | DesktopBackendConfiguration.DesktopBackendConfiguration, |
| 88 | { |
| 89 | resolvePrimary: Effect.die("unexpected resolvePrimary"), |
| 90 | resolvePrimaryLabel: Effect.succeed("Windows"), |
| 91 | resolveWsl: () => Effect.die("unexpected resolveWsl"), |
| 92 | currentBootstrapToken: Effect.succeed("current-window-token"), |
| 93 | } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"], |
| 94 | ); |
| 95 | |
| 96 | const bootstrapsLayer = (instances: ReadonlyArray<DesktopBackendManager.DesktopBackendInstance>) => |
| 97 | Layer.merge(DesktopBackendPool.layerTest([...instances]), backendConfigurationLayer); |
| 98 | |
| 99 | describe("getLocalEnvironmentBootstraps", () => { |
| 100 | it.effect("hands out the current window's token to a backend launched with the secret", () => |
| 101 | Effect.gen(function* () { |
| 102 | const result = yield* getLocalEnvironmentBootstraps.handler(); |
| 103 | |
| 104 | assert.deepEqual(result, [ |
| 105 | { |
| 106 | id: "wsl:default", |
| 107 | label: "WSL (Ubuntu)", |
| 108 | runningDistro: "Ubuntu", |
| 109 | httpBaseUrl: "http://127.0.0.1:3774/", |
| 110 | wsBaseUrl: "ws://127.0.0.1:3774/", |
| 111 | bootstrapToken: "current-window-token", |
| 112 | }, |
| 113 | ]); |
| 114 | }).pipe( |
| 115 | Effect.provide( |
| 116 | bootstrapsLayer([ |
| 117 | { |
| 118 | ...defaultWslInstance, |
| 119 | currentConfig: Effect.succeedSome({ |
| 120 | ...readyWslConfig, |
| 121 | bootstrap: { |
| 122 | ...readyWslConfig.bootstrap, |
| 123 | desktopBootstrapSecret: "desktop-secret", |
| 124 | }, |
| 125 | }), |
| 126 | }, |
| 127 | ]), |
| 128 | ), |
| 129 | ), |
| 130 | ); |
| 131 | |
| 132 | it.effect("publishes a pending bootstrap only while a transient retry is scheduled", () => { |
| 133 | const retryingConfig: DesktopBackendManager.DesktopBackendStartConfig = { |
| 134 | ...readyWslConfig, |
| 135 | preflightFailure: Option.some({ |
| 136 | reason: "WSL probe timed out", |
| 137 | fatal: false, |
| 138 | retryLimit: 12, |
| 139 | }), |
| 140 | }; |
| 141 | const retryingInstance: DesktopBackendManager.DesktopBackendInstance = { |
| 142 | ...defaultWslInstance, |
| 143 | currentConfig: Effect.succeedSome(retryingConfig), |
| 144 | snapshot: Effect.succeed({ |
| 145 | desiredRunning: true, |
| 146 | ready: false, |
| 147 | activePid: Option.none(), |
| 148 | restartAttempt: 2, |
| 149 | restartScheduled: true, |
| 150 | }), |
| 151 | }; |
| 152 | |
| 153 | return Effect.gen(function* () { |
| 154 | const result = yield* getLocalEnvironmentBootstraps.handler(); |
| 155 | assert.deepEqual(result, [ |
| 156 | { |
| 157 | id: "wsl:default", |
| 158 | label: "WSL (default distro)", |
| 159 | runningDistro: null, |
| 160 | httpBaseUrl: null, |
| 161 | wsBaseUrl: null, |
| 162 | }, |
| 163 | ]); |
| 164 | }).pipe(Effect.provide(bootstrapsLayer([retryingInstance]))); |
| 165 | }); |
| 166 | |
| 167 | it.effect("omits a bounded transient bootstrap after retries stop", () => { |
| 168 | const stoppedInstance: DesktopBackendManager.DesktopBackendInstance = { |
| 169 | ...defaultWslInstance, |
| 170 | currentConfig: Effect.succeedSome({ |
| 171 | ...readyWslConfig, |
| 172 | preflightFailure: Option.some({ |
| 173 | reason: "WSL probe timed out", |
| 174 | fatal: false, |
| 175 | retryLimit: 12, |
| 176 | }), |
| 177 | }), |
| 178 | snapshot: Effect.succeed({ |
| 179 | desiredRunning: false, |
| 180 | ready: false, |
| 181 | activePid: Option.none(), |
| 182 | restartAttempt: 12, |
| 183 | restartScheduled: false, |
| 184 | }), |
| 185 | }; |
| 186 | |
| 187 | return Effect.gen(function* () { |
| 188 | const result = yield* getLocalEnvironmentBootstraps.handler(); |
| 189 | assert.deepEqual(result, []); |
| 190 | }).pipe(Effect.provide(bootstrapsLayer([stoppedInstance]))); |
| 191 | }); |
| 192 | }); |
| 193 | |
| 194 | describe("toLocalBackendPath", () => { |
| 195 | const { runningDistro: _, ...windowsConfig } = readyWslConfig; |
| 196 | it.effect("converts paths through wslpath only for backends running in WSL", () => |
| 197 | Effect.gen(function* () { |
| 198 | const convert = (backendId: string, path = "C:\\Users\\me\\project") => |
| 199 | toLocalBackendPath.handler({ backendId, path }); |
| 200 | assert.strictEqual(yield* convert("primary"), "C:\\Users\\me\\project"); |
| 201 | assert.strictEqual(yield* convert("wsl:default"), "/drives/c/Users/me/project"); |
| 202 | assert.strictEqual(yield* convert("wsl:missing"), null); |
| 203 | assert.strictEqual( |
| 204 | yield* convert("wsl:default", "\\\\wsl.localhost\\ubuntu\\home\\me\\repo"), |
| 205 | "/home/me/repo", |
| 206 | ); |
| 207 | assert.strictEqual(yield* convert("wsl:default", "\\\\wsl$\\Debian\\home\\me\\repo"), null); |
| 208 | assert.strictEqual( |
| 209 | yield* convert("primary", "\\\\wsl$\\Debian\\home\\me\\repo"), |
| 210 | "\\\\wsl$\\Debian\\home\\me\\repo", |
| 211 | ); |
| 212 | }).pipe( |
| 213 | Effect.provide( |
| 214 | Layer.mergeAll( |
| 215 | DesktopBackendPool.layerTest([ |
| 216 | { |
| 217 | ...defaultWslInstance, |
| 218 | id: DesktopBackendManager.BackendInstanceId("primary"), |
| 219 | currentConfig: Effect.succeedSome(windowsConfig), |
| 220 | }, |
| 221 | defaultWslInstance, |
| 222 | ]), |
| 223 | DesktopWslEnvironment.layerTest({ |
| 224 | windowsToWslPath: (distro, windowsPath) => |
| 225 | distro === "Ubuntu" && windowsPath === "C:\\Users\\me\\project" |
| 226 | ? Option.some("/drives/c/Users/me/project") |
| 227 | : Option.none(), |
| 228 | }), |
| 229 | ), |
| 230 | ), |
| 231 | ), |
| 232 | ); |
| 233 | }); |
| 234 | |
| 235 | describe("installRelayTelemetryEnabled", () => { |
| 236 | // The renderer reads this over sync IPC, so the answer must not wait on the filesystem. |
| 237 | const relayTelemetryEnabled = ( |
| 238 | env: NodeJS.ProcessEnv, |
| 239 | policy?: Parameters<typeof DesktopManagedPolicy.layerTest>[0], |
| 240 | loginShellEnv: NodeJS.ProcessEnv = {}, |
| 241 | ) => |
| 242 | Effect.gen(function* () { |
| 243 | const listeners = new Map<string, DesktopIpc.DesktopIpcSyncListener>(); |
| 244 | const ipcMain: DesktopIpc.DesktopIpcMain = { |
| 245 | removeHandler: () => undefined, |
| 246 | handle: () => undefined, |
| 247 | removeAllListeners: (channel) => void listeners.delete(channel), |
| 248 | on: (channel, listener) => void listeners.set(channel, listener), |
| 249 | }; |
| 250 | let discoveryFinished = false; |
| 251 | const ask = () => { |
| 252 | const event = { returnValue: undefined as unknown }; |
| 253 | listeners.get(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL)?.(event as never); |
| 254 | return event.returnValue; |
| 255 | }; |
| 256 | yield* installRelayTelemetryEnabled().pipe( |
| 257 | Effect.provideService(HostProcess.Environment, env), |
| 258 | Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { |
| 259 | installIntoProcess: Effect.succeed(true), |
| 260 | awaitDiscovery: Effect.succeed(true), |
| 261 | awaitUserShellDiscovery: Effect.succeed(true), |
| 262 | discoveryFinished: Effect.sync(() => discoveryFinished), |
| 263 | updates: Stream.empty, |
| 264 | }), |
| 265 | Effect.provide( |
| 266 | Layer.mergeAll(DesktopIpc.layerTest(ipcMain), DesktopManagedPolicy.layerTest(policy)), |
| 267 | ), |
| 268 | ); |
| 269 | const beforeDiscovery = ask(); |
| 270 | // The login shell's values land in the process env after startup has installed handlers. |
| 271 | Object.assign(env, loginShellEnv); |
| 272 | discoveryFinished = true; |
| 273 | return { beforeDiscovery, afterDiscovery: ask() }; |
| 274 | }).pipe(Effect.scoped); |
| 275 | |
| 276 | it.effect("reads the desktop host opt-out before returning the renderer policy", () => |
| 277 | Effect.gen(function* () { |
| 278 | assert.deepEqual(yield* relayTelemetryEnabled({ T3CODE_TELEMETRY_ENABLED: "false" }), { |
| 279 | beforeDiscovery: false, |
| 280 | afterDiscovery: false, |
| 281 | }); |
| 282 | // Undecided until the login shell is read, so the renderer asks again instead of opting out. |
| 283 | assert.deepEqual(yield* relayTelemetryEnabled({}), { |
| 284 | beforeDiscovery: null, |
| 285 | afterDiscovery: true, |
| 286 | }); |
| 287 | assert.deepEqual( |
| 288 | yield* relayTelemetryEnabled({}, undefined, { T3CODE_TELEMETRY_ENABLED: "false" }), |
| 289 | { beforeDiscovery: null, afterDiscovery: false }, |
| 290 | ); |
| 291 | }), |
| 292 | ); |
| 293 | |
| 294 | it.effect("turns relay tracing off when the managed policy turns telemetry off", () => |
| 295 | Effect.gen(function* () { |
| 296 | const policy = (limits: ManagedPolicyLimits) => ({ |
| 297 | schemaVersion: 1 as const, |
| 298 | organization: "Example Corp", |
| 299 | limits, |
| 300 | }); |
| 301 | const after = function* (...args: Parameters<typeof relayTelemetryEnabled>) { |
| 302 | return (yield* relayTelemetryEnabled(...args)).afterDiscovery; |
| 303 | }; |
| 304 | assert.isFalse(yield* after({}, policy({ telemetry: false }))); |
| 305 | assert.isTrue(yield* after({}, policy({ webhookTasks: false }))); |
| 306 | // A policy that cannot be read fails closed. |
| 307 | assert.isFalse( |
| 308 | yield* after({}, new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" })), |
| 309 | ); |
| 310 | }), |
| 311 | ); |
| 312 | }); |
| 313 | |
| 314 | describe("readMedia", () => { |
| 315 | it.effect("reads http(s) media only for the main window", () => |
| 316 | Effect.gen(function* () { |
| 317 | const mib = new Uint8Array(1024 * 1024); |
| 318 | const fetch = vi.fn(async (url: string) => { |
| 319 | if (url.endsWith("/missing.png")) return new Response("Not Found", { status: 404 }); |
| 320 | if (url.endsWith("/small.png")) return new Response(new Uint8Array([1, 2])); |
| 321 | let sent = 0; |
| 322 | // 257 MiB from one reused chunk: over the cap without allocating it. |
| 323 | const huge = new ReadableStream<Uint8Array>({ |
| 324 | pull: (controller) => (sent++ < 257 ? controller.enqueue(mib) : controller.close()), |
| 325 | }); |
| 326 | return new Response(huge); |
| 327 | }); |
| 328 | const main = { |
| 329 | webContents: { id: 1, session: { fetch } }, |
| 330 | } as unknown as Electron.BrowserWindow; |
| 331 | const read = (url: string, senderId: number) => |
| 332 | readMedia |
| 333 | .handler(url, { sender: { id: senderId } }) |
| 334 | .pipe( |
| 335 | Effect.provide( |
| 336 | Layer.mock(ElectronWindow.ElectronWindow)({ main: Effect.succeedSome(main) }), |
| 337 | ), |
| 338 | ); |
| 339 | |
| 340 | assert.strictEqual(yield* read("https://example.com/a.png", 2), null); |
| 341 | assert.strictEqual(yield* read("file:///etc/passwd", 1), null); |
| 342 | assert.strictEqual(fetch.mock.calls.length, 0); |
| 343 | assert.deepEqual(yield* read("https://example.com/small.png", 1), { |
| 344 | status: 200, |
| 345 | mimeType: "", |
| 346 | data: Buffer.from([1, 2]), |
| 347 | }); |
| 348 | assert.deepEqual(yield* read("https://example.com/missing.png", 1), { |
| 349 | status: 404, |
| 350 | mimeType: "text/plain;charset=UTF-8", |
| 351 | data: new Uint8Array(), |
| 352 | }); |
| 353 | assert.deepEqual(yield* read("https://example.com/huge.mp4", 1), { |
| 354 | status: 413, |
| 355 | mimeType: "", |
| 356 | data: new Uint8Array(), |
| 357 | }); |
| 358 | }), |
| 359 | ); |
| 360 | }); |
| 361 | |
| 362 | describe("pickProjectFavicon", () => { |
| 363 | const pickerLayer = ( |
| 364 | pickFiles: () => Effect.Effect<Array<string>>, |
| 365 | settings?: DesktopAppSettings.DesktopSettings, |
| 366 | ) => |
| 367 | Layer.mergeAll( |
| 368 | Layer.mock(ElectronDialog.ElectronDialog)({ pickFiles }), |
| 369 | Layer.mock(ElectronWindow.ElectronWindow)({ |
| 370 | focusedMainOrFirst: Effect.succeedNone, |
| 371 | }), |
| 372 | DesktopAppSettings.layerTest(settings), |
| 373 | ); |
| 374 | |
| 375 | it.effect("opens a single-image picker from the project directory", () => |
| 376 | Effect.gen(function* () { |
| 377 | const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"])); |
| 378 | const result = yield* pickProjectFavicon |
| 379 | .handler("/project") |
| 380 | .pipe(Effect.provide(pickerLayer(pickFiles))); |
| 381 | |
| 382 | assert.strictEqual(result, "/pictures/icon.png"); |
| 383 | assert.deepEqual(pickFiles.mock.calls, [ |
| 384 | [ |
| 385 | { |
| 386 | owner: Option.none(), |
| 387 | defaultPath: Option.some("/project"), |
| 388 | multiple: false, |
| 389 | filters: [ |
| 390 | { |
| 391 | name: "Images", |
| 392 | extensions: [ |
| 393 | "avif", |
| 394 | "bmp", |
| 395 | "gif", |
| 396 | "ico", |
| 397 | "heic", |
| 398 | "heif", |
| 399 | "jpeg", |
| 400 | "jpg", |
| 401 | "png", |
| 402 | "svg", |
| 403 | "tif", |
| 404 | "tiff", |
| 405 | "webp", |
| 406 | "icns", |
| 407 | ], |
| 408 | }, |
| 409 | ], |
| 410 | }, |
| 411 | ], |
| 412 | ]); |
| 413 | }), |
| 414 | ); |
| 415 | |
| 416 | it.effect("does not open a picker while the local environment is off", () => |
| 417 | Effect.gen(function* () { |
| 418 | const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"])); |
| 419 | const result = yield* pickProjectFavicon.handler("/project").pipe( |
| 420 | Effect.provide( |
| 421 | pickerLayer(pickFiles, { |
| 422 | ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, |
| 423 | localEnvironmentEnabled: false, |
| 424 | }), |
| 425 | ), |
| 426 | ); |
| 427 | |
| 428 | assert.strictEqual(result, null); |
| 429 | assert.strictEqual(pickFiles.mock.calls.length, 0); |
| 430 | }), |
| 431 | ); |
| 432 | }); |
| 433 | |
| 434 | describe("syncHtmlFullscreen", () => { |
| 435 | const fullscreenWindow = (fullscreen: boolean, { animatedExit = false } = {}) => { |
| 436 | let current = fullscreen; |
| 437 | let exiting = false; |
| 438 | const queued: boolean[] = []; |
| 439 | const leaveListeners: Array<() => void> = []; |
| 440 | const leave = () => { |
| 441 | current = false; |
| 442 | for (const listener of leaveListeners) listener(); |
| 443 | }; |
| 444 | // Like macOS, an animated exit keeps reporting fullscreen and queues requests until it ends. |
| 445 | const setFullScreen = vi.fn((next: boolean) => { |
| 446 | if (exiting) queued.push(next); |
| 447 | else if (next) current = true; |
| 448 | else if (!current) return; |
| 449 | else if (animatedExit) exiting = true; |
| 450 | else leave(); |
| 451 | }); |
| 452 | const finishExit = () => { |
| 453 | exiting = false; |
| 454 | leave(); |
| 455 | for (const next of queued.splice(0)) setFullScreen(next); |
| 456 | }; |
| 457 | const window = { |
| 458 | webContents: { id: 1 }, |
| 459 | isDestroyed: () => false, |
| 460 | isFullScreen: () => current, |
| 461 | setFullScreen, |
| 462 | on: (event: string, listener: () => void) => { |
| 463 | if (event === "leave-full-screen") leaveListeners.push(listener); |
| 464 | }, |
| 465 | } as unknown as Electron.BrowserWindow; |
| 466 | const layer = Layer.mock(ElectronWindow.ElectronWindow)({ main: Effect.succeedSome(window) }); |
| 467 | return { window, setFullScreen, finishExit, layer }; |
| 468 | }; |
| 469 | const fromMainRenderer = { sender: { id: 1 } }; |
| 470 | |
| 471 | it.effect("takes the screen for the app's own fullscreen element and gives it back", () => { |
| 472 | const { window, layer } = fullscreenWindow(false); |
| 473 | return Effect.gen(function* () { |
| 474 | yield* syncHtmlFullscreen.handler(true, fromMainRenderer); |
| 475 | assert.isTrue(window.isFullScreen()); |
| 476 | |
| 477 | yield* syncHtmlFullscreen.handler(false, fromMainRenderer); |
| 478 | assert.isFalse(window.isFullScreen()); |
| 479 | }).pipe(Effect.provide(layer)); |
| 480 | }); |
| 481 | |
| 482 | it.effect("keeps a window the user had already made fullscreen", () => { |
| 483 | const { window, setFullScreen, layer } = fullscreenWindow(true); |
| 484 | return Effect.gen(function* () { |
| 485 | yield* syncHtmlFullscreen.handler(true, fromMainRenderer); |
| 486 | yield* syncHtmlFullscreen.handler(false, fromMainRenderer); |
| 487 | |
| 488 | assert.isTrue(window.isFullScreen()); |
| 489 | assert.strictEqual(setFullScreen.mock.calls.length, 0); |
| 490 | }).pipe(Effect.provide(layer)); |
| 491 | }); |
| 492 | |
| 493 | it.effect("hands the window back once the user leaves OS fullscreen during playback", () => { |
| 494 | const { window, layer } = fullscreenWindow(false); |
| 495 | return Effect.gen(function* () { |
| 496 | yield* syncHtmlFullscreen.handler(true, fromMainRenderer); |
| 497 | window.setFullScreen(false); |
| 498 | window.setFullScreen(true); |
| 499 | yield* syncHtmlFullscreen.handler(false, fromMainRenderer); |
| 500 | |
| 501 | assert.isTrue(window.isFullScreen()); |
| 502 | }).pipe(Effect.provide(layer)); |
| 503 | }); |
| 504 | |
| 505 | it.effect("takes the screen again when the video returns during an animated exit", () => { |
| 506 | const { window, finishExit, layer } = fullscreenWindow(false, { animatedExit: true }); |
| 507 | return Effect.gen(function* () { |
| 508 | yield* syncHtmlFullscreen.handler(true, fromMainRenderer); |
| 509 | yield* syncHtmlFullscreen.handler(false, fromMainRenderer); |
| 510 | yield* syncHtmlFullscreen.handler(true, fromMainRenderer); |
| 511 | finishExit(); |
| 512 | assert.isTrue(window.isFullScreen()); |
| 513 | |
| 514 | yield* syncHtmlFullscreen.handler(false, fromMainRenderer); |
| 515 | finishExit(); |
| 516 | assert.isFalse(window.isFullScreen()); |
| 517 | }).pipe(Effect.provide(layer)); |
| 518 | }); |
| 519 | }); |
| 520 | |
| 521 | it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( |
| 522 | "finds remote editors installed without PATH launchers", |
| 523 | () => |
| 524 | Effect.gen(function* () { |
| 525 | const fs = yield* FileSystem.FileSystem; |
| 526 | const path = yield* Path.Path; |
| 527 | const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-remote-editors-" }); |
| 528 | for (const app of ["Cursor", "Visual Studio Code", "WebStorm"]) { |
| 529 | const executable = path.join( |
| 530 | home, |
| 531 | "Applications", |
| 532 | `${app}.app`, |
| 533 | app === "WebStorm" ? "Contents/MacOS/webstorm" : "Contents/Resources/app/bin/code", |
| 534 | ); |
| 535 | yield* fs.makeDirectory(path.dirname(executable), { recursive: true }); |
| 536 | yield* fs.writeFileString(executable, "#!/bin/sh\n"); |
| 537 | yield* fs.chmod(executable, 0o755); |
| 538 | } |
| 539 | const editors = yield* probeRemoteEditors.handler(undefined).pipe( |
| 540 | Effect.provideService(HostProcess.Environment, { |
| 541 | HOME: home, |
| 542 | PATH: path.join(home, "empty"), |
| 543 | }), |
| 544 | Effect.provideService(HostProcess.Platform, "darwin"), |
| 545 | ); |
| 546 | assert.include(editors, "cursor"); |
| 547 | assert.include(editors, "vscode"); |
| 548 | assert.include(editors, "webstorm"); |
| 549 | }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), |
| 550 | ); |
| 551 | |
| 552 | describe("probeRemoteEditors PATH scan", () => { |
| 553 | const platform = HostProcess.Platform.defaultValue(); |
| 554 | const launcherName = (command: string) => (platform === "win32" ? `${command}.cmd` : command); |
| 555 | |
| 556 | const makeFakePath = Effect.fnUntraced(function* () { |
| 557 | const fs = yield* FileSystem.FileSystem; |
| 558 | const path = yield* Path.Path; |
| 559 | const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-probe-path-" }); |
| 560 | const dirs = ["a", "b", "c", "d"].map((name) => path.join(root, name)); |
| 561 | for (const dir of dirs) yield* fs.makeDirectory(dir, { recursive: true }); |
| 562 | // Launchers in different PATH directories, deliberately not in REMOTE_CAPABLE_EDITOR_IDS order. |
| 563 | for (const [dir, command] of [ |
| 564 | [dirs[2]!, "webstorm"], |
| 565 | [dirs[0]!, "cursor"], |
| 566 | [dirs[3]!, "code"], |
| 567 | [dirs[1]!, "zeditor"], |
| 568 | ] as const) { |
| 569 | const file = path.join(dir, launcherName(command)); |
| 570 | yield* fs.writeFileString(file, "#!/bin/sh\n"); |
| 571 | if (platform !== "win32") yield* fs.chmod(file, 0o755); |
| 572 | } |
| 573 | return { |
| 574 | root, |
| 575 | env: { |
| 576 | HOME: root, |
| 577 | USERPROFILE: root, |
| 578 | PATH: dirs.join(platform === "win32" ? ";" : ":"), |
| 579 | PATHEXT: ".COM;.EXE;.BAT;.CMD", |
| 580 | }, |
| 581 | }; |
| 582 | }); |
| 583 | |
| 584 | const countingFileSystem = (counter: { stat: number; reads: Map<string, number> }) => |
| 585 | Layer.effect( |
| 586 | FileSystem.FileSystem, |
| 587 | Effect.gen(function* () { |
| 588 | const fs = yield* FileSystem.FileSystem; |
| 589 | return FileSystem.FileSystem.of({ |
| 590 | ...fs, |
| 591 | stat: (target) => { |
| 592 | counter.stat += 1; |
| 593 | return fs.stat(target); |
| 594 | }, |
| 595 | readDirectory: (target, options) => { |
| 596 | counter.reads.set(target, (counter.reads.get(target) ?? 0) + 1); |
| 597 | return fs.readDirectory(target, options); |
| 598 | }, |
| 599 | }); |
| 600 | }), |
| 601 | ).pipe(Layer.provideMerge(NodeServices.layer)); |
| 602 | |
| 603 | const serialReference = (env: Record<string, string>) => |
| 604 | Effect.gen(function* () { |
| 605 | const available: Array<string> = []; |
| 606 | for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) { |
| 607 | const editor = EDITORS.find((candidate) => candidate.id === editorId); |
| 608 | if (editor && Option.isSome(yield* resolveEditorCommand(editor, env))) { |
| 609 | available.push(editorId); |
| 610 | } |
| 611 | } |
| 612 | return available; |
| 613 | }); |
| 614 | |
| 615 | it.effect("reads each PATH directory once instead of stat-ing every candidate per editor", () => |
| 616 | Effect.gen(function* () { |
| 617 | const { env: baseEnv } = yield* makeFakePath(); |
| 618 | const delimiter = platform === "win32" ? ";" : ":"; |
| 619 | const uncachedCounter = { stat: 0, reads: new Map<string, number>() }; |
| 620 | const cachedCounter = { stat: 0, reads: new Map<string, number>() }; |
| 621 | const uncachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` }; |
| 622 | const cachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` }; |
| 623 | const uncached = yield* serialReference(uncachedEnv).pipe( |
| 624 | Effect.provide(countingFileSystem(uncachedCounter)), |
| 625 | ); |
| 626 | const cached = yield* probeRemoteEditors |
| 627 | .handler(undefined) |
| 628 | .pipe( |
| 629 | Effect.provideService(HostProcess.Environment, cachedEnv), |
| 630 | Effect.provideService(HostProcess.Platform, platform), |
| 631 | Effect.provide(countingFileSystem(cachedCounter)), |
| 632 | ); |
| 633 | // The host can add editors from app folders the fixture can't redirect (e.g. /Applications). |
| 634 | const fixtureEditors = ["cursor", "vscode", "zed", "webstorm"]; |
| 635 | assert.deepStrictEqual( |
| 636 | uncached.filter((id) => fixtureEditors.includes(id)), |
| 637 | fixtureEditors, |
| 638 | ); |
| 639 | assert.deepStrictEqual(cached, uncached); |
| 640 | assert.isAbove(uncachedCounter.stat, 0); |
| 641 | // On every platform the probe lists each PATH directory at most once. Only PATH entries count: |
| 642 | // resolveEditorCommand also reads app folders such as /Applications on macOS. |
| 643 | const pathReads = cachedEnv.PATH.split(delimiter) |
| 644 | .filter((entry) => entry.length > 0) |
| 645 | .map((entry) => cachedCounter.reads.get(entry) ?? 0); |
| 646 | assert.isAbove(Math.max(...pathReads), 0); |
| 647 | assert.isAtMost(Math.max(...pathReads), 1); |
| 648 | // Without the listings, Windows stats every PATH entry x PATHEXT candidate for each editor; |
| 649 | // elsewhere there is no PATHEXT, so the stat count is about the same either way. |
| 650 | if (platform === "win32") { |
| 651 | assert.isBelow(cachedCounter.stat, uncachedCounter.stat / 2); |
| 652 | } |
| 653 | }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), |
| 654 | ); |
| 655 | }); |