-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathentrypoints.go
More file actions
568 lines (529 loc) · 17.4 KB
/
Copy pathentrypoints.go
File metadata and controls
568 lines (529 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
package main
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
)
func entrypointPath(manager bool) string {
root := defaultInstallRoot()
name := silentName
if manager {
name = managerName
}
switch runtime.GOOS {
case "darwin":
return filepath.Join(root, name+".app")
case "windows":
return filepath.Join(root, name+".lnk")
default:
return filepath.Join(root, name+".desktop")
}
}
func (s *server) installEntrypoints() commandResult {
err := installEntrypoints()
if err != nil {
return installActionResult("failed", err.Error())
}
return installActionResult("ok", "入口已安装。")
}
func (s *server) uninstallEntrypoints(args map[string]any) commandResult {
options := mapArg(args, "options")
removeOwnedData := boolArg(options, "removeOwnedData")
err := uninstallEntrypoints()
if err == nil && removeOwnedData {
_ = os.RemoveAll(stateDir())
}
if err != nil {
return installActionResult("failed", err.Error())
}
return installActionResult("ok", "入口已卸载。")
}
func (s *server) uninstallCodexTools(args map[string]any) commandResult {
payload := codexToolsUninstallPayload()
if runtime.GOOS != "windows" {
return failed("ChatGPT Codex Tools 卸载功能仅支持 Windows 安装包。", payload)
}
options := mapArg(args, "options")
removeOwnedData := boolArg(options, "removeOwnedData")
removeWindowsWatcherInstall()
cleanupWindowsCodexToolsEntrypoints()
if removeOwnedData {
_ = os.RemoveAll(stateDir())
}
uninstaller := windowsCodexToolsUninstallerPath()
payload = codexToolsUninstallPayload()
if uninstaller == "" {
return ok("未找到 Windows 安装器卸载程序;已移除入口和 watcher。若使用便携版,请手动删除当前 ChatGPT Codex Tools 文件夹。", payload)
}
if err := startWindowsCodexToolsUninstaller(uninstaller); err != nil {
return failed("启动 Windows 卸载程序失败:"+err.Error(), payload)
}
return ok("已启动 Windows 卸载程序,请按提示完成卸载。", payload)
}
func installActionResult(status, message string) commandResult {
return commandResult{
"status": status,
"message": message,
"silent_shortcut": shortcutInstallState(entrypointPath(false)),
"management_shortcut": shortcutInstallState(entrypointPath(true)),
}
}
func shortcutInstallState(path string) map[string]any {
return map[string]any{"installed": fileExists(path), "path": path}
}
func installEntrypoints() error {
switch runtime.GOOS {
case "darwin":
if err := writeMacOSAppBundle(false); err != nil {
return err
}
if err := writeMacOSAppBundle(true); err != nil {
return err
}
cleanupLegacyEntrypoints()
return nil
case "windows":
if err := createWindowsShortcut(entrypointPath(false), companionBinaryPath(silentBinary+".exe"), "Launch ChatGPT Codex silently"); err != nil {
return err
}
if err := createWindowsShortcut(entrypointPath(true), companionBinaryPath(managerBinary+".exe"), "Open ChatGPT Codex management tool"); err != nil {
return err
}
cleanupLegacyEntrypoints()
return nil
default:
if err := writeDesktopEntry(false); err != nil {
return err
}
if err := writeDesktopEntry(true); err != nil {
return err
}
cleanupLegacyEntrypoints()
return nil
}
}
func uninstallEntrypoints() error {
var firstErr error
for _, path := range append([]string{entrypointPath(false), entrypointPath(true)}, legacyEntrypointPaths()...) {
if err := os.RemoveAll(path); err != nil && firstErr == nil && !errors.Is(err, os.ErrNotExist) {
firstErr = err
}
}
return firstErr
}
func cleanupLegacyEntrypoints() {
for _, path := range legacyEntrypointPaths() {
_ = os.RemoveAll(path)
}
}
func legacyEntrypointPaths() []string {
root := defaultInstallRoot()
switch runtime.GOOS {
case "darwin":
return []string{
filepath.Join(root, "Codex++.app"),
filepath.Join(root, "Codex++ 管理工具.app"),
filepath.Join(root, "CodexTools.app"),
}
case "windows":
return []string{
filepath.Join(root, "Codex++.lnk"),
filepath.Join(root, "Codex++ 管理工具.lnk"),
filepath.Join(root, "CodexTools.lnk"),
}
default:
return []string{
filepath.Join(root, "Codex++.desktop"),
filepath.Join(root, "Codex++ 管理工具.desktop"),
filepath.Join(root, "CodexTools.desktop"),
}
}
}
const (
windowsCodexToolsUninstallKey = `HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\ChatGPT Codex Tools`
legacyWindowsCodexToolsUninstallKey = `HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\CodexTools`
)
func codexToolsUninstallPayload() map[string]any {
uninstaller := windowsCodexToolsUninstallerPath()
return map[string]any{
"platform": runtime.GOOS,
"supported": runtime.GOOS == "windows",
"uninstallerPath": uninstaller,
"installerFound": uninstaller != "",
}
}
func cleanupWindowsCodexToolsEntrypoints() {
_ = uninstallEntrypoints()
if runtime.GOOS != "windows" {
return
}
if startMenu := windowsCodexToolsStartMenuDir(); startMenu != "" {
_ = os.RemoveAll(startMenu)
}
if legacyStartMenu := legacyWindowsCodexToolsStartMenuDir(); legacyStartMenu != "" {
_ = os.RemoveAll(legacyStartMenu)
}
}
func removeWindowsWatcherInstall() {
if runtime.GOOS != "windows" {
return
}
_ = windowsRegDeleteCurrentUserValue(watcherRunKey, watcherRunName)
if shortcut := watcherStartupShortcutPath(); shortcut != "" {
_ = os.Remove(shortcut)
}
}
func windowsCodexToolsStartMenuDir() string {
appdata := os.Getenv("APPDATA")
if appdata == "" {
return ""
}
return filepath.Join(appdata, "Microsoft", "Windows", "Start Menu", "Programs", "ChatGPT Codex Tools")
}
func legacyWindowsCodexToolsStartMenuDir() string {
appdata := os.Getenv("APPDATA")
if appdata == "" {
return ""
}
return filepath.Join(appdata, "Microsoft", "Windows", "Start Menu", "Programs", "CodexTools")
}
func windowsCodexToolsUninstallerPath() string {
if runtime.GOOS != "windows" {
return ""
}
var candidates []string
add := func(path string) {
path = strings.TrimSpace(path)
if path != "" {
candidates = append(candidates, path)
}
}
if executable, err := os.Executable(); err == nil {
add(filepath.Join(filepath.Dir(executable), "Uninstall.exe"))
}
if localAppData := os.Getenv("LOCALAPPDATA"); localAppData != "" {
add(filepath.Join(localAppData, "ChatGPT Codex Tools", "Uninstall.exe"))
add(filepath.Join(localAppData, "CodexTools", "Uninstall.exe"))
}
for _, key := range []string{windowsCodexToolsUninstallKey, legacyWindowsCodexToolsUninstallKey} {
if installLocation := windowsRegistryString(key, "InstallLocation"); installLocation != "" {
add(filepath.Join(strings.Trim(installLocation, `"`), "Uninstall.exe"))
}
if uninstallString := windowsRegistryString(key, "UninstallString"); uninstallString != "" {
add(windowsExecutableFromCommand(uninstallString))
}
}
for _, candidate := range candidates {
if fileExists(candidate) {
return candidate
}
}
return ""
}
func windowsRegistryString(key, name string) string {
if runtime.GOOS != "windows" {
return ""
}
cmd := exec.Command("reg", "query", key, "/v", name)
hideSubprocessWindow(cmd)
output, err := cmd.Output()
if err != nil {
return ""
}
return parseWindowsRegQueryValue(string(output), name)
}
func parseWindowsRegQueryValue(output, name string) string {
for _, line := range strings.Split(output, "\n") {
trimmed := strings.TrimSpace(line)
if !strings.HasPrefix(strings.ToLower(trimmed), strings.ToLower(name)) {
continue
}
parts := strings.SplitN(trimmed, "REG_SZ", 2)
if len(parts) != 2 {
continue
}
return strings.TrimSpace(parts[1])
}
return ""
}
func windowsExecutableFromCommand(command string) string {
trimmed := strings.TrimSpace(command)
if trimmed == "" {
return ""
}
if strings.HasPrefix(trimmed, `"`) {
end := strings.Index(trimmed[1:], `"`)
if end >= 0 {
return trimmed[1 : end+1]
}
}
fields := strings.Fields(trimmed)
if len(fields) == 0 {
return ""
}
return fields[0]
}
func startWindowsCodexToolsUninstaller(path string) error {
if runtime.GOOS != "windows" {
return errors.New("ChatGPT Codex Tools 卸载程序只支持 Windows")
}
cmd := exec.Command(path)
cmd.Dir = filepath.Dir(path)
return cmd.Start()
}
func writeMacOSAppBundle(manager bool) error {
appPath := entrypointPath(manager)
contents := filepath.Join(appPath, "Contents")
macos := filepath.Join(contents, "MacOS")
resources := filepath.Join(contents, "Resources")
if err := os.MkdirAll(macos, 0o755); err != nil {
return err
}
if err := os.MkdirAll(resources, 0o755); err != nil {
return err
}
displayName := silentName
executableName := "ChatGPTCodex"
binary := silentBinary
identifierSuffix := ""
if manager {
displayName = managerName
executableName = "ChatGPTCodexManager"
binary = managerBinary
identifierSuffix = ".manager"
}
plist := macOSInfoPlist(displayName, executableName, identifierSuffix)
if err := os.WriteFile(filepath.Join(contents, "Info.plist"), []byte(plist), 0o644); err != nil {
return err
}
target := companionBinaryPath(binary)
script := fmt.Sprintf("#!/bin/sh\nexport PATH=\"${PATH:-%s}:%s\"\nexec %q\n", defaultGUIPath, defaultGUIPath, target)
executable := filepath.Join(macos, executableName)
if err := os.WriteFile(executable, []byte(script), 0o755); err != nil {
return err
}
_ = copyFirstExistingFile([]string{
filepath.Join(filepath.Dir(target), "codex-plus-plus.icns"),
filepath.Join(filepath.Dir(target), "codex-plus-plus.png"),
}, resources)
return nil
}
func macOSInfoPlist(displayName, executableName, identifierSuffix string) string {
return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key>
<string>%s</string>
<key>CFBundleDisplayName</key>
<string>%s</string>
<key>CFBundleIdentifier</key>
<string>com.hereww.chatgptcodextools%s</string>
<key>CFBundleVersion</key>
<string>%s</string>
<key>CFBundleShortVersionString</key>
<string>%s</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleExecutable</key>
<string>%s</string>
<key>CFBundleIconFile</key>
<string>codex-plus-plus</string>
<key>LSUIElement</key>
<true/>
<key>LSMinimumSystemVersion</key>
<string>12.0</string>
</dict>
</plist>`, displayName, displayName, identifierSuffix, version, version, executableName)
}
func copyFirstExistingFile(candidates []string, resources string) error {
for _, candidate := range candidates {
data, err := os.ReadFile(candidate)
if err != nil {
continue
}
return os.WriteFile(filepath.Join(resources, filepath.Base(candidate)), data, 0o644)
}
return nil
}
func createWindowsShortcut(shortcutPath, target, description string) error {
if runtime.GOOS != "windows" {
return errors.New("Windows shortcuts are only supported on Windows")
}
if err := os.MkdirAll(filepath.Dir(shortcutPath), 0o755); err != nil {
return err
}
script := fmt.Sprintf(`$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut(%s)
$shortcut.TargetPath = %s
$shortcut.WorkingDirectory = %s
$shortcut.Description = %s
$shortcut.IconLocation = %s
$shortcut.Save()
`, psQuote(shortcutPath), psQuote(target), psQuote(filepath.Dir(target)), psQuote(description), psQuote(target))
cmd := exec.Command("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script)
hideSubprocessWindow(cmd)
return cmd.Run()
}
func createWindowsShortcutWithArgs(shortcutPath, target, arguments, description string) error {
if runtime.GOOS != "windows" {
return errors.New("Windows shortcuts are only supported on Windows")
}
if err := os.MkdirAll(filepath.Dir(shortcutPath), 0o755); err != nil {
return err
}
script := fmt.Sprintf(`$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut(%s)
$shortcut.TargetPath = %s
$shortcut.Arguments = %s
$shortcut.WorkingDirectory = %s
$shortcut.Description = %s
$shortcut.IconLocation = %s
$shortcut.WindowStyle = 7
$shortcut.Save()
`, psQuote(shortcutPath), psQuote(target), psQuote(arguments), psQuote(filepath.Dir(target)), psQuote(description), psQuote(target))
cmd := exec.Command("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script)
hideSubprocessWindow(cmd)
return cmd.Run()
}
func windowsRegAddCurrentUserString(key, name, value string) error {
if runtime.GOOS != "windows" {
return errors.New("Windows registry is only supported on Windows")
}
cmd := exec.Command("reg", "add", key, "/v", name, "/t", "REG_SZ", "/d", value, "/f")
hideSubprocessWindow(cmd)
return cmd.Run()
}
func windowsRegDeleteCurrentUserValue(key, name string) error {
if runtime.GOOS != "windows" {
return errors.New("Windows registry is only supported on Windows")
}
cmd := exec.Command("reg", "delete", key, "/v", name, "/f")
hideSubprocessWindow(cmd)
return cmd.Run()
}
func psQuote(value string) string {
return "'" + strings.ReplaceAll(value, "'", "''") + "'"
}
func writeDesktopEntry(manager bool) error {
path := entrypointPath(manager)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
name := silentName
binary := silentBinary
if manager {
name = managerName
binary = managerBinary
}
desktop := fmt.Sprintf("[Desktop Entry]\nType=Application\nName=%s\nExec=%s\nTerminal=false\n", name, companionBinaryPath(binary))
return os.WriteFile(path, []byte(desktop), 0o755)
}
func watcherPayload() map[string]any {
flag := filepath.Join(stateDir(), "watcher.disabled")
install := watcherInstallState()
runValueInstalled := false
if runtime.GOOS == "windows" {
runValueInstalled = strings.TrimSpace(windowsRegistryString(watcherRunKey, watcherRunName)) != ""
}
return map[string]any{
"enabled": !fileExists(flag),
"disabled_flag": flag,
"platform": runtime.GOOS,
"install_supported": runtime.GOOS == "windows",
"run_value_name": watcherRunName,
"run_value": install.RunValue,
"run_value_installed": runValueInstalled,
"startup_shortcut": install.ShortcutPath,
"startup_shortcut_installed": install.ShortcutPath != "" && fileExists(install.ShortcutPath),
"launcher_path": install.LauncherPath,
"launcher_arguments": install.Arguments,
}
}
func watcherInstallState() watcherInstallPlan {
launcher := companionBinaryPath(silentBinary)
if runtime.GOOS == "windows" {
launcher += ".exe"
}
return buildWatcherInstallPlan(launcher, defaultWatcherDebugPort, watcherStartupShortcutPath())
}
func buildWatcherInstallPlan(launcherPath string, debugPort int, shortcutPath string) watcherInstallPlan {
arguments := fmt.Sprintf("--debug-port %d", debugPort)
return watcherInstallPlan{
LauncherPath: launcherPath,
Arguments: arguments,
RunValue: fmt.Sprintf("\"%s\" %s", strings.ReplaceAll(launcherPath, `"`, `\"`), arguments),
ShortcutPath: shortcutPath,
}
}
func watcherStartupShortcutPath() string {
appdata := os.Getenv("APPDATA")
if appdata == "" {
return ""
}
return filepath.Join(appdata, "Microsoft", "Windows", "Start Menu", "Programs", "Startup", watcherStartupLinkName)
}
func (s *server) installWatcher() commandResult {
payload := watcherPayload()
if runtime.GOOS != "windows" {
return failed("watcher 安装仅支持 Windows;macOS 只能手动从 ChatGPT Codex 入口启动并用启用/禁用控制本地标志。", payload)
}
install := watcherInstallState()
if !fileExists(install.LauncherPath) {
return failed("安装 watcher 失败:未找到静默启动器 "+install.LauncherPath, watcherPayload())
}
if err := windowsRegAddCurrentUserString(watcherRunKey, watcherRunName, install.RunValue); err != nil {
return failed("安装 watcher 失败:"+err.Error(), watcherPayload())
}
if install.ShortcutPath != "" {
_ = os.Remove(install.ShortcutPath)
}
spawnWatcherLauncher(install.LauncherPath, defaultWatcherDebugPort)
return ok("watcher 已安装。", watcherPayload())
}
func (s *server) uninstallWatcher() commandResult {
if runtime.GOOS != "windows" {
return ok("watcher 安装仅支持 Windows;当前平台没有需要移除的自动启动项。", watcherPayload())
}
if err := windowsRegDeleteCurrentUserValue(watcherRunKey, watcherRunName); err != nil {
// reg delete returns an error when the value does not exist; removal should remain idempotent.
_ = err
}
if shortcut := watcherStartupShortcutPath(); shortcut != "" {
_ = os.Remove(shortcut)
}
return ok("watcher 已移除。", watcherPayload())
}
func spawnWatcherLauncher(launcherPath string, debugPort int) {
if runtime.GOOS != "windows" {
return
}
cmd := exec.Command(launcherPath, "--debug-port", strconv.Itoa(debugPort))
cmd.Stdin = nil
cmd.Stdout = io.Discard
cmd.Stderr = io.Discard
hideSubprocessWindow(cmd)
_ = cmd.Start()
}
func (s *server) setWatcherDisabled(disabled bool) commandResult {
flag := filepath.Join(stateDir(), "watcher.disabled")
if disabled {
if err := os.MkdirAll(filepath.Dir(flag), 0o755); err != nil {
return failed("禁用 watcher 失败:"+err.Error(), watcherPayload())
}
if err := os.WriteFile(flag, []byte("disabled"), 0o644); err != nil {
return failed("禁用 watcher 失败:"+err.Error(), watcherPayload())
}
return ok("watcher 已禁用。", watcherPayload())
}
if err := os.Remove(flag); err != nil && !errors.Is(err, os.ErrNotExist) {
return failed("启用 watcher 失败:"+err.Error(), watcherPayload())
}
return ok("watcher 已启用。", watcherPayload())
}