-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathcontroller.ts
More file actions
1546 lines (1352 loc) · 55.8 KB
/
controller.ts
File metadata and controls
1546 lines (1352 loc) · 55.8 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
/**
* CLI Controller
*
* All runtime state and orchestration of the sync lifecycle.
* Helpers should provide data and never hold control.
*/
import type { CliToPluginMessage, PluginToCliMessage } from "@code-link/shared"
import { normalizeCodeFilePathWithExtension, pluralize, shortProjectHash } from "@code-link/shared"
import fs from "fs/promises"
import path from "path"
import type { WebSocket } from "ws"
import { CERT_DIR, getOrCreateCerts } from "./helpers/certs.ts"
import { initConnection, sendMessage } from "./helpers/connection.ts"
import {
autoResolveConflicts,
deleteLocalFile,
detectConflicts,
filterEchoedFiles,
listFiles,
readFileSafe,
writeRemoteFiles,
} from "./helpers/files.ts"
import { tryGitInit } from "./helpers/git.ts"
import { Installer } from "./helpers/installer.ts"
import { PluginUserPromptCoordinator } from "./helpers/plugin-prompts.ts"
import { validateIncomingChange } from "./helpers/sync-validator.ts"
import { initWatcher } from "./helpers/watcher.ts"
import type { Config, Conflict, ConflictVersionData, FileInfo, WatcherEvent } from "./types.ts"
import { FileMetadataCache, type FileSyncMetadata } from "./utils/file-metadata-cache.ts"
import { createHashTracker } from "./utils/hash-tracker.ts"
import {
cancelDisconnectMessage,
debug,
didShowDisconnect,
error,
fileDelete,
fileDown,
fileUp,
info,
resetDisconnectState,
scheduleDisconnectMessage,
status,
success,
warn,
wasRecentlyDisconnected,
} from "./utils/logging.ts"
import { findOrCreateProjectDirectory } from "./utils/project.ts"
import { hashFileContent } from "./utils/state-persistence.ts"
/**
* Explicit sync lifecycle modes
*/
export type SyncMode = "disconnected" | "handshaking" | "snapshot_processing" | "conflict_resolution" | "watching"
/**
* Shared state that persists across all lifecycle modes
*/
interface SyncStateBase {
pendingRemoteChanges: FileInfo[]
}
type DisconnectedState = SyncStateBase & {
mode: "disconnected"
socket: null
}
type HandshakingState = SyncStateBase & {
mode: "handshaking"
socket: WebSocket
}
type SnapshotProcessingState = SyncStateBase & {
mode: "snapshot_processing"
socket: WebSocket
}
type ConflictResolutionState = SyncStateBase & {
mode: "conflict_resolution"
socket: WebSocket
pendingConflicts: Conflict[]
}
type WatchingState = SyncStateBase & {
mode: "watching"
socket: WebSocket
}
export type SyncState =
| DisconnectedState
| HandshakingState
| SnapshotProcessingState
| ConflictResolutionState
| WatchingState
/**
* Events that drive state transitions
*/
type SyncEvent =
| {
type: "HANDSHAKE"
socket: WebSocket
projectInfo: { projectId: string; projectName: string }
}
| { type: "REQUEST_FILES" }
| { type: "REMOTE_FILE_LIST"; files: FileInfo[] }
| {
type: "CONFLICTS_DETECTED"
conflicts: Conflict[]
safeWrites: FileInfo[]
localOnly: FileInfo[]
}
| { type: "REMOTE_FILE_CHANGE"; file: FileInfo; fileMeta?: FileSyncMetadata }
| { type: "REMOTE_FILE_DELETE"; fileName: string }
| { type: "LOCAL_DELETE_APPROVED"; fileName: string }
| { type: "LOCAL_DELETE_REJECTED"; fileName: string; content: string }
| {
type: "CONFLICTS_RESOLVED"
resolution: "local" | "remote"
}
| {
type: "FILE_SYNCED_CONFIRMATION"
fileName: string
remoteModifiedAt: number
}
| { type: "DISCONNECT" }
| { type: "WATCHER_EVENT"; event: WatcherEvent }
| {
type: "CONFLICT_VERSION_RESPONSE"
versions: ConflictVersionData[]
}
/**
* Side effects emitted by transitions
*/
type Effect =
| {
type: "INIT_WORKSPACE"
projectInfo: { projectId: string; projectName: string }
}
| { type: "LOAD_PERSISTED_STATE" }
| { type: "SEND_MESSAGE"; payload: CliToPluginMessage }
| { type: "LIST_LOCAL_FILES" }
| { type: "DETECT_CONFLICTS"; remoteFiles: FileInfo[] }
| {
type: "WRITE_FILES"
files: FileInfo[]
silent?: boolean
skipEcho?: boolean
}
| { type: "DELETE_LOCAL_FILES"; names: string[] }
| { type: "REQUEST_CONFLICT_DECISIONS"; conflicts: Conflict[] }
| { type: "REQUEST_CONFLICT_VERSIONS"; conflicts: Conflict[] }
| {
type: "UPDATE_FILE_METADATA"
fileName: string
remoteModifiedAt: number
}
| {
type: "SEND_LOCAL_CHANGE"
fileName: string
content: string
}
| {
type: "LOCAL_INITIATED_FILE_DELETE"
fileNames: string[]
}
| {
type: "SEND_FILE_RENAME"
oldFileName: string
newFileName: string
content: string
}
| { type: "UPDATE_CONFLICT_DATA"; conflicts: Conflict[] }
| { type: "PERSIST_STATE" }
| {
type: "SYNC_COMPLETE"
totalCount: number
updatedCount: number
unchangedCount: number
}
| {
type: "LOG"
level: "info" | "debug" | "warn" | "success"
message: string
}
interface PendingRenameConfirmation {
oldFileName: string
content: string
}
/** Log helper */
function log(level: "info" | "debug" | "warn" | "success", message: string): Effect {
return { type: "LOG", level, message }
}
/**
* After updating a conflict's content, filter out any conflicts where both sides now match.
* If no conflicts remain, transition to watching mode. Otherwise emit updated conflict data.
*/
function applyConflictUpdate(
state: ConflictResolutionState,
updatedConflicts: Conflict[],
effects: Effect[]
): { state: SyncState; effects: Effect[] } {
const remaining = updatedConflicts.filter(c => c.localContent !== c.remoteContent)
if (remaining.length === 0) {
// All conflicts resolved — transition to watching
effects.push(
log("debug", "All conflicts auto-resolved (content converged)"),
{ type: "PERSIST_STATE" },
{
type: "SYNC_COMPLETE",
totalCount: updatedConflicts.length,
updatedCount: updatedConflicts.length,
unchangedCount: 0,
}
)
const { pendingConflicts: _discarded, ...rest } = state
return {
state: { ...rest, mode: "watching", pendingRemoteChanges: [] },
effects,
}
}
effects.push({ type: "UPDATE_CONFLICT_DATA", conflicts: remaining })
return { state: { ...state, pendingConflicts: remaining }, effects }
}
/**
* Pure state transition function
* Takes current state + event, returns new state + effects to execute
*/
function transition(state: SyncState, event: SyncEvent): { state: SyncState; effects: Effect[] } {
const effects: Effect[] = []
switch (event.type) {
case "HANDSHAKE": {
if (state.mode !== "disconnected") {
effects.push(log("warn", `Received HANDSHAKE in mode ${state.mode}, ignoring`))
return { state, effects }
}
effects.push(
{ type: "INIT_WORKSPACE", projectInfo: event.projectInfo },
{ type: "LOAD_PERSISTED_STATE" },
{ type: "SEND_MESSAGE", payload: { type: "request-files" } }
)
return {
state: {
...state,
mode: "handshaking",
socket: event.socket,
},
effects,
}
}
case "FILE_SYNCED_CONFIRMATION": {
// Remote confirms they received our local change
effects.push(log("debug", `Remote confirmed sync: ${event.fileName}`), {
type: "UPDATE_FILE_METADATA",
fileName: event.fileName,
remoteModifiedAt: event.remoteModifiedAt,
})
return { state, effects }
}
case "DISCONNECT": {
effects.push({ type: "PERSIST_STATE" }, log("debug", "Disconnected, persisting state"))
if (state.mode === "conflict_resolution") {
const { pendingConflicts: _discarded, ...rest } = state
return {
state: {
...rest,
mode: "disconnected",
socket: null,
},
effects,
}
}
return {
state: {
...state,
mode: "disconnected",
socket: null,
},
effects,
}
}
case "REQUEST_FILES": {
// Plugin is asking for our local file list
// Valid in any mode except disconnected
if (state.mode === "disconnected") {
effects.push(log("warn", "Received REQUEST_FILES while disconnected, ignoring"))
return { state, effects }
}
effects.push(log("debug", "Plugin requested file list"), {
type: "LIST_LOCAL_FILES",
})
return { state, effects }
}
case "REMOTE_FILE_LIST": {
if (state.mode !== "handshaking") {
effects.push(log("warn", `Received REMOTE_FILE_LIST in mode ${state.mode}, ignoring`))
return { state, effects }
}
effects.push(log("debug", `Received file list: ${pluralize(event.files.length, "file")}`))
// During initial file list, detect conflicts between remote snapshot and local files
effects.push({
type: "DETECT_CONFLICTS",
remoteFiles: event.files,
})
// Transition to snapshot_processing - conflict detection effect will determine next mode
return {
state: {
...state,
mode: "snapshot_processing",
pendingRemoteChanges: event.files,
},
effects,
}
}
case "CONFLICTS_DETECTED": {
if (state.mode !== "snapshot_processing") {
effects.push(log("warn", `Received CONFLICTS_DETECTED in mode ${state.mode}, ignoring`))
return { state, effects }
}
const { conflicts, safeWrites, localOnly } = event
// detectConflicts returns:
// - safeWrites = files we can apply (remote-only or local unchanged)
// - conflicts = files that need manual resolution (content or deletion conflicts)
// - localOnly = files to upload
// (unchanged files have metadata recorded in DETECT_CONFLICTS executor)
// Apply safe writes
if (safeWrites.length > 0) {
effects.push(log("debug", `Applying ${safeWrites.length} safe writes`))
if (wasRecentlyDisconnected()) {
effects.push(log("success", `Applied ${pluralize(safeWrites.length, "file")} during sync`))
}
effects.push({
type: "WRITE_FILES",
files: safeWrites,
silent: true,
})
}
// Upload local-only files
if (localOnly.length > 0) {
effects.push(log("debug", `Uploading ${pluralize(localOnly.length, "local-only file")}`))
for (const file of localOnly) {
effects.push({
type: "SEND_MESSAGE",
payload: {
type: "file-change",
fileName: file.name,
content: file.content,
},
})
}
}
// If conflicts remain, request remote version data before surfacing to user
if (conflicts.length > 0) {
effects.push(log("debug", `${pluralize(conflicts.length, "conflict")} require version check`), {
type: "REQUEST_CONFLICT_VERSIONS",
conflicts,
})
return {
state: {
...state,
mode: "conflict_resolution",
pendingConflicts: conflicts,
},
effects,
}
}
// No conflicts - transition to watching
const remoteTotal = state.pendingRemoteChanges.length
const totalCount = remoteTotal + localOnly.length
const updatedCount = safeWrites.length + localOnly.length
const unchangedCount = Math.max(0, remoteTotal - safeWrites.length)
effects.push(
{ type: "PERSIST_STATE" },
{
type: "SYNC_COMPLETE",
totalCount,
updatedCount,
unchangedCount,
}
)
return {
state: {
...state,
mode: "watching",
pendingRemoteChanges: [],
},
effects,
}
}
case "REMOTE_FILE_CHANGE": {
// Use helper to validate the incoming change
const validation = validateIncomingChange(event.fileMeta, state.mode)
if (validation.action === "queue") {
if (state.mode === "conflict_resolution") {
const conflictIndex = state.pendingConflicts.findIndex(c => c.fileName === event.file.name)
if (conflictIndex >= 0) {
// Update conflict with latest remote content
const updatedConflicts = [...state.pendingConflicts]
updatedConflicts[conflictIndex] = {
...updatedConflicts[conflictIndex],
remoteContent: event.file.content,
remoteModifiedAt: event.file.modifiedAt,
}
effects.push(log("debug", `Updated conflict with latest remote content: ${event.file.name}`))
return applyConflictUpdate(state, updatedConflicts, effects)
}
// Non-conflicted file during conflict resolution: fall through to apply
} else {
// Changes during initial sync are ignored - the snapshot handles reconciliation
effects.push(log("debug", `Ignoring file change during sync: ${event.file.name}`))
return { state, effects }
}
}
if (validation.action === "reject") {
effects.push(log("warn", `Rejected file change: ${event.file.name} (${validation.reason})`))
return { state, effects }
}
// Apply the change
effects.push(log("debug", `Applying remote change: ${event.file.name}`), {
type: "WRITE_FILES",
files: [event.file],
skipEcho: true,
})
return { state, effects }
}
case "REMOTE_FILE_DELETE": {
// Reject if not connected
if (state.mode === "disconnected") {
effects.push(log("warn", `Rejected delete while disconnected: ${event.fileName}`))
return { state, effects }
}
// During conflict resolution, update conflict data instead of deleting
if (state.mode === "conflict_resolution") {
const conflictIndex = state.pendingConflicts.findIndex(c => c.fileName === event.fileName)
if (conflictIndex >= 0) {
const updatedConflicts = [...state.pendingConflicts]
updatedConflicts[conflictIndex] = { ...updatedConflicts[conflictIndex], remoteContent: null }
effects.push(log("debug", `Updated conflict with remote delete: ${event.fileName}`))
return applyConflictUpdate(state, updatedConflicts, effects)
}
}
// Remote deletes applied immediately
// (the file is already gone from Framer)
effects.push(
log("debug", `Remote delete applied: ${event.fileName}`),
{ type: "DELETE_LOCAL_FILES", names: [event.fileName] },
{ type: "PERSIST_STATE" }
)
return { state, effects }
}
case "LOCAL_DELETE_APPROVED": {
// User confirmed the delete - apply it
effects.push(
log("debug", `Delete confirmed: ${event.fileName}`),
{ type: "DELETE_LOCAL_FILES", names: [event.fileName] },
{ type: "PERSIST_STATE" }
)
return { state, effects }
}
case "LOCAL_DELETE_REJECTED": {
// User cancelled - restore the file
effects.push(log("debug", `Delete cancelled: ${event.fileName}`))
effects.push({
type: "WRITE_FILES",
files: [
{
name: event.fileName,
content: event.content,
modifiedAt: Date.now(),
},
],
})
return { state, effects }
}
case "CONFLICTS_RESOLVED": {
// Only valid in conflict_resolution mode
if (state.mode !== "conflict_resolution") {
effects.push(log("warn", `Received CONFLICTS_RESOLVED in mode ${state.mode}, ignoring`))
return { state, effects }
}
// User picked one resolution for ALL conflicts
if (event.resolution === "remote") {
// Apply all remote versions (or delete locally if remote is null)
for (const conflict of state.pendingConflicts) {
if (conflict.remoteContent === null) {
// Remote deleted this file - delete locally
effects.push({
type: "DELETE_LOCAL_FILES",
names: [conflict.fileName],
})
} else {
effects.push({
type: "WRITE_FILES",
files: [
{
name: conflict.fileName,
content: conflict.remoteContent,
modifiedAt: conflict.remoteModifiedAt,
},
],
silent: true,
})
}
}
effects.push(log("success", "Keeping Framer changes"))
} else {
// Send all local versions (or request delete confirmation if local is null)
const localDeletes: string[] = []
for (const conflict of state.pendingConflicts) {
if (conflict.localContent === null) {
localDeletes.push(conflict.fileName)
} else {
effects.push({
type: "SEND_MESSAGE",
payload: {
type: "file-change",
fileName: conflict.fileName,
content: conflict.localContent,
},
})
}
}
// Batch local deletes into single confirmation prompt
if (localDeletes.length > 0) {
effects.push({
type: "LOCAL_INITIATED_FILE_DELETE",
fileNames: localDeletes,
})
}
effects.push(log("success", "Keeping local changes"))
}
// All conflicts resolved - transition to watching
effects.push(
{ type: "PERSIST_STATE" },
{
type: "SYNC_COMPLETE",
totalCount: state.pendingConflicts.length,
updatedCount: state.pendingConflicts.length,
unchangedCount: 0,
}
)
const { pendingConflicts: _discarded, ...rest } = state
return {
state: {
...rest,
mode: "watching",
},
effects,
}
}
case "WATCHER_EVENT": {
// Local file system change detected
const { kind, relativePath, content } = event.event
// Only process changes in watching or conflict_resolution mode
if (state.mode !== "watching") {
if (state.mode === "conflict_resolution") {
const conflictIndex = state.pendingConflicts.findIndex(c => c.fileName === relativePath)
if (conflictIndex >= 0) {
if ((kind === "add" || kind === "change") && content !== undefined) {
// Update conflict with latest local content
const updatedConflicts = [...state.pendingConflicts]
updatedConflicts[conflictIndex] = { ...updatedConflicts[conflictIndex], localContent: content }
effects.push(log("debug", `Updated conflict with latest local content: ${relativePath}`))
return applyConflictUpdate(state, updatedConflicts, effects)
}
if (kind === "delete") {
// Local deleted a conflicted file
const updatedConflicts = [...state.pendingConflicts]
updatedConflicts[conflictIndex] = { ...updatedConflicts[conflictIndex], localContent: null }
effects.push(log("debug", `Updated conflict with local delete: ${relativePath}`))
return applyConflictUpdate(state, updatedConflicts, effects)
}
if (kind === "rename") {
// Renaming a conflicted file during resolution is ambiguous; ignore
effects.push(log("debug", `Ignoring rename of conflicted file: ${relativePath}`))
return { state, effects }
}
}
// Check if rename's old path is a conflicted file
if (kind === "rename" && event.event.oldRelativePath) {
const oldConflictIndex = state.pendingConflicts.findIndex(
c => c.fileName === event.event.oldRelativePath
)
if (oldConflictIndex >= 0) {
effects.push(log("debug", `Ignoring rename of conflicted file: ${event.event.oldRelativePath} → ${relativePath}`))
return { state, effects }
}
}
// Non-conflicted file: fall through to normal processing
// - delete → LOCAL_INITIATED_FILE_DELETE (pending-deletes guard queues, clear-conflicts surfaces)
// - rename → SEND_FILE_RENAME (set-mode guard prevents conflict UI dismissal)
// - add/change → SEND_LOCAL_CHANGE
} else {
effects.push(log("debug", `Ignoring watcher event in ${state.mode} mode: ${kind} ${relativePath}`))
return { state, effects }
}
}
switch (kind) {
case "add":
case "change": {
if (content === undefined) {
effects.push(log("warn", `Watcher event missing content: ${relativePath}`))
return { state, effects }
}
effects.push({
type: "SEND_LOCAL_CHANGE",
fileName: relativePath,
content,
})
break
}
case "delete": {
effects.push(log("debug", `Local delete detected: ${relativePath}`), {
type: "LOCAL_INITIATED_FILE_DELETE",
fileNames: [relativePath],
})
break
}
case "rename": {
if (content === undefined || !event.event.oldRelativePath) {
effects.push(log("warn", `Rename event missing data: ${relativePath}`))
return { state, effects }
}
effects.push(
log("debug", `Local rename detected: ${event.event.oldRelativePath} → ${relativePath}`),
{
type: "SEND_FILE_RENAME",
oldFileName: event.event.oldRelativePath,
newFileName: relativePath,
content,
}
)
break
}
}
return { state, effects }
}
case "CONFLICT_VERSION_RESPONSE": {
if (state.mode !== "conflict_resolution") {
effects.push(log("warn", `Received CONFLICT_VERSION_RESPONSE in mode ${state.mode}, ignoring`))
return { state, effects }
}
const { autoResolvedLocal, autoResolvedRemote, remainingConflicts } = autoResolveConflicts(
state.pendingConflicts,
event.versions
)
if (autoResolvedLocal.length > 0) {
effects.push(log("debug", `Auto-resolved ${autoResolvedLocal.length} local changes`))
const localDeletes: string[] = []
for (const conflict of autoResolvedLocal) {
if (conflict.localContent === null) {
localDeletes.push(conflict.fileName)
} else {
effects.push({
type: "SEND_LOCAL_CHANGE",
fileName: conflict.fileName,
content: conflict.localContent,
})
}
}
// Batch local deletes into single confirmation prompt
if (localDeletes.length > 0) {
effects.push({
type: "LOCAL_INITIATED_FILE_DELETE",
fileNames: localDeletes,
})
}
}
if (autoResolvedRemote.length > 0) {
effects.push(log("debug", `Auto-resolved ${autoResolvedRemote.length} remote changes`))
for (const conflict of autoResolvedRemote) {
if (conflict.remoteContent === null) {
// Remote deleted - delete locally
effects.push({
type: "DELETE_LOCAL_FILES",
names: [conflict.fileName],
})
} else {
effects.push({
type: "WRITE_FILES",
files: [
{
name: conflict.fileName,
content: conflict.remoteContent,
modifiedAt: conflict.remoteModifiedAt ?? Date.now(),
},
],
silent: true, // Auto-resolved during initial sync - no individual indicators
})
}
}
}
if (remainingConflicts.length > 0) {
effects.push(log("warn", `${pluralize(remainingConflicts.length, "conflict")} require resolution`), {
type: "REQUEST_CONFLICT_DECISIONS",
conflicts: remainingConflicts,
})
return {
state: {
...state,
pendingConflicts: remainingConflicts,
},
effects,
}
}
const resolvedCount = autoResolvedLocal.length + autoResolvedRemote.length
effects.push(
{ type: "PERSIST_STATE" },
{
type: "SYNC_COMPLETE",
totalCount: resolvedCount,
updatedCount: resolvedCount,
unchangedCount: 0,
}
)
const { pendingConflicts: _discarded, ...rest } = state
return {
state: {
...rest,
mode: "watching",
pendingRemoteChanges: [],
},
effects,
}
}
default: {
effects.push(log("warn", `Unhandled event type in transition`))
return { state, effects }
}
}
}
/**
* Effect executor - interprets effects and calls helpers
* Returns additional events that should be processed (e.g., CONFLICTS_DETECTED after DETECT_CONFLICTS)
*/
async function executeEffect(
effect: Effect,
context: {
config: Config
hashTracker: ReturnType<typeof createHashTracker>
installer: Installer | null
fileMetadataCache: FileMetadataCache
pendingRenameConfirmations: Map<string, PendingRenameConfirmation>
shutdown: () => Promise<void>
userActions: PluginUserPromptCoordinator
syncState: SyncState
}
): Promise<SyncEvent[]> {
const { config, hashTracker, installer, fileMetadataCache, pendingRenameConfirmations, shutdown, userActions, syncState } =
context
switch (effect.type) {
case "INIT_WORKSPACE": {
// Initialize project directory if not already set
if (!config.projectDir) {
const projectName = config.explicitName ?? effect.projectInfo.projectName
const directoryInfo = await findOrCreateProjectDirectory({
projectHash: config.projectHash,
projectName,
explicitDirectory: config.explicitDirectory,
})
config.projectDir = directoryInfo.directory
config.projectDirCreated = directoryInfo.created
if (directoryInfo.nameCollision) {
warn(`Folder ${projectName} already exists`)
}
// May allow customization of file directory in the future
config.filesDir = `${config.projectDir}/files`
debug(`Files directory: ${config.filesDir}`)
await fs.mkdir(config.filesDir, { recursive: true })
}
return []
}
case "LOAD_PERSISTED_STATE": {
if (config.projectDir) {
await fileMetadataCache.initialize(config.projectDir)
debug(`Loaded persisted metadata for ${pluralize(fileMetadataCache.size(), "file")}`)
}
return []
}
case "LIST_LOCAL_FILES": {
if (!config.filesDir) {
return []
}
// List all local files and send to plugin
const files = await listFiles(config.filesDir)
if (syncState.socket) {
await sendMessage(syncState.socket, {
type: "file-list",
files,
})
}
return []
}
case "DETECT_CONFLICTS": {
if (!config.filesDir) {
return []
}
// Use existing helper to detect conflicts
const { conflicts, writes, localOnly, unchanged } = await detectConflicts(
effect.remoteFiles,
config.filesDir,
{ persistedState: fileMetadataCache.getPersistedState() }
)
// Record metadata for unchanged files so watcher add events get skipped
// (chokidar ignoreInitial=false fires late adds that would otherwise re-upload)
for (const file of unchanged) {
fileMetadataCache.recordRemoteWrite(file.name, file.content, file.modifiedAt ?? Date.now())
}
// Return CONFLICTS_DETECTED event to continue the flow
return [
{
type: "CONFLICTS_DETECTED",
conflicts,
safeWrites: writes,
localOnly,
},
]
}
case "SEND_MESSAGE": {
if (syncState.socket) {
const sent = await sendMessage(syncState.socket, effect.payload)
if (!sent) {
warn(`Failed to send message: ${effect.payload.type}`)
}
} else {
warn(`No socket available to send: ${effect.payload.type}`)
}
return []
}
case "WRITE_FILES": {
if (config.filesDir) {
// skipEcho skip writes that match hashTracker (inbound echo)
// it is opt-in: some callers still need side-effects (metadata/logs)
// even when content matches the last hash tracked in-memory.
const filesToWrite =
effect.skipEcho === true ? filterEchoedFiles(effect.files, hashTracker) : effect.files
if (effect.skipEcho && filesToWrite.length !== effect.files.length) {
const skipped = effect.files.length - filesToWrite.length
debug(`Skipped ${pluralize(skipped, "echoed change")}`)
}
if (filesToWrite.length === 0) {
return []
}
await writeRemoteFiles(filesToWrite, config.filesDir, hashTracker, installer ?? undefined)
for (const file of filesToWrite) {
if (!effect.silent) {
fileDown(file.name)
}
const remoteTimestamp = file.modifiedAt ?? Date.now()
fileMetadataCache.recordRemoteWrite(file.name, file.content, remoteTimestamp)
}
}
return []
}
case "DELETE_LOCAL_FILES": {
if (config.filesDir) {
for (const fileName of effect.names) {
await deleteLocalFile(fileName, config.filesDir, hashTracker)
fileDelete(fileName)
fileMetadataCache.recordDelete(fileName)
}
}
return []
}
case "REQUEST_CONFLICT_DECISIONS": {
await userActions.requestConflictDecisions(syncState.socket, effect.conflicts)
return []
}
case "UPDATE_CONFLICT_DATA": {
if (syncState.socket) {
await sendMessage(syncState.socket, {
type: "conflicts-detected",
conflicts: effect.conflicts,
})
}
return []
}
case "REQUEST_CONFLICT_VERSIONS": {
if (!syncState.socket) {
warn("Cannot request conflict versions without active socket")
return []
}
const persistedState = fileMetadataCache.getPersistedState()
const versionRequests = effect.conflicts.map(conflict => {
const persisted = persistedState.get(conflict.fileName)
return {
fileName: conflict.fileName,
lastSyncedAt: conflict.lastSyncedAt ?? persisted?.timestamp,
}
})
debug(`Requesting remote version data for ${pluralize(versionRequests.length, "file")}`)
await sendMessage(syncState.socket, {
type: "conflict-version-request",
conflicts: versionRequests,
})
return []
}
case "UPDATE_FILE_METADATA": {
if (!config.filesDir || !config.projectDir) {
return []
}
// Read current file content to compute hash
const currentContent = await readFileSafe(effect.fileName, config.filesDir)