flow-wm 0.2.0

A scrolling, infinite-horizontal-canvas tiling window manager for Windows
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
//! IPC message and response types for the flow protocol.
//!
//! The protocol uses newline-delimited JSON. The CLI sends a [`SocketMessage`],
//! the daemon replies with a [`SocketResponse`].
//!
//! # Wire format
//!
//! ```text
//! {"type":"stop"}\n
//! {"status":"ok"}\n
//! ```
//!
//! See the developer guide's *IPC & Watchdog* chapter
//! (`docs/src/dev-guide/ipc-and-watchdog.md`) for the message catalog and the
//! named-pipe transport.

use crate::common::Direction;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Target window mode for the [`SocketMessage::SetWindow`] command.
///
/// Used by both the IPC wire format (serde) and the CLI (clap `Subcommand`).
/// See the developer guide (`docs/src/dev-guide/ipc-and-watchdog.md`) for the
/// message catalog.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::Subcommand)]
#[serde(rename_all = "snake_case")]
pub enum WindowMode {
    /// Place the focused window in floating mode.
    Float,
    /// Place the focused window in tiling mode.
    Tile,
    /// Toggle between float and tile based on current state.
    Cycle,
}

/// Default named pipe path used by the daemon and CLI on Windows.
pub const PIPE_NAME: &str = r"\\.\pipe\flow";

/// Environment variable name for overriding the pipe path.
const PIPE_ENV: &str = "FLOW_PIPE_NAME";

/// Return the named pipe path for IPC.
///
/// Reads from the `FLOW_PIPE_NAME` environment variable, falling back to
/// [`PIPE_NAME`] if not set. This allows integration tests to use isolated
/// pipe names without interfering with a production daemon.
///
/// Both `flowd` and `flow` read the same variable, so spawning the daemon
/// via `flow start` inherits the variable automatically.
pub fn pipe_name() -> String {
    std::env::var(PIPE_ENV).unwrap_or_else(|_| PIPE_NAME.to_owned())
}

/// A command sent from `flow` CLI to the `flowd` daemon.
///
/// Serialised with an externally tagged `"type"` field and snake_case variant
/// names. See the developer guide (`docs/src/dev-guide/ipc-and-watchdog.md`)
/// for the full message catalog.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SocketMessage {
    /// Shut down the daemon gracefully.
    Stop,
    /// Reload configuration from disk.
    ReloadConfig,
    /// Validate the current config file without applying it.
    CheckConfig,

    // --- Focus ---
    /// Move focus left.
    FocusLeft,
    /// Move focus right.
    FocusRight,
    /// Move focus up (within column).
    FocusUp,
    /// Move focus down (within column).
    FocusDown,

    // --- Swap (per-window) ---
    /// Swap the focused window with its left neighbour.
    SwapLeft,
    /// Swap the focused window with its right neighbour.
    SwapRight,
    /// Swap the focused window with the one above it (same column).
    SwapUp,
    /// Swap the focused window with the one below it (same column).
    SwapDown,

    // --- Column swap ---
    /// Swap the focused column with its neighbour in the given direction.
    ///
    /// Unlike the per-window `Swap*` messages above, this operates on the
    /// *entire column* containing the focused window. The layout engine's
    /// `swap_column` handles the viewport scroll automatically (via
    /// `ensure_column_visible`), so off-screen columns are brought into view
    /// as part of the same diff — no separate "offscreen" message is needed.
    SwapColumn {
        /// Direction to swap the column (left or right).
        direction: Direction,
    },

    // --- Semantic move ---
    /// Move the focused window in the given direction.
    ///
    /// This is a high-level, *semantic* command: the daemon translates the
    /// intended movement based on the window's current state and the layout.
    ///
    /// - Tiled window, left/right → swap the entire column (delegates to
    ///   [`SocketMessage::SwapColumn`]). Real cross-column move (extract +
    ///   reinsert) is *[deferred — not yet wired]*.
    /// - Tiled window, up/down → swap with the adjacent window in the same
    ///   column (delegates to [`SocketMessage::SwapWindow`]).
    /// - Floating window, any direction → nudge by a configurable shift.
    ///   *[deferred — not yet wired]*
    ///
    /// Keeping `move-window` separate from the concrete `SwapColumn`/`Swap*`
    /// messages lets the daemon own the "what does *move* mean here?"
    /// decision, so keybindings stay stable as floating support lands.
    MoveWindow {
        /// Direction to move the focused window.
        direction: Direction,
    },

    // --- Scroll ---
    /// Scroll viewport left.
    ScrollLeft,
    /// Scroll viewport right.
    ScrollRight,

    // --- Column resize ---
    /// Expand the focused column width.
    ExpandColumn,
    /// Shrink the focused column width.
    ShrinkColumn,
    /// Set focused column width to an explicit pixel value.
    ///
    /// The width is free-form (not snapped to the expand/shrink slot ladder)
    /// and is validated by the daemon against the engine's current bounds
    /// (`[min_column_width_px, abs_max_width]`).
    SetColumnWidth {
        /// Target column width in pixels.
        width_px: u32,
    },

    // --- Viewport center ---
    /// Center the viewport so the focused column lands at the monitor midpoint.
    ///
    /// Maps to [`ScrollingSpace::center_focused_column`](crate::workspace::ScrollingSpace::center_focused_column).
    /// Uses the variable-width prefix sum, so it is correct even when columns
    /// have been expanded or shrunk. See (`docs/src/dev-guide/layout/mutations.md`).
    Center,

    // --- Window state ---
    /// Set the focused window's mode (float, tile, or cycle).
    ///
    /// Replaces the legacy [`ToggleFloat`] with explicit mode control.
    SetWindow {
        /// Desired window mode.
        mode: WindowMode,
    },
    /// Toggle the focused window between tiling and floating.
    ToggleFloat,
    /// Toggle monocle mode on the focused column.
    ToggleMonocle,
    /// Place the focused window above (z-order).
    PlaceAbove,
    /// Promote the focused window out of its column into a new standalone column.
    ///
    /// The focused window is detached from its current column and inserted as
    /// the sole row of a brand-new column placed immediately to the left or
    /// right of the source column. The source column's remaining rows are
    /// redistributed to equal heights. This is a no-op when the focused
    /// window is already the only row in its column.
    Promote {
        /// Direction to spawn the new column (left or right of source).
        direction: Direction,
    },
    /// Merge the focused window's row into the adjacent column.
    ///
    /// The focused window is removed from its current column and appended as
    /// a new bottom row of the neighbour column. Both columns' row heights
    /// are redistributed to equal shares. Vertical directions are rejected
    /// (this is a horizontal-only operation).
    MergeColumn {
        /// Direction of the neighbour column to merge into (left or right).
        direction: Direction,
    },
    /// Close the focused window.
    CloseWindow,

    // --- Workspace ---
    //
    // These three messages form the niri-style virtual-desktop surface.
    // `SwitchWorkspace` and `MoveWindowToWorkspace` are implemented (see
    // `daemon::dispatch`); `SwapWorkspace` is still a stub pending a separate
    // animation model.
    //
    // The `workspace_id` field carries a [`crate::workspace::WorkspaceId`]
    // (a `u32` newtype over niri-style IDs). On the wire it serialises as a
    // bare integer, matching `WorkspaceId`'s `#[serde(transparent)]` impl.
    /// Switch the active monitor's focus to the given workspace.
    ///
    /// Mirrors `flow dispatch switch-workspace <id>`. The previously active
    /// workspace is conceptually frozen in its packed position (above or
    /// below the target, the vertical analogue of horizontal column packing
    /// inside a `ScrollingSpace`) and the target slides into the viewport.
    SwitchWorkspace {
        /// Target workspace identifier (niri-style `u32`).
        workspace_id: u32,
    },
    /// Swap the active workspace with the target workspace in the monitor's
    /// workspace list.
    ///
    /// Mirrors `flow dispatch swap-workspace <id>`. The two workspaces exchange
    /// positions in the packed vertical stack; focus follows the originally
    /// active workspace to its new slot. This is the operation most other
    /// tiling managers omit but that is essential for rearranging a long
    /// workspace list without re-creating workspaces.
    SwapWorkspace {
        /// Target workspace identifier to swap with the active workspace.
        workspace_id: u32,
    },
    /// Move the focused window to the target workspace.
    ///
    /// Mirrors `flow dispatch move-to-workspace <id>`. The focused window is
    /// detached from the active workspace's `ScrollingSpace` (with local
    /// focus succession — no OS foreground focus push) and re-inserted into
    /// the target workspace's `ScrollingSpace` after its currently focused
    /// column. The camera then follows the moved window: the active workspace
    /// switches to the target so the moved window is visible (see
    /// `dispatch_move_window_to_workspace`). Moving to the currently active
    /// workspace is a no-op.
    ///
    /// The variant is named `MoveWindowToWorkspace` (rather than the shorter
    /// `MoveToWorkspace`) to mirror the sibling [`MoveWindow`](Self::MoveWindow)
    /// message: both operate on the focused *window*, and the longer name
    /// makes the operand explicit. The CLI surface keeps the shorter
    /// `move-to-workspace` for brevity.
    MoveWindowToWorkspace {
        /// Destination workspace identifier.
        workspace_id: u32,
    },

    // --- Queries ---
    /// Query all managed windows.
    QueryWindowsAll,
    /// Query the virtual layout.
    QueryLayoutVirtual,
    /// Query the actual (projected) layout.
    QueryLayoutActual,
    /// Query full daemon state.
    QueryState,

    // --- Config mutation ---
    /// Set a single config value at runtime.
    SetConfigValue {
        /// Dot-separated config key.
        key: String,
        /// JSON value to set.
        value: serde_json::Value,
    },
    /// Remove per-app learned preferences for the given executable.
    ForgetApp {
        /// Executable name (e.g. `"firefox.exe"`).
        exe: String,
    },
    /// Remove all per-app learned preferences.
    ForgetAllApps,

    // --- Loadout save / restore ---
    /// Save the current workspace arrangement to a loadout file.
    ///
    /// `path: None` means the daemon should use the config-default path.
    /// `path: Some(p)` overrides to the given file path.
    LoadoutSave {
        /// Destination file path, or `None` for the config default.
        path: Option<PathBuf>,
    },
    /// Restore a previously saved loadout.
    ///
    /// `path: None` means the daemon should use the config-default path.
    LoadoutLoad {
        /// Source file path, or `None` for the config default.
        path: Option<PathBuf>,
    },
}

impl SocketMessage {
    /// Whether this command mutates window positions or layout state.
    ///
    /// Returns `true` for commands that would conflict with an in-progress
    /// tile drag (focus changes, swaps, resizes, mode toggles, workspace
    /// switches, config reloads that re-apply geometry, and `CloseWindow`
    /// whose async destroy reflows the layout). Read-only queries and pure
    /// daemon lifecycle commands return `false`.
    #[must_use]
    pub fn is_layout_mutating(&self) -> bool {
        matches!(
            self,
            Self::FocusLeft
                | Self::FocusRight
                | Self::FocusUp
                | Self::FocusDown
                | Self::SwapLeft
                | Self::SwapRight
                | Self::SwapUp
                | Self::SwapDown
                | Self::SwapColumn { .. }
                | Self::MoveWindow { .. }
                | Self::ScrollLeft
                | Self::ScrollRight
                | Self::ExpandColumn
                | Self::ShrinkColumn
                | Self::SetColumnWidth { .. }
                | Self::Center
                | Self::SetWindow { .. }
                | Self::ToggleFloat
                | Self::ToggleMonocle
                | Self::Promote { .. }
                | Self::MergeColumn { .. }
                | Self::SwitchWorkspace { .. }
                | Self::SwapWorkspace { .. }
                | Self::MoveWindowToWorkspace { .. }
                | Self::ReloadConfig
                | Self::CloseWindow
        )
    }
}

/// A response sent from the `flowd` daemon back to the `flow` CLI.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum SocketResponse {
    /// Command succeeded.
    Ok,
    /// Command failed with an error message.
    Error {
        /// Human-readable error description.
        message: String,
    },
    /// Response to a query, carrying arbitrary JSON data.
    Data {
        /// The query result payload.
        payload: serde_json::Value,
    },
    /// The daemon is busy — a tile-window drag is in progress and layout-mutating
    /// commands are temporarily rejected. The client may retry shortly.
    Busy,
}

/// Serialise a message as a single line of JSON terminated by `\\n`.
///
/// This is the wire format for the named pipe transport.
///
/// # Errors
///
/// Returns an error if `serde_json` fails to serialise `msg`.
pub fn encode_message<T: Serialize>(msg: &T) -> Result<String, serde_json::Error> {
    let mut line = serde_json::to_string(msg)?;
    line.push('\n');
    Ok(line)
}

/// Parse a single newline-delimited JSON message.
///
/// Returns `None` if the line is empty or whitespace-only.
pub fn decode_message<'de, T: Deserialize<'de>>(line: &'de str) -> Option<T> {
    let trimmed = line.trim();
    if trimmed.is_empty() {
        return None;
    }
    serde_json::from_str(trimmed).ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    // Positive: round-trip Stop message
    #[test]
    fn roundtrip_stop() {
        let msg = SocketMessage::Stop;
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, r#"{"type":"stop"}"#);

        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, SocketMessage::Stop);
    }

    // Positive: round-trip SetColumnWidth
    #[test]
    fn roundtrip_set_column_width() {
        let msg = SocketMessage::SetColumnWidth { width_px: 960 };
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, r#"{"type":"set_column_width","width_px":960}"#);

        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, SocketMessage::SetColumnWidth { width_px: 960 });
    }

    // Positive: round-trip SwapColumn
    #[test]
    fn roundtrip_swap_column() {
        let msg = SocketMessage::SwapColumn {
            direction: Direction::Right,
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, r#"{"type":"swap_column","direction":"Right"}"#);

        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(
            parsed,
            SocketMessage::SwapColumn {
                direction: Direction::Right,
            }
        );
    }

    // Positive: round-trip MoveWindow
    #[test]
    fn roundtrip_move_window() {
        let msg = SocketMessage::MoveWindow {
            direction: Direction::Left,
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, r#"{"type":"move_window","direction":"Left"}"#);

        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(
            parsed,
            SocketMessage::MoveWindow {
                direction: Direction::Left,
            }
        );
    }

    // Positive: round-trip SocketResponse::Ok
    #[test]
    fn roundtrip_response_ok() {
        let resp = SocketResponse::Ok;
        let json = serde_json::to_string(&resp).unwrap();
        assert_eq!(json, r#"{"status":"ok"}"#);

        let parsed: SocketResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, SocketResponse::Ok);
    }

    // Positive: round-trip SocketResponse::Error
    #[test]
    fn roundtrip_response_error() {
        let resp = SocketResponse::Error {
            message: "daemon busy".into(),
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert_eq!(json, r#"{"status":"error","message":"daemon busy"}"#);

        let parsed: SocketResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, resp);
    }

    // Positive: round-trip SocketResponse::Data
    #[test]
    fn roundtrip_response_data() {
        let resp = SocketResponse::Data {
            payload: serde_json::json!({"windows": []}),
        };
        let json = serde_json::to_string(&resp).unwrap();
        let parsed: SocketResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, resp);
    }

    // Positive: encode_message adds newline
    #[test]
    fn encode_adds_newline() {
        let encoded = encode_message(&SocketMessage::Stop).unwrap();
        assert!(encoded.ends_with('\n'));
        assert_eq!(encoded, "{\"type\":\"stop\"}\n");
    }

    // Positive: decode_message handles whitespace
    #[test]
    fn decode_trims_whitespace() {
        let msg: Option<SocketMessage> = decode_message("  {\"type\":\"stop\"}  \n");
        assert_eq!(msg, Some(SocketMessage::Stop));
    }

    // Negative: decode_message returns None for empty line
    #[test]
    fn decode_empty_returns_none() {
        let msg: Option<SocketMessage> = decode_message("");
        assert_eq!(msg, None);
    }

    // Negative: decode_message returns None for invalid JSON
    #[test]
    fn decode_invalid_returns_none() {
        let msg: Option<SocketMessage> = decode_message("not json");
        assert_eq!(msg, None);
    }

    // Positive: encode/decode round-trip through wire format
    #[test]
    fn wire_format_roundtrip() {
        let msg = SocketMessage::FocusLeft;
        let wire = encode_message(&msg).unwrap();
        let parsed: Option<SocketMessage> = decode_message(&wire);
        assert_eq!(parsed, Some(SocketMessage::FocusLeft));
    }

    // Positive: SetConfigValue round-trip
    #[test]
    fn roundtrip_set_config_value() {
        let msg = SocketMessage::SetConfigValue {
            key: "gaps.inner".into(),
            value: serde_json::json!(10),
        };
        let json = serde_json::to_string(&msg).unwrap();
        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    // --- Full coverage: all remaining unit variants via wire roundtrip ---

    // Positive: round-trip all simple (unit) variants not yet covered individually
    #[test]
    fn roundtrip_all_unit_variants() {
        // Every unit variant (no fields) except Stop (already tested above)
        let variants = vec![
            SocketMessage::ReloadConfig,
            SocketMessage::CheckConfig,
            SocketMessage::FocusRight,
            SocketMessage::FocusUp,
            SocketMessage::FocusDown,
            SocketMessage::SwapLeft,
            SocketMessage::SwapRight,
            SocketMessage::SwapUp,
            SocketMessage::SwapDown,
            SocketMessage::ScrollLeft,
            SocketMessage::ScrollRight,
            SocketMessage::ExpandColumn,
            SocketMessage::ShrinkColumn,
            SocketMessage::Center,
            SocketMessage::ToggleFloat,
            SocketMessage::ToggleMonocle,
            SocketMessage::PlaceAbove,
            SocketMessage::Promote {
                direction: Direction::Left,
            },
            SocketMessage::MergeColumn {
                direction: Direction::Right,
            },
            SocketMessage::CloseWindow,
            SocketMessage::QueryWindowsAll,
            SocketMessage::QueryLayoutVirtual,
            SocketMessage::QueryLayoutActual,
            SocketMessage::QueryState,
            SocketMessage::ForgetAllApps,
        ];

        for msg in &variants {
            let wire = encode_message(msg).unwrap();
            let parsed: Option<SocketMessage> = decode_message(&wire);
            assert_eq!(parsed.as_ref(), Some(msg), "roundtrip failed for: {msg:?}");
        }
    }

    // Positive: round-trip ForgetApp variant (has string field)
    #[test]
    fn roundtrip_forget_app() {
        let msg = SocketMessage::ForgetApp {
            exe: "firefox.exe".into(),
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert!(json.contains(r#""forget_app""#));
        assert!(json.contains(r#""exe":"firefox.exe""#));

        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    // Positive: round-trip SwitchWorkspace (struct variant carrying workspace_id)
    #[test]
    fn roundtrip_switch_workspace() {
        let msg = SocketMessage::SwitchWorkspace { workspace_id: 3 };
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, r#"{"type":"switch_workspace","workspace_id":3}"#);

        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, SocketMessage::SwitchWorkspace { workspace_id: 3 });
    }

    // Positive: round-trip SwapWorkspace
    #[test]
    fn roundtrip_swap_workspace() {
        let msg = SocketMessage::SwapWorkspace { workspace_id: 7 };
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, r#"{"type":"swap_workspace","workspace_id":7}"#);

        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, SocketMessage::SwapWorkspace { workspace_id: 7 });
    }

    // Positive: round-trip MoveWindowToWorkspace
    #[test]
    fn roundtrip_move_window_to_workspace() {
        let msg = SocketMessage::MoveWindowToWorkspace { workspace_id: 11 };
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(
            json,
            r#"{"type":"move_window_to_workspace","workspace_id":11}"#
        );

        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(
            parsed,
            SocketMessage::MoveWindowToWorkspace { workspace_id: 11 }
        );
    }

    // Positive: workspace_id of 0 round-trips (boundary value)
    #[test]
    fn roundtrip_workspace_id_zero() {
        // WorkspaceId(0) is a valid construction; ensure the wire protocol
        // does not implicitly reject or mangle zero.
        for msg in [
            SocketMessage::SwitchWorkspace { workspace_id: 0 },
            SocketMessage::SwapWorkspace { workspace_id: 0 },
            SocketMessage::MoveWindowToWorkspace { workspace_id: 0 },
        ] {
            let wire = encode_message(&msg).unwrap();
            let parsed: Option<SocketMessage> = decode_message(&wire);
            assert_eq!(parsed.as_ref(), Some(&msg), "zero id failed: {wire}");
        }
    }

    // Positive: wire format roundtrip covers FocusLeft via encode+decode
    #[test]
    fn wire_format_roundtrip_set_column_width() {
        // Positive: set_column_width with an explicit pixel value round-trips
        let msg = SocketMessage::SetColumnWidth { width_px: 1280 };
        let wire = encode_message(&msg).unwrap();
        let parsed: Option<SocketMessage> = decode_message(&wire);
        assert_eq!(
            parsed,
            Some(SocketMessage::SetColumnWidth { width_px: 1280 })
        );
    }

    // Positive: round-trip SetWindow (float)
    #[test]
    fn roundtrip_set_window_float() {
        let msg = SocketMessage::SetWindow {
            mode: WindowMode::Float,
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, r#"{"type":"set_window","mode":"float"}"#);

        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(
            parsed,
            SocketMessage::SetWindow {
                mode: WindowMode::Float
            }
        );
    }

    // Positive: round-trip SetWindow (tile)
    #[test]
    fn roundtrip_set_window_tile() {
        let msg = SocketMessage::SetWindow {
            mode: WindowMode::Tile,
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, r#"{"type":"set_window","mode":"tile"}"#);

        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(
            parsed,
            SocketMessage::SetWindow {
                mode: WindowMode::Tile
            }
        );
    }

    // Positive: round-trip SetWindow (cycle)
    #[test]
    fn roundtrip_set_window_cycle() {
        let msg = SocketMessage::SetWindow {
            mode: WindowMode::Cycle,
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, r#"{"type":"set_window","mode":"cycle"}"#);

        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(
            parsed,
            SocketMessage::SetWindow {
                mode: WindowMode::Cycle
            }
        );
    }

    // Positive: round-trip LoadoutSave with None path (config default)
    #[test]
    fn roundtrip_loadout_save_none_path() {
        let msg = SocketMessage::LoadoutSave { path: None };
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, r#"{"type":"loadout_save","path":null}"#);
        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, SocketMessage::LoadoutSave { path: None });
    }

    // Positive: round-trip LoadoutSave with explicit path
    #[test]
    fn roundtrip_loadout_save_some_path() {
        let msg = SocketMessage::LoadoutSave {
            path: Some(PathBuf::from("C:\\temp\\loadout.json")),
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert!(json.contains("\"type\":\"loadout_save\""));
        assert!(json.contains("\"path\":\"C:\\\\temp\\\\loadout.json\""));
        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    // Positive: round-trip LoadoutLoad
    #[test]
    fn roundtrip_loadout_load() {
        let msg = SocketMessage::LoadoutLoad { path: None };
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, r#"{"type":"loadout_load","path":null}"#);
        let parsed: SocketMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, SocketMessage::LoadoutLoad { path: None });
    }

    // Negative: unknown loadout type tag returns None
    #[test]
    fn decode_unknown_loadout_type_returns_none() {
        let line = r#"{"type":"loadout_delete","path":null}"#;
        let msg: Option<SocketMessage> = decode_message(line);
        assert_eq!(msg, None, "unknown loadout type should return None");
    }

    // --- encode_message error path ---

    // Negative: encode_message returns Err for a type that fails serialization
    #[test]
    fn encode_message_returns_err_for_unserializable() {
        /// A type that always fails during serialization, to exercise the error
        /// path of `encode_message`.
        #[derive(Debug)]
        struct AlwaysFailSerialize;

        impl serde::Serialize for AlwaysFailSerialize {
            fn serialize<S: serde::Serializer>(&self, _s: S) -> Result<S::Ok, S::Error> {
                Err(serde::ser::Error::custom(
                    "intentional serialization failure",
                ))
            }
        }

        let result = encode_message(&AlwaysFailSerialize);
        assert!(
            result.is_err(),
            "encode_message should return Err for failing serializer"
        );
        let err = result.unwrap_err();
        assert!(
            err.to_string()
                .contains("intentional serialization failure")
        );
    }

    // Positive: encode_message returns Ok for all SocketMessage variants
    #[test]
    fn encode_message_succeeds_for_all_variants() {
        // Covers every variant to ensure none triggers an unexpected error
        let all_variants = vec![
            SocketMessage::Stop,
            SocketMessage::ReloadConfig,
            SocketMessage::CheckConfig,
            SocketMessage::FocusLeft,
            SocketMessage::FocusRight,
            SocketMessage::FocusUp,
            SocketMessage::FocusDown,
            SocketMessage::SwapLeft,
            SocketMessage::SwapRight,
            SocketMessage::SwapUp,
            SocketMessage::SwapDown,
            SocketMessage::SwapColumn {
                direction: Direction::Right,
            },
            SocketMessage::MoveWindow {
                direction: Direction::Left,
            },
            SocketMessage::ScrollLeft,
            SocketMessage::ScrollRight,
            SocketMessage::ExpandColumn,
            SocketMessage::ShrinkColumn,
            SocketMessage::Center,
            SocketMessage::SetColumnWidth { width_px: 800 },
            SocketMessage::SetWindow {
                mode: WindowMode::Float,
            },
            SocketMessage::ToggleFloat,
            SocketMessage::ToggleMonocle,
            SocketMessage::PlaceAbove,
            SocketMessage::Promote {
                direction: Direction::Left,
            },
            SocketMessage::MergeColumn {
                direction: Direction::Right,
            },
            SocketMessage::CloseWindow,
            SocketMessage::QueryWindowsAll,
            SocketMessage::QueryLayoutVirtual,
            SocketMessage::QueryLayoutActual,
            SocketMessage::QueryState,
            SocketMessage::SetConfigValue {
                key: "outer_gap".into(),
                value: serde_json::json!(16),
            },
            SocketMessage::ForgetApp {
                exe: "explorer.exe".into(),
            },
            SocketMessage::ForgetAllApps,
            SocketMessage::SwitchWorkspace { workspace_id: 1 },
            SocketMessage::SwapWorkspace { workspace_id: 2 },
            SocketMessage::MoveWindowToWorkspace { workspace_id: 3 },
            SocketMessage::LoadoutSave { path: None },
            SocketMessage::LoadoutSave {
                path: Some(PathBuf::from("C:\\temp\\loadout.json")),
            },
            SocketMessage::LoadoutLoad { path: None },
            SocketMessage::LoadoutLoad {
                path: Some(PathBuf::from("C:\\temp\\loadout.json")),
            },
        ];

        for msg in &all_variants {
            let result = encode_message(msg);
            assert!(result.is_ok(), "encode_message failed for variant: {msg:?}");
            let wire = result.unwrap();
            assert!(
                wire.ends_with('\n'),
                "wire format must end with newline for: {msg:?}"
            );
        }
    }

    // --- decode_message negative edge cases ---

    // Negative: decode_message returns None for unknown type tag
    #[test]
    fn decode_unknown_type_tag_returns_none() {
        let line = r#"{"type":"nonexistent_command"}"#;
        let msg: Option<SocketMessage> = decode_message(line);
        assert_eq!(msg, None, "unknown type tag should return None");
    }

    // Negative: decode_message returns None for missing type tag
    #[test]
    fn decode_missing_type_tag_returns_none() {
        let line = r#"{"not_a_type":"stop"}"#;
        let msg: Option<SocketMessage> = decode_message(line);
        assert_eq!(msg, None, "missing type tag should return None");
    }

    // Negative: decode_message returns None for plain object (no fields)
    #[test]
    fn decode_empty_object_returns_none() {
        let line = "{}";
        let msg: Option<SocketMessage> = decode_message(line);
        assert_eq!(msg, None, "empty object should return None");
    }

    // Negative: decode_message returns None for array instead of object
    #[test]
    fn decode_array_returns_none() {
        let line = "[1, 2, 3]";
        let msg: Option<SocketMessage> = decode_message(line);
        assert_eq!(msg, None, "array input should return None");
    }

    // Positive: decode_message handles trailing newline in wire
    #[test]
    fn decode_trailing_newline() {
        let line = "{\"type\":\"stop\"}\n";
        let msg: Option<SocketMessage> = decode_message(line);
        assert_eq!(msg, Some(SocketMessage::Stop));
    }

    // Positive: SocketResponse::Data with complex payload round-trips
    #[test]
    fn roundtrip_response_data_complex() {
        let resp = SocketResponse::Data {
            payload: serde_json::json!({
                "windows": [
                    {"id": 1, "title": "Firefox", "rect": [0, 0, 960, 1080]},
                    {"id": 2, "title": "VS Code", "rect": [960, 0, 960, 1080]}
                ],
                "focused": 1
            }),
        };
        let wire = encode_message(&resp).unwrap();
        let parsed: Option<SocketResponse> = decode_message(&wire);
        assert_eq!(parsed, Some(resp));
    }

    // Negative: decode_message returns None for response-shaped data on message type
    #[test]
    fn decode_response_status_on_message_returns_none() {
        // A response JSON has "status" tag, not "type" tag — should not parse as SocketMessage
        let line = r#"{"status":"ok"}"#;
        let msg: Option<SocketMessage> = decode_message(line);
        assert_eq!(
            msg, None,
            "response-shaped JSON should not parse as SocketMessage"
        );
    }

    // Negative: decode_message returns None for message-shaped data on response type
    #[test]
    fn decode_message_type_on_response_returns_none() {
        // A message JSON has "type" tag, not "status" tag — should not parse as SocketResponse
        let line = r#"{"type":"stop"}"#;
        let resp: Option<SocketResponse> = decode_message(line);
        assert_eq!(
            resp, None,
            "message-shaped JSON should not parse as SocketResponse"
        );
    }

    // ── SocketResponse::Busy serialization ───────────────────────────────

    // Positive: SocketResponse::Busy round-trips through serde with the
    // `{"status":"busy"}` wire format. This is the variant the daemon returns
    // when a tile drag is in progress and a layout-mutating command arrives.
    #[test]
    fn roundtrip_response_busy() {
        let resp = SocketResponse::Busy;
        let json = serde_json::to_string(&resp).unwrap();
        assert_eq!(json, r#"{"status":"busy"}"#);

        let parsed: SocketResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, SocketResponse::Busy);
    }

    // Positive: SocketResponse::Busy round-trips through the wire encode/decode
    // helpers (newline-delimited transport) — same path the named-pipe transport uses.
    #[test]
    fn wire_format_roundtrip_response_busy() {
        let wire = encode_message(&SocketResponse::Busy).unwrap();
        assert_eq!(wire, "{\"status\":\"busy\"}\n");
        let parsed: Option<SocketResponse> = decode_message(&wire);
        assert_eq!(parsed, Some(SocketResponse::Busy));
    }

    // ── SocketMessage::is_layout_mutating ────────────────────────────────
    //
    // The dispatch busy gate (src/daemon/dispatch.rs) relies on this method to
    // reject conflicting commands during a tile drag. The classification MUST
    // match the daemon's actual mutation behaviour: every variant that touches
    // window positions, focus, layout state, or workspace assignment must return
    // `true`; pure queries and daemon-lifecycle commands must return `false`.
    // A misclassification is a silent correctness bug (either a rejected
    // read-only query, or an allowed mutating command that corrupts the drag),
    // so the tests enumerate every variant explicitly.

    // Positive: every layout-mutating variant returns true. The list is
    // exhaustive — adding a new mutating variant without updating this list
    // (and `is_layout_mutating`) would let a future command slip past the gate.
    #[test]
    fn is_layout_mutating_returns_true_for_mutating_variants() {
        let mutating: Vec<SocketMessage> = vec![
            // Focus (changes focused column/row — mutates layout-driven state)
            SocketMessage::FocusLeft,
            SocketMessage::FocusRight,
            SocketMessage::FocusUp,
            SocketMessage::FocusDown,
            // Per-window swap
            SocketMessage::SwapLeft,
            SocketMessage::SwapRight,
            SocketMessage::SwapUp,
            SocketMessage::SwapDown,
            // Column swap
            SocketMessage::SwapColumn {
                direction: Direction::Left,
            },
            // Semantic move
            SocketMessage::MoveWindow {
                direction: Direction::Right,
            },
            // Scroll (mutates viewport_offset)
            SocketMessage::ScrollLeft,
            SocketMessage::ScrollRight,
            // Column resize
            SocketMessage::ExpandColumn,
            SocketMessage::ShrinkColumn,
            SocketMessage::SetColumnWidth { width_px: 800 },
            // Viewport center (mutates viewport_offset)
            SocketMessage::Center,
            // Window state
            SocketMessage::SetWindow {
                mode: WindowMode::Float,
            },
            SocketMessage::ToggleFloat,
            SocketMessage::ToggleMonocle,
            SocketMessage::Promote {
                direction: Direction::Left,
            },
            SocketMessage::MergeColumn {
                direction: Direction::Right,
            },
            // Workspace
            SocketMessage::SwitchWorkspace { workspace_id: 1 },
            SocketMessage::SwapWorkspace { workspace_id: 2 },
            SocketMessage::MoveWindowToWorkspace { workspace_id: 3 },
            // Config reload (re-applies geometry to every workspace)
            SocketMessage::ReloadConfig,
            // Close (async WM_CLOSE → destroy hook → layout reflow)
            SocketMessage::CloseWindow,
        ];

        for msg in &mutating {
            assert!(
                msg.is_layout_mutating(),
                "expected is_layout_mutating() == true for {msg:?}"
            );
        }
    }

    // Negative: every read-only / lifecycle variant returns false. Queries and
    // daemon-control commands must never be blocked by the busy gate.
    #[test]
    fn is_layout_mutating_returns_false_for_read_only_variants() {
        let read_only: Vec<SocketMessage> = vec![
            // Daemon lifecycle
            SocketMessage::Stop,
            SocketMessage::CheckConfig,
            // Queries
            SocketMessage::QueryWindowsAll,
            SocketMessage::QueryLayoutVirtual,
            SocketMessage::QueryLayoutActual,
            SocketMessage::QueryState,
            // Runtime config mutation (does not move windows)
            SocketMessage::SetConfigValue {
                key: "gaps.inner".into(),
                value: serde_json::json!(10),
            },
            // Per-app preferences (registry-only, no layout change)
            SocketMessage::ForgetApp {
                exe: "firefox.exe".into(),
            },
            SocketMessage::ForgetAllApps,
            // Z-order only (no layout mutation)
            SocketMessage::PlaceAbove,
        ];

        for msg in &read_only {
            assert!(
                !msg.is_layout_mutating(),
                "expected is_layout_mutating() == false for {msg:?}"
            );
        }
    }

    // Positive: is_layout_mutating handles both Direction values for SwapColumn.
    // Defends against a future refactor that special-cases one direction.
    #[test]
    fn is_layout_mutating_swap_column_both_directions() {
        assert!(
            SocketMessage::SwapColumn {
                direction: Direction::Left
            }
            .is_layout_mutating()
        );
        assert!(
            SocketMessage::SwapColumn {
                direction: Direction::Right
            }
            .is_layout_mutating()
        );
    }

    // Positive: is_layout_mutating handles both Direction values for MoveWindow.
    #[test]
    fn is_layout_mutating_move_window_both_directions() {
        assert!(
            SocketMessage::MoveWindow {
                direction: Direction::Left
            }
            .is_layout_mutating()
        );
        assert!(
            SocketMessage::MoveWindow {
                direction: Direction::Right
            }
            .is_layout_mutating()
        );
    }

    // Positive: is_layout_mutating handles all three WindowMode values for SetWindow.
    #[test]
    fn is_layout_mutating_set_window_all_modes() {
        for mode in [WindowMode::Float, WindowMode::Tile, WindowMode::Cycle] {
            assert!(
                SocketMessage::SetWindow { mode }.is_layout_mutating(),
                "SetWindow with mode {mode:?} should be layout-mutating"
            );
        }
    }

    // Positive: is_layout_mutating handles workspace_id of 0 (boundary).
    #[test]
    fn is_layout_mutating_workspace_commands_with_zero_id() {
        assert!(SocketMessage::SwitchWorkspace { workspace_id: 0 }.is_layout_mutating());
        assert!(SocketMessage::SwapWorkspace { workspace_id: 0 }.is_layout_mutating());
        assert!(SocketMessage::MoveWindowToWorkspace { workspace_id: 0 }.is_layout_mutating());
    }
}