-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathapp.go
More file actions
3779 lines (3497 loc) · 113 KB
/
Copy pathapp.go
File metadata and controls
3779 lines (3497 loc) · 113 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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package main wires the per-user Go services into Wails bindings the
// renderer can call as `window.go.main.App.*`. The shape of this object
// mirrors the existing TypeScript DesktopAPI so the renderer migration in
// Phase 3b is a mechanical IPC-call rewrite rather than an API reshape.
//
// Style: each binding method delegates to one of the internal packages and
// returns errors verbatim; Wails surfaces them to the renderer as rejected
// promises. The mutex on App protects only the lazy-initialised handles
// (bridge / login) and the cached settings shape.
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"time"
"github.com/google/uuid"
wailsruntime "github.com/wailsapp/wails/v2/pkg/runtime"
"officedex/internal/appupdate"
"officedex/internal/binresolver"
"officedex/internal/bridge"
"officedex/internal/diagnostics"
"officedex/internal/extrender"
"officedex/internal/localstore"
"officedex/internal/login"
"officedex/internal/mask"
"officedex/internal/netproxy"
"officedex/internal/preview"
"officedex/internal/report"
runtimemgr "officedex/internal/runtime"
"officedex/internal/settings"
"officedex/internal/subprocess"
"officedex/internal/types"
)
const (
appName = "OfficeDex"
previewExtraWidth = 500
bridgeEventChannel = "bridge:event"
authEventChannel = "auth:event"
previewEventChannel = "preview:open"
appUpdateChannel = "appupdate:event"
runtimeEventChannel = "runtime:event"
defaultUpdateManifestURL = "https://raw.githubusercontent.com/officecli/officedex-dist/main/manifest.json"
)
// appVersion is injected at build time via `-ldflags "-X main.appVersion=<v>"`.
// The default "dev" sentinel makes `go run` / `wails dev` work without flags.
var appVersion = "dev"
type DesktopNotificationInput struct {
Title string `json:"title"`
Body string `json:"body"`
}
type desktopNotificationRuntime interface {
IsNotificationAvailable(context.Context) bool
CheckNotificationAuthorization(context.Context) (bool, error)
RequestNotificationAuthorization(context.Context) (bool, error)
SendNotification(context.Context, wailsruntime.NotificationOptions) error
}
type wailsDesktopNotificationRuntime struct{}
func (wailsDesktopNotificationRuntime) IsNotificationAvailable(ctx context.Context) bool {
return wailsruntime.IsNotificationAvailable(ctx)
}
func (wailsDesktopNotificationRuntime) CheckNotificationAuthorization(ctx context.Context) (bool, error) {
return wailsruntime.CheckNotificationAuthorization(ctx)
}
func (wailsDesktopNotificationRuntime) RequestNotificationAuthorization(ctx context.Context) (bool, error) {
return wailsruntime.RequestNotificationAuthorization(ctx)
}
func (wailsDesktopNotificationRuntime) SendNotification(ctx context.Context, options wailsruntime.NotificationOptions) error {
return wailsruntime.SendNotification(ctx, options)
}
// App is the Wails-bound object surfaced to the renderer.
type App struct {
ctx context.Context
userDataDir string
workspaceDir string
settingsStore *settings.Store
localStore *localstore.Store
previewReg *preview.Registry
mu sync.Mutex
cachedSettings types.UserSettings
bridgeClient *bridge.Client
bridgeCwd string
loginManager *login.Manager
loginUnsub func()
pendingLoginURL string
previewModeWidthBefore int
previewModeXBefore int
previewModeXShifted bool
appUpdateMgr *appupdate.Manager
runtimeMgr *runtimemgr.Manager
proxyPool *netproxy.Pool
extRenderer *extrender.Renderer
// resolver cache. binresolver.Resolve stats the filesystem on every call;
// runCommandOptions / ensureBridge run on every RPC. We cache the resolved
// path + env until UpdateSettings flips touchesBridge=true.
resolvedBinaryPath string
resolvedBinaryEnv []string
binaryResolvedAt time.Time
notificationMu sync.Mutex
notificationAuthorizationGranted bool
}
// NewApp resolves user-scoped paths and constructs the per-user services
// that do not depend on a Wails context. Context-dependent setup (bridge
// listeners that emit events) waits for OnStartup.
func NewApp() (*App, error) {
userDataDir, err := resolveUserDataDir(appName)
if err != nil {
return nil, fmt.Errorf("resolve user data dir: %w", err)
}
if err := os.MkdirAll(userDataDir, 0o755); err != nil {
return nil, fmt.Errorf("mkdir user data dir: %w", err)
}
workspaceDir := filepath.Join(userDataDir, "workspace")
if err := os.MkdirAll(workspaceDir, 0o755); err != nil {
return nil, fmt.Errorf("mkdir workspace: %w", err)
}
settingsStore := settings.New(filepath.Join(userDataDir, "settings.json"), nil)
cached, err := settingsStore.Load()
if err != nil {
return nil, fmt.Errorf("load settings: %w", err)
}
previewReg, err := preview.New(preview.RegistryOptions{
TrustedRoots: previewTrustedRoots(workspaceDir, cached),
})
if err != nil {
return nil, fmt.Errorf("preview registry: %w", err)
}
localStore := localstore.New(filepath.Join(userDataDir, "officedex.sqlite"))
proxyPool := netproxy.NewPool()
if cached.Proxy != nil && cached.Proxy.Enabled && cached.Proxy.URL != "" {
// Settings sanitize on Load already drops any URL that fails
// netproxy.ValidateURL, so Set cannot return an error for cached
// settings; the explicit discard documents that invariant.
_ = proxyPool.Set(cached.Proxy.URL)
}
bridge.SetProxyEnvSupplier(proxyPool.SubprocessEnv)
login.SetProxyEnvSupplier(proxyPool.SubprocessEnv)
app := &App{
userDataDir: userDataDir,
workspaceDir: workspaceDir,
settingsStore: settingsStore,
localStore: localStore,
previewReg: previewReg,
cachedSettings: cached,
proxyPool: proxyPool,
}
manifestURL := os.Getenv("OFFICEDEX_UPDATE_MANIFEST_URL")
if strings.TrimSpace(manifestURL) == "" {
manifestURL = defaultUpdateManifestURL
}
updateMgr, err := appupdate.New(appupdate.Options{
ManifestURL: manifestURL,
CurrentVersion: appVersion,
UpdatesDir: filepath.Join(userDataDir, "updates"),
HTTPClient: proxyPool.NewClient(0),
Listener: func(ev appupdate.Event) {
emit(app.ctx, appUpdateChannel, ev)
},
})
if err != nil {
return nil, fmt.Errorf("appupdate manager: %w", err)
}
app.appUpdateMgr = updateMgr
runtimeInstallRoot := filepath.Join(userDataDir, "runtime")
rtMgr, err := runtimemgr.New(runtimemgr.ManagerOptions{
InstallRoot: runtimeInstallRoot,
Repo: "officecli/officecli-dist",
HTTPClient: proxyPool.NewClient(0),
Listener: func(ev types.RuntimeEvent) {
emit(app.ctx, runtimeEventChannel, ev)
},
})
if err != nil {
return nil, fmt.Errorf("runtime manager: %w", err)
}
_ = rtMgr.LoadFromDisk()
app.runtimeMgr = rtMgr
return app, nil
}
// startup is called by Wails after the renderer is ready. The context is
// retained so binding methods can dispatch events and open OS dialogs.
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
if err := wailsruntime.InitializeNotifications(ctx); err != nil {
wailsruntime.LogWarningf(ctx, "init notifications: %v", err)
}
if err := a.localStore.Open(ctx); err != nil {
wailsruntime.LogErrorf(ctx, "open local store: %v", err)
} else if err := a.initializeWorkspaces(ctx); err != nil {
wailsruntime.LogErrorf(ctx, "init workspace: %v", err)
}
if binPath := a.resolveExtrenderBinary(); binPath != "" {
a.extRenderer = extrender.New(binPath)
wailsruntime.LogInfof(ctx, "extrender: %s", binPath)
}
}
// shutdown is called by Wails when the window is about to close. It stops
// long-running children so we don't leak processes.
func (a *App) shutdown(ctx context.Context) {
a.mu.Lock()
bridgeClient := a.bridgeClient
a.bridgeClient = nil
loginUnsub := a.loginUnsub
a.loginUnsub = nil
a.mu.Unlock()
if bridgeClient != nil {
bridgeClient.Stop()
}
if loginUnsub != nil {
loginUnsub()
}
if a.localStore != nil {
_ = a.localStore.Close()
}
if a.runtimeMgr != nil {
a.runtimeMgr.CancelDownload()
}
if ctx != nil {
wailsruntime.CleanupNotifications(ctx)
}
}
// ─── Bridge bindings ────────────────────────────────────────────────────────
// Initialize starts the agent-bridge if needed and forwards the initialize
// JSON-RPC call.
func (a *App) Initialize() ([]byte, error) {
client, err := a.ensureBridge()
if err != nil {
return nil, err
}
return client.Initialize(a.ctx)
}
// GetCapabilities returns the agent capability map.
func (a *App) GetCapabilities() ([]byte, error) {
client, err := a.ensureBridge()
if err != nil {
return nil, err
}
return client.GetCapabilities(a.ctx)
}
func (a *App) SendDesktopNotification(input DesktopNotificationInput) error {
return a.sendDesktopNotificationWithRuntime(wailsDesktopNotificationRuntime{}, input)
}
func (a *App) sendDesktopNotificationWithRuntime(notificationRuntime desktopNotificationRuntime, input DesktopNotificationInput) error {
ctx := a.ctx
if ctx == nil {
return errors.New("desktop notification runtime is unavailable")
}
title := strings.TrimSpace(input.Title)
if title == "" {
title = appName
}
body := strings.TrimSpace(input.Body)
if !notificationRuntime.IsNotificationAvailable(ctx) {
return errors.New("desktop notifications are unavailable on this platform")
}
if err := a.ensureDesktopNotificationAuthorization(ctx, notificationRuntime); err != nil {
return err
}
return notificationRuntime.SendNotification(ctx, wailsruntime.NotificationOptions{
ID: fmt.Sprintf("officedex-%d", time.Now().UnixNano()),
Title: title,
Body: body,
})
}
func (a *App) ensureDesktopNotificationAuthorization(ctx context.Context, notificationRuntime desktopNotificationRuntime) error {
a.notificationMu.Lock()
defer a.notificationMu.Unlock()
if a.notificationAuthorizationGranted {
return nil
}
authorized, err := notificationRuntime.CheckNotificationAuthorization(ctx)
if err != nil {
return fmt.Errorf("check notification authorization: %w", err)
}
if !authorized {
authorized, err = notificationRuntime.RequestNotificationAuthorization(ctx)
if err != nil {
return fmt.Errorf("request notification authorization: %w", err)
}
if !authorized {
return errors.New("desktop notification permission denied")
}
}
a.notificationAuthorizationGranted = true
return nil
}
// ListImageTemplates returns server-managed image prompt templates exposed by
// officecli agent-bridge.
func (a *App) ListImageTemplates() ([]types.ImagePromptTemplate, error) {
client, err := a.ensureBridge()
if err != nil {
return nil, err
}
return client.ListImageTemplates(a.ctx)
}
func (a *App) CreateImageTemplate(input types.CreateUserImageTemplateInput) (types.ImagePromptTemplate, error) {
client, err := a.ensureBridge()
if err != nil {
return types.ImagePromptTemplate{}, err
}
item, err := client.CreateImageTemplate(a.ctx, input)
if err != nil {
return types.ImagePromptTemplate{}, err
}
return *item, nil
}
func (a *App) CreateImageTemplatePublishRequest(input types.CreateImageTemplatePublishRequestInput) (types.ImageTemplatePublishRequest, error) {
client, err := a.ensureBridge()
if err != nil {
return types.ImageTemplatePublishRequest{}, err
}
item, err := client.CreateImageTemplatePublishRequest(a.ctx, input)
if err != nil {
return types.ImageTemplatePublishRequest{}, err
}
return *item, nil
}
// GenerateResult is the renderer-facing shape of a task invocation result.
type GenerateResult struct {
TaskID string `json:"taskId"`
SessionID string `json:"sessionId"`
Status string `json:"status"`
}
// Generate dispatches `office.generate` against the agent bridge after
// applying settings-driven defaults (output dir, runtime mode).
func (a *App) Generate(input types.GenerateInput) (GenerateResult, error) {
settings, err := a.settingsStore.Load()
if err != nil {
return GenerateResult{}, fmt.Errorf("load settings: %w", err)
}
input = normalizeGenerateInputText(input)
if input.DocumentType == types.DocIMG {
var watermark *types.ImageWatermarkGenerateOptions
settings, watermark = a.refreshImageWatermarkSettingsForGenerate(settings)
input.ImageWatermark = watermark
}
if err := validateCustomProvider(settings); err != nil {
return GenerateResult{}, err
}
if err := a.requireLoggedInForCustomProvider(settings); err != nil {
return GenerateResult{}, err
}
resolved, err := a.resolveGenerateInput(input, settings)
if err != nil {
return GenerateResult{}, err
}
targetCwd, err := a.effectiveWorkspaceDirForInput(input.WorkspaceID, input.NoProject, settings)
if err != nil {
return GenerateResult{}, err
}
client, err := a.ensureBridgeForCwd(targetCwd)
if err != nil {
return GenerateResult{}, err
}
result, err := client.InvokeGenerate(a.ctx, resolved)
if err != nil {
return GenerateResult{}, err
}
if a.localStore != nil && result.TaskID != "" {
if err := a.recordTaskWorkspaceContext(result.TaskID, resolved.WorkspaceID, resolved.ConversationID, resolved.ParentTaskID, resolved.Topic, resolved.NoProject); err != nil {
return GenerateResult{}, err
}
_ = a.localStore.RecordEvent(types.BridgeEvent{
TaskID: result.TaskID,
Type: "task.user_input",
Payload: generateInputEventPayload(resolved, localstore.TaskContext{
WorkspaceID: resolved.WorkspaceID,
ConversationID: resolved.ConversationID,
ParentTaskID: resolved.ParentTaskID,
}),
})
}
return GenerateResult{TaskID: result.TaskID, SessionID: result.SessionID, Status: result.Status}, nil
}
// Modify dispatches `office.modify` ("继续修改") against the agent bridge: an
// LLM-driven in-place edit of an existing pptx/docx/xlsx artifact. The modified
// file is written next to the source (officecli derives the output directory
// from the source path when OutputDir is empty, but we resolve it explicitly so
// the result lands within a preview-trusted root).
func (a *App) Modify(input types.ModifyInput) (GenerateResult, error) {
settings, err := a.settingsStore.Load()
if err != nil {
return GenerateResult{}, fmt.Errorf("load settings: %w", err)
}
if err := validateCustomProvider(settings); err != nil {
return GenerateResult{}, err
}
if err := a.requireLoggedInForCustomProvider(settings); err != nil {
return GenerateResult{}, err
}
if strings.TrimSpace(input.SourceFile) == "" {
return GenerateResult{}, errors.New("modify: source file is required")
}
if strings.TrimSpace(input.Prompt) == "" {
return GenerateResult{}, errors.New("modify: prompt is required")
}
resolved := input
if strings.TrimSpace(resolved.OutputDir) == "" {
resolved.OutputDir = filepath.Dir(input.SourceFile)
}
targetCwd, err := a.effectiveWorkspaceDirForInput(input.WorkspaceID, input.NoProject, settings)
if err != nil {
return GenerateResult{}, err
}
client, err := a.ensureBridgeForCwd(targetCwd)
if err != nil {
return GenerateResult{}, err
}
result, err := client.InvokeModify(a.ctx, resolved)
if err != nil {
return GenerateResult{}, err
}
if a.localStore != nil && result.TaskID != "" {
if err := a.recordTaskWorkspaceContext(result.TaskID, resolved.WorkspaceID, resolved.ConversationID, resolved.ParentTaskID, resolved.Prompt, resolved.NoProject); err != nil {
return GenerateResult{}, err
}
_ = a.localStore.RecordEvent(types.BridgeEvent{
TaskID: result.TaskID,
Type: "task.user_input",
Payload: map[string]any{
"prompt": resolved.Prompt,
"source_file": resolved.SourceFile,
},
})
}
return GenerateResult{TaskID: result.TaskID, SessionID: result.SessionID, Status: result.Status}, nil
}
// RespondInput is the renderer payload for the respond binding.
type RespondInput struct {
TaskID string `json:"taskId"`
QuestionID string `json:"questionId,omitempty"`
OptionID string `json:"optionId,omitempty"`
Answer string `json:"answer,omitempty"`
Answers []RespondAnswerInput `json:"answers,omitempty"`
}
type RespondAnswerInput struct {
QuestionGroupID string `json:"questionGroupId,omitempty"`
QuestionID string `json:"questionId"`
OptionID string `json:"optionId,omitempty"`
Answer string `json:"answer"`
QuestionIndex int `json:"questionIndex,omitempty"`
}
// Respond forwards a user answer back to the running task.
func (a *App) Respond(input RespondInput) ([]byte, error) {
if err := a.recordRespondAnswers(input); err != nil {
return nil, err
}
client, err := a.ensureBridgeForTask(input.TaskID)
if err != nil {
return nil, err
}
answers := make([]bridge.RespondAnswer, 0, len(input.Answers))
for _, answer := range input.Answers {
answers = append(answers, bridge.RespondAnswer{
QuestionID: answer.QuestionID,
OptionID: answer.OptionID,
Answer: answer.Answer,
})
}
raw, err := client.RespondTask(a.ctx, bridge.RespondParams{
TaskID: input.TaskID,
QuestionID: input.QuestionID,
OptionID: input.OptionID,
Answer: input.Answer,
Answers: answers,
})
if err != nil && isBridgeTaskNotFoundError(err) {
return a.recoverStaleInteractiveRespond(input, err)
}
return raw, err
}
func (a *App) recordRespondAnswers(input RespondInput) error {
if a.localStore == nil || strings.TrimSpace(input.TaskID) == "" {
return nil
}
answers := make([]localstore.TaskAnswer, 0, len(input.Answers)+1)
if len(input.Answers) > 0 {
for _, item := range input.Answers {
if strings.TrimSpace(item.QuestionID) == "" {
continue
}
groupID := strings.TrimSpace(item.QuestionGroupID)
if groupID == "" {
groupID = strings.TrimSpace(input.QuestionID)
}
answers = append(answers, localstore.TaskAnswer{
QuestionGroupID: groupID,
QuestionID: strings.TrimSpace(item.QuestionID),
OptionID: strings.TrimSpace(item.OptionID),
Answer: strings.TrimSpace(item.Answer),
QuestionIndex: item.QuestionIndex,
})
}
} else if strings.TrimSpace(input.QuestionID) != "" && (strings.TrimSpace(input.OptionID) != "" || strings.TrimSpace(input.Answer) != "") {
answers = append(answers, localstore.TaskAnswer{
QuestionID: strings.TrimSpace(input.QuestionID),
OptionID: strings.TrimSpace(input.OptionID),
Answer: strings.TrimSpace(input.Answer),
QuestionIndex: -1,
})
}
if len(answers) == 0 {
return nil
}
ctx := a.ctx
if ctx == nil {
ctx = context.Background()
}
return a.localStore.RecordTaskAnswers(ctx, strings.TrimSpace(input.TaskID), answers)
}
func (a *App) recoverStaleInteractiveRespond(input RespondInput, originalErr error) ([]byte, error) {
if a.localStore == nil {
return nil, originalErr
}
ctx := a.ctx
if ctx == nil {
ctx = context.Background()
}
events, err := a.localStore.QueryEventsByTask(ctx, input.TaskID)
if err != nil {
return nil, err
}
if !latestTaskStateRecoverable(events) {
return nil, fmt.Errorf("task was interrupted and cannot be resumed; please restart this plan")
}
taskCtx, ok, err := a.localStore.TaskContext(ctx, input.TaskID)
if err != nil {
return nil, err
}
if !ok {
return nil, fmt.Errorf("task was interrupted and cannot be resumed; missing task context")
}
generateInput, err := recoverGenerateInputFromEvents(events, taskCtx)
if err != nil {
return nil, err
}
client, err := a.ensureBridgeForTask(input.TaskID)
if err != nil {
return nil, err
}
result, err := client.InvokeGenerate(ctx, generateInput)
if err != nil {
return nil, err
}
if result.TaskID == "" {
return nil, fmt.Errorf("task recovery failed: replacement task id is empty")
}
if err := a.recordTaskWorkspaceContext(result.TaskID, taskCtx.WorkspaceID, taskCtx.ConversationID, input.TaskID, generateInput.Topic, generateInput.NoProject); err != nil {
return nil, err
}
recoveredInputEvent := types.BridgeEvent{
EventID: "local-recovered-input-" + uuid.NewString(),
TaskID: result.TaskID,
Type: "task.user_input",
TS: time.Now().UTC().Format(time.RFC3339Nano),
Payload: generateInputEventPayload(generateInput, taskCtx),
}
_ = a.localStore.RecordEvent(recoveredInputEvent)
if canEmitWailsEvent(ctx) {
emit(ctx, bridgeEventChannel, recoveredInputEvent)
}
if err := waitForRecoverablePendingInput(ctx, client, result.TaskID); err != nil {
return nil, err
}
answers, err := a.localStore.QueryTaskAnswers(ctx, input.TaskID)
if err != nil {
return nil, err
}
params := bridge.RespondParams{TaskID: result.TaskID, QuestionID: input.QuestionID}
if len(answers) > 0 {
params.OptionID = input.OptionID
params.Answer = input.Answer
params.Answers = make([]bridge.RespondAnswer, 0, len(answers))
for _, item := range answers {
params.Answers = append(params.Answers, bridge.RespondAnswer{
QuestionID: item.QuestionID,
OptionID: item.OptionID,
Answer: item.Answer,
})
if params.QuestionID == "" && item.QuestionGroupID != "" {
params.QuestionID = item.QuestionGroupID
}
}
} else {
params.OptionID = input.OptionID
params.Answer = input.Answer
}
if len(params.Answers) == 0 && strings.TrimSpace(params.OptionID) == "" && strings.TrimSpace(params.Answer) == "" {
return nil, fmt.Errorf("task was interrupted and cannot be resumed; missing saved answers")
}
if _, err := client.RespondTask(ctx, params); err != nil {
return nil, err
}
a.recordLocalTaskCancelled(input.TaskID, "Task was recovered after the application restarted")
payload, err := json.Marshal(map[string]any{
"accepted": true,
"task_id": result.TaskID,
"taskId": result.TaskID,
"recoveredFrom": input.TaskID,
})
if err != nil {
return nil, err
}
return payload, nil
}
func latestTaskStateRecoverable(events []types.BridgeEvent) bool {
state := ""
for _, event := range events {
switch event.Type {
case "task.question", "task.plan", "task.completed", "task.failed", "task.cancelled":
state = event.Type
}
}
return state == "task.question" || state == "task.plan"
}
func recoverGenerateInputFromEvents(events []types.BridgeEvent, taskCtx localstore.TaskContext) (types.GenerateInput, error) {
var userInput map[string]any
var started map[string]any
for _, event := range events {
if event.Type == "task.started" {
started = event.Payload
}
if event.Type == "task.user_input" {
userInput = event.Payload
}
}
if userInput == nil {
return types.GenerateInput{}, fmt.Errorf("task was interrupted and cannot be resumed; missing original input")
}
documentType := stringField(userInput, "document_type", "documentType")
if documentType == "" {
documentType = stringField(started, "document_type", "documentType")
}
prompt := recoverPromptFromPayload(userInput)
if prompt == "" {
prompt = stringField(started, "prompt")
}
topic := recoverTopicFromPayload(userInput)
if topic == "" {
topic = stringField(started, "topic")
}
if topic == "" {
topic = prompt
}
if prompt == "" {
prompt = topic
}
if documentType == "" || prompt == "" {
return types.GenerateInput{}, fmt.Errorf("task was interrupted and cannot be resumed; missing original prompt")
}
input := types.GenerateInput{
DocumentType: types.DocumentType(documentType),
Topic: topic,
Prompt: prompt,
WorkspaceID: taskCtx.WorkspaceID,
NoProject: strings.TrimSpace(taskCtx.WorkspaceID) == "",
ConversationID: taskCtx.ConversationID,
ParentTaskID: taskCtx.ParentTaskID,
RuntimeMode: stringField(userInput, "runtime_mode", "runtimeMode"),
GenerationMode: stringField(userInput, "generation_mode", "generationMode"),
PromptTemplateID: stringField(userInput, "prompt_template_id", "promptTemplateId"),
SourceFile: stringField(userInput, "source_file", "sourceFile"),
ReferenceImages: stringSliceField(userInput, "reference_images", "referenceImages"),
ImageRatio: stringField(userInput, "image_ratio", "imageRatio"),
FPS: intField(userInput, "fps"),
OutputDir: stringField(userInput, "output_dir", "outputDir"),
Publish: boolField(userInput, "publish"),
ImageQuality: stringField(userInput, "image_quality", "imageQuality"),
LocalPreview: boolField(userInput, "local_preview", "localPreview"),
}
if v, ok := optionalBoolField(userInput, "enable_images", "enableImages"); ok {
input.EnableImages = &v
}
return input, nil
}
func waitForRecoverablePendingInput(ctx context.Context, client *bridge.Client, taskID string) error {
waitCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()
for {
status, err := client.TaskStatus(waitCtx, taskID)
if err != nil {
return err
}
if len(status.CurrentQuestion) > 0 || len(status.CurrentPlan) > 0 {
return nil
}
if status.Status == "failed" || status.Status == "completed" || status.Status == "cancelled" {
return fmt.Errorf("task recovery failed before input was requested: %s", status.Status)
}
select {
case <-waitCtx.Done():
return fmt.Errorf("task recovery timed out waiting for pending input")
case <-ticker.C:
}
}
}
// Cancel asks the bridge to cancel a running task.
func (a *App) Cancel(taskID string) ([]byte, error) {
client, err := a.ensureBridgeForTask(taskID)
if err != nil {
return nil, err
}
raw, err := client.CancelTask(a.ctx, taskID)
if err != nil {
if isBridgeTaskNotFoundError(err) {
a.recordLocalTaskCancelled(taskID, "Task was already gone when cancellation was requested")
}
return raw, err
}
a.recordLocalTaskCancelled(taskID, "Task cancelled by user")
return raw, nil
}
func (a *App) recordLocalTaskCancelled(taskID, message string) {
if a.localStore == nil || strings.TrimSpace(taskID) == "" {
return
}
if strings.TrimSpace(message) == "" {
message = "Task cancelled"
}
_ = a.localStore.RecordEvent(types.BridgeEvent{
EventID: "local-cancel-" + uuid.NewString(),
TaskID: strings.TrimSpace(taskID),
Type: "task.cancelled",
TS: time.Now().UTC().Format(time.RFC3339Nano),
Payload: map[string]any{"message": message},
})
}
func isBridgeTaskNotFoundError(err error) bool {
if err == nil {
return false
}
message := strings.ToLower(err.Error())
return strings.Contains(message, "not found") || strings.Contains(message, "not_found")
}
// ─── Shell / dialog bindings ────────────────────────────────────────────────
// OpenPath opens filePath with the OS default handler.
func (a *App) OpenPath(filePath string) error {
return openOSPath(filePath)
}
// ShowItemInFolder reveals filePath in the platform file manager.
func (a *App) ShowItemInFolder(filePath string) error {
return revealOSPath(filePath)
}
// OpenExternal opens an http(s) URL in the user's default browser.
func (a *App) OpenExternal(url string) error {
if a.ctx == nil {
return errors.New("app: not started")
}
wailsruntime.BrowserOpenURL(a.ctx, url)
return nil
}
// FileDialogFilter matches the renderer-facing filter shape.
type FileDialogFilter struct {
Name string `json:"name"`
Extensions []string `json:"extensions"`
}
// FileDialogOptions matches the renderer-facing dialog options.
type FileDialogOptions struct {
Filters []FileDialogFilter `json:"filters,omitempty"`
}
// OpenFileDialog shows a single-file picker. Returns "" when the user
// cancels.
func (a *App) OpenFileDialog(options *FileDialogOptions) (string, error) {
if a.ctx == nil {
return "", errors.New("app: not started")
}
return wailsruntime.OpenFileDialog(a.ctx, wailsruntime.OpenDialogOptions{
Filters: dialogFilters(options),
})
}
// OpenDirectoryDialog shows a folder picker. Returns "" when the user cancels.
func (a *App) OpenDirectoryDialog() (string, error) {
if a.ctx == nil {
return "", errors.New("app: not started")
}
return wailsruntime.OpenDirectoryDialog(a.ctx, wailsruntime.OpenDialogOptions{})
}
// OpenMultiFileDialog shows a multi-file picker. Returns an empty slice when
// the user cancels.
func (a *App) OpenMultiFileDialog(options *FileDialogOptions) ([]string, error) {
if a.ctx == nil {
return nil, errors.New("app: not started")
}
return wailsruntime.OpenMultipleFilesDialog(a.ctx, wailsruntime.OpenDialogOptions{
Filters: dialogFilters(options),
})
}
// PastedImageInput is the renderer-facing payload for SavePastedImage.
// DataBase64 is the standard base64-encoded image bytes (no data: URL
// prefix), and Ext is the file extension without a leading dot. Unsupported
// extensions normalise to "png".
type PastedImageInput struct {
DataBase64 string `json:"dataBase64"`
Ext string `json:"ext"`
}
// SavePastedImage persists clipboard image bytes inside the workspace and
// returns the absolute file path so the renderer can append it to the
// reference-images list.
func (a *App) SavePastedImage(input PastedImageInput) (string, error) {
if input.DataBase64 == "" {
return "", errors.New("save pasted image: empty data")
}
data, err := base64.StdEncoding.DecodeString(input.DataBase64)
if err != nil {
return "", fmt.Errorf("decode pasted image: %w", err)
}
if len(data) == 0 {
return "", errors.New("save pasted image: empty data")
}
ext := normalizePastedImageExt(input.Ext)
settings, err := a.settingsStore.Load()
if err != nil {
return "", fmt.Errorf("load settings: %w", err)
}
workspaceDir, err := a.effectiveWorkspaceDir(settings)
if err != nil {
return "", err
}
dir := filepath.Join(workspaceDir, ".pasted-images")
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", fmt.Errorf("mkdir pasted-images dir: %w", err)
}
name := fmt.Sprintf("paste-%d.%s", time.Now().UnixNano(), ext)
dest := filepath.Join(dir, name)
if err := os.WriteFile(dest, data, 0o644); err != nil {
return "", fmt.Errorf("write pasted image: %w", err)
}
return dest, nil
}
func normalizePastedImageExt(ext string) string {
cleaned := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(ext), "."))
switch cleaned {
case "png", "jpg", "jpeg", "gif", "webp", "bmp", "svg":
return cleaned
default:
return "png"
}
}
// SetPreviewMode resizes the main window to make room for the preview pane,
// or restores the pre-preview width when active is false. The widened window
// is clamped to the current screen width, and if the right edge would overflow
// the screen the window is shifted left to keep it fully visible.
func (a *App) SetPreviewMode(active bool) error {
if a.ctx == nil {
return errors.New("app: not started")
}
w, h := wailsruntime.WindowGetSize(a.ctx)
a.mu.Lock()
defer a.mu.Unlock()
if active {
if a.previewModeWidthBefore > 0 {
return nil
}
a.previewModeWidthBefore = w
targetW := w + previewExtraWidth
screenW := a.currentScreenWidthLocked()
if screenW > 0 && targetW > screenW {
targetW = screenW
}
x, y := wailsruntime.WindowGetPosition(a.ctx)
if screenW > 0 && x+targetW > screenW {
newX := screenW - targetW
if newX < 0 {
newX = 0
}
a.previewModeXBefore = x
a.previewModeXShifted = true
wailsruntime.WindowSetPosition(a.ctx, newX, y)
}
wailsruntime.WindowSetSize(a.ctx, targetW, h)
return nil
}
if a.previewModeWidthBefore > 0 {
wailsruntime.WindowSetSize(a.ctx, a.previewModeWidthBefore, h)
a.previewModeWidthBefore = 0
if a.previewModeXShifted {
_, y := wailsruntime.WindowGetPosition(a.ctx)
wailsruntime.WindowSetPosition(a.ctx, a.previewModeXBefore, y)
a.previewModeXShifted = false
a.previewModeXBefore = 0
}
}
return nil
}
// currentScreenWidthLocked returns the logical width of the screen currently
// hosting the window, falling back to the primary screen, or 0 when unknown.
// Caller must hold a.mu (the function does not touch shared state, but the
// name documents the calling context).
func (a *App) currentScreenWidthLocked() int {
screens, err := wailsruntime.ScreenGetAll(a.ctx)
if err != nil {
return 0
}
for _, s := range screens {
if s.IsCurrent {
return s.Size.Width
}
}
for _, s := range screens {
if s.IsPrimary {
return s.Size.Width
}
}
return 0
}
// ─── Preview bindings ───────────────────────────────────────────────────────
// PreviewArtifact registers an artifact for preview and emits an event so the
// renderer can open it. Phase 3a uses the main-window preview pane instead of
// a separate window (Wails v2 multi-window is non-trivial); a follow-up phase
// can introduce a real second window if needed.