Skip to content

fix(komorebi): keep workspace labels on their monitors - #192

Merged
aguil merged 17 commits into
masterfrom
fix/komorebi-monitor-labels
Nov 23, 2026
Merged

aguil merged 17 commits into
masterfrom
fix/komorebi-monitor-labels

Conversation

@aguil

@aguil aguil commented Nov 22, 2026 •

Copy link
Copy Markdown
Owner

Why the change

Workspace labels drifted between the two external monitors because komorebi matched them by a connection ID that Windows swaps, so this matches them by serial number, stops the startup steps that relabelled them by position, and restores the labels and window placement after a reconnect.

Special things to note

  • Run chezmoi init before relying on chezmoi for komorebi.json. This repo is public, so the serials live in the local chezmoi config. While both are blank, chezmoi skips the file. An existing value wins over detection, so edit it when replacing a monitor.
  • What is proven, and what is not. While docking, komorebi 0.1.41 can see a display before Windows identifies it, and loses labels, bar spacing and windows. On real docks the script has fixed labels and spacing, uncloaked lost windows, and put all four windows back three times: twice after a rebuild and once after a full restart. One earlier dock failed because it skipped windows the undock had minimized; the fix for that (reopening them) has not come up on a dock since. Also not tried: a swap of the external connection IDs with serial matching installed, stacked windows, and chezmoi init with the new template. 3 of the 8 logged rebuilds failed and needed the restart, which is allowed once per 10 minutes; komorebi rebuild after a dock fails intermittently: bar 0 does not come back #193 has the likely cause (one bar does not come back).
  • Tradeoffs. Restoring reopens a saved window you minimize while undocked, uses an undocumented Windows call (the one komorebi uses), and focuses each window to move it. With the internal display off, Alt+1–3 do nothing and placement is not saved or restored. Alt+Shift+C restarts komorebi without restoring placement. Saving keeps a hidden PowerShell running (about 1% of one core, 80 MB). The scenario tests for the scripts are not in the repo.

Change outline

How labels reach a monitor at startup:

 start-komorebi.cmd
-  komorebi.exe                      # restores saved workspaces by position
+  komorebi.exe --clean-state        # skips that restore
     match each display to a config
-      by device ID (UID swaps between externals)
+      by serial number (device ID for the internal panel)
-  workspace-reconcile.ps1           # names monitors by index, then every 15s

What happens after a display change:

+workspace-cycle.ahk: on display change, wait 8s, then
+  workspace-recover.ps1
+    wait up to 20s for komorebi and Windows to agree
+    labels, order, bar spacing, serial or display wrong
+      -> rebuild the monitor list in place
+         still wrong -> start-komorebi.cmd (10 min cooldown)
+    any other mismatch -> log it, change nothing
+    a configured display went away, komorebi restarted, or a rebuild was needed
+      -> uncloak forgotten windows, reopen minimized ones,
+         send each back to its saved workspace
+      -> if any is not back: log it and keep saving paused (10 min)
+  workspace-recover.ps1 -Watch       # saves placement while docked and healthy
+    two equal checks 10s apart -> workspace-placement.json
+    stopped by a display change or start-komorebi.cmd until recovery finishes
+  at load: run recovery if a display change or restart is still pending

Where the serials come from:

+[data.komorebi]                     # ~/.config/chezmoi/chezmoi.toml, never committed
+  viewsonicSerial, asusSerial       # set by chezmoi init, first match wins:
+     1. env var
+     2. existing value
+     3. monitor-serial.ps1          # stored EDID for the model; blank if ambiguous
+     both blank  -> .chezmoiignore skips komorebi.json
+     any set     -> komorebi.json.tmpl renders them

How Alt+N picks a workspace:

 workspace-target.ps1
-  choose a label list from the monitor count
+  label = fixed slot label (I1–I3, E4–E6, E7–E9)
+  if that label is missing, use the matching I label
+  if that is missing too, do nothing

Files:

 .chezmoi.toml.tmpl                  # adds [data.komorebi]
 .chezmoiignore.tmpl                 # skips komorebi.json while serials are blank; fixes
                                     # Windows-only and wl-paste entries that matched nothing
 .chezmoiremove                      # removes the old reconcile script
+scripts/monitor-serial.ps1          # finds a model's serial at init
-komorebi.json
+komorebi.json.tmpl
 dot_config/
   start-komorebi.cmd                # --clean-state, no reconcile call, marks a restart
   workspace-cycle.ahk               # display-change trigger, starts the saver, no reconcile timer
+  workspace-recover.ps1             # restores labels by serial, and placement
+  workspace-window.ps1              # window calls it uses (uncloak, reopen, focus)
-  workspace-reconcile.ps1
   workspace-target.ps1              # labels by presence
   workspace-ring.ps1, -cycle.ps1    # floor, not round, the monitor index
   whkdrc                            # --clean-state; drops the no-op alt+shift+o
   komorebi-setup-notes.md           # explains all of the above

🤖 Generated with Claude Code

aguil and others added 17 commits November 22, 2026 10:56
PowerShell's [int] cast rounds, so cycling to the third workspace of a
monitor targeted the next monitor instead (2/3 became 1). Use
[math]::Floor in workspace-ring.ps1 and workspace-cycle.ps1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Match the external monitors by serial number. The device IDs end in a
UID that Windows assigns per connection, and the ViewSonic and ASUS
kept trading them, so neither matched and both lost their config.

The repo is public, so the serials come from [data.komorebi] in the
local chezmoi config. While both are blank, komorebi.json is ignored
so an apply cannot overwrite a working live file.

Remove workspace-reconcile.ps1, which named monitors by index and hid
the failed match. workspace-target.ps1 now picks labels from the
workspaces that exist instead of the monitor count.

Start komorebi with --clean-state: the saved state is restored by
monitor position and moved the labels again after a restart. The cost
is that a restart forgets which workspace each window was on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
alt+shift+o ran `komorebic reload-configuration`, which only executes
komorebi.ps1 or komorebi.ahk from the home folder. This setup has
neither, so the binding did nothing. komorebi already reloads
komorebi.json when the file is saved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Default the [data.komorebi] serials to the ones Windows recorded for
each model, so a new machine needs no manual step. An env var or an
existing value still wins, and detection runs only during chezmoi init.

monitor-serial.ps1 reads stored EDID data without elevation. It uses
the text serial, then the numeric one, matching what komorebi reports,
and prints nothing for placeholders or two different serials.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
komorebi 0.1.41 looks up a reconnected monitor's workspaces once, when
it adds the monitor. After a dock that swapped the display IDs, both
externals missed that lookup and kept one unnamed workspace; the log
implies their serials were not available yet.

workspace-recover.ps1 waits for komorebi and Windows to agree, then
reloads komorebi.json if labels are wrong. It restarts komorebi, with a
cooldown, if the order is wrong or a serial never arrives. AutoHotkey
runs it 8 seconds after the last display change. The reload resets
layouts changed by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A second dock left the ASUS as a permanent UNKNOWN display: komorebi
added it before Windows gave it an ID, and does not correct that while
the monitor count stays the same. workspace-recover.ps1 only gave up.

Rebuild the monitor list in place with replace-configuration when a
configured display or serial is missing or the order is wrong, and
restart komorebi only if that fails. Wait 20 seconds instead of 45. A
rebuild brings windows on hidden workspaces to the front.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A third dock left a window unmanaged and the ASUS without space for its
bar. The reload restored only names and layouts, so the labels looked
right while windows overlapped the bars.

Drop the reload and rebuild the monitor list in place for wrong labels
too, and check bar spacing before and after. A rebuild adopts visible
windows and restarts the bars. It moves windows from hidden workspaces
to the first workspace on their monitor. Unmanaged windows alone are
not detected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
komorebi adopts windows wherever they are while docking, so a dock moved
visible windows to other monitors. A window on a hidden workspace stayed
cloaked and unmanaged, and neither a rebuild nor a restart shows it.

Save placement while docked and healthy, stop on a display change, and
after recovery uncloak forgotten windows and send each one back. Wait
for an earlier recovery run instead of skipping. Not yet run on a real
dock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Retry when komorebi gives no state, and stop with an error if it never
does, instead of indexing null or treating it as empty. Keep saving
paused when a restore fails or is incomplete, so that the good placement
is not overwritten for up to 10 minutes.

Finding: quality-restore-aborts-on-missing-state

One failed `komorebic state` call aborts or skips placement restore, and
the good snapshot can then be overwritten

The script says `komorebic fails while komorebi is busy; callers poll
again`, but the restore path does not tolerate a missing state.

Move-Window passes Get-KomorebiState straight to Get-FocusedHwnd on each
of its 6 attempts. With no state, Get-FocusedHwnd indexes a null array
and throws, so the retry loop does not retry. Nothing catches the error
until the outer handler, which logs it and exits. The remaining windows
are not moved, and the visible workspaces and focus are not restored.
The two Get-Placement calls in Restore-Placement fail the same way.

The undocked marker and frozen file are left behind, and nothing retries
until the next display change. After FreezeMinutes (10), the watcher
sees correct labels and saves the half-restored layout over the good
snapshot.

A second path loses the snapshot sooner. If the state read before the
move loop returns nothing, the loop moves no windows. If later reads
succeed, the main flow still removes the undocked marker and the frozen
file, so the watcher can save the wrong layout within about 20 seconds.

Move-Window should treat a missing state as a failed attempt, and
Restore-Placement should poll until it gets one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Note a drop in the monitor count when the display change arrives, so a
display that is back before recovery runs still gets its windows
restored. Keep the marker if a display drops again during recovery.

Finding: quality-quick-reconnect-skips-restore

A display that drops and returns before recovery samples it is never
recorded as undocked, so placement is not restored

The undocked marker is written only inside workspace-recover.ps1, from
one Test-AllDisplays sample after the 8-second debounce and the
readiness poll. Every WM_DISPLAYCHANGE restarts the 8-second timer. A
display that disconnects and reconnects within that window is therefore
seen only in its final, fully docked state.

If labels, order and bar spacing are right by then, $problem is empty
and no marker exists, so restore is skipped. This contradicts the stated
behavior (`a display went away, or a rebuild was needed`) and the
comment `Otherwise nothing moved the windows`.

The same run then removes the frozen file. The watcher can save the
disturbed layout about 20 seconds later, replacing the good snapshot.

Recording the missing display when the display-change event arrives,
before the debounce, would close the gap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
chezmoi matches ignore patterns against target paths, so dot_config/
entries matched nothing. Use .config/ for the two new scripts and the
older komorebi entries beside them, and fix the notes' extension.

Finding: quality-chezmoiignore-source-paths

New ignore entries use source paths, so the Windows-only scripts are
still installed on macOS and Linux

chezmoi matches .chezmoiignore patterns against target paths. The new
entries use the source prefix `dot_config/`, but the targets are
`.config/workspace-recover.ps1` and `.config/workspace-window.ps1`, so
neither entry matches.

Applying on macOS, Linux or WSL will install both scripts under
~/.config. The repository's config matrix says komorebi config must
never be installed outside Windows.

The neighboring `dot_config/` entries already had this problem, and the
PR extends it to two more files. Using `.config/...` for these entries
fixes it. The `.chezmoiremove` entry added in this PR already uses the
target form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The third bar's config was missing from the Windows-only list, so chezmoi
installed it on Linux and macOS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The entry used the source path, which chezmoi does not match, so the
WSL-only shim was installed everywhere. Already installed copies are not
removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Do not expect a saved window back if komorebi now tracks it untiled or
it is not visible. They made every restore count as failed, which kept
the undock marker, so a later display change undid the user's moves.
Forgotten cloaked and visible unmanaged windows still count as failures.

Finding: quality-restore-never-succeeds-with-untiled-window

Restore-Placement counts floating, monocle, maximized and hidden windows
as failures, so recovery state is not cleared

Restore-Placement puts every saved window that still exists into
`$wanted`, excluding only minimized ones. Success requires every
`$wanted` entry to appear in Get-Placement, which lists only tiled
windows.

A window that was tiled when saved but has since been floated, put in
monocle, maximized through komorebi, or hidden to the tray keeps its
handle and owning process. It stays in `$wanted`, but the restore cannot
place it, so the function returns false even when all tiled windows are
correct.

The caller then returns before removing either the undocked marker or
the frozen file. Saving stays paused until the frozen file is 10 minutes
old. Any further display change while docked refreshes that pause and
runs the restore again from the old snapshot, because the undocked
marker remains. That moves back windows the user has since rearranged.
It contradicts the guard comment (`Otherwise nothing moved the windows,
and the user may just have`) and the notes, which say these windows are
left alone.

Excluding windows that are not currently tiled and are intentionally
untiled or not visible from `$wanted` would avoid this, while still
counting a forgotten cloaked window as a failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On a real dock Windows left two saved windows minimized. Restore skipped
them and still logged success, so the wrong layout replaced the saved
one.

Reopen saved windows that are minimized, wait for komorebi to adopt them
and place them. Count one that stays minimized as a failure, report the
windows left alone, and keep the placement each restore started from.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mark an undock only when fewer displays remain than komorebi.json lists,
and leave displays outside the config out of the saved placement. An
extra display being removed no longer undoes window moves.

Finding: quality-extra-display-removal-restores-stale-placement

Removing an unconfigured display is treated as an undock and restores
stale placement

workspace-cycle.ahk writes the `undocked` marker whenever the total
monitor count drops. It does not check that a display listed in
`display_index_preferences` was lost, so removing a virtual display or a
fourth monitor while all three configured displays stay connected also
writes it.

If Windows and komorebi disagree about the extra display (the virtual
display case in the notes), readiness stays `displays differ`. Watch
mode then saves nothing for the whole session. When the display is
removed, recovery sees `ready`, all displays present, no problem and an
`undocked` marker, so it calls Restore-Placement with the file saved
before the extra display appeared. Window moves the user made during
that session are reverted, saved windows they minimized are reopened,
and focus is taken to do it. The notes say a virtual display is logged
and nothing is changed, and the code comment says restore should not
undo moves the user may just have made.

If both sides see the extra display, readiness is `ready`. Test-Labels
skips monitors with no config index, so Watch saves the extra monitor's
unnamed workspace as an empty name plus a fourth `visible` entry. After
removal, the restore cannot succeed: the visible list has four entries
against three. It logs `placement wrong`, leaves the `undocked` marker
in place and keeps saving paused for up to 10 minutes.

Consider writing the marker only when a configured display was lost, and
not saving workspaces that are missing from the config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
start-komorebi.cmd kills AutoHotkey and any recovery that was waiting.
Leave the markers before stopping anything, and have the hotkey script
pause saving and run recovery at load if one exists. Do nothing if no
saved window is left, such as after a reboot.

Finding: quality-restart-drops-pending-recovery

Restarting through start-komorebi.cmd cancels pending recovery, and
AutoHotkey never reruns it at load

Recovery now has one trigger: a one-shot 8-second timer inside
workspace-cycle.ahk, armed by WM_DISPLAYCHANGE. start-komorebi.cmd
force-kills AutoHotkey64.exe, which discards that timer. The relaunched
script calls only RunWatch() at load. The old script called
RunReconcile() at load and every 15 seconds, and this PR removes both
without a replacement.

The setup notes say a scheduled task runs start-komorebi.cmd on every
session unlock. If the user docks and unlocks within about 8 seconds,
the display change writes the `frozen` marker (and `undocked` if the
count had dropped), then the unlock kills AutoHotkey before recovery
starts. komorebi starts with --clean-state, so it forgets window
workspaces. Nothing then checks labels, order or bar spacing, or
restores placement, until another display change happens.

The good snapshot is also lost. The relaunched watcher ignores the
`undocked` marker and stops honouring `frozen` after 10 minutes. If the
displays look healthy, it then saves the scrambled layout over
workspace-placement.json. The leftover `undocked` marker makes the next
docked recovery restore that bad layout.

An unlock with no display change has a related effect. Placement is
dropped by --clean-state, there is no `frozen` file, and the watcher can
overwrite the snapshot after two matching checks. The PR describes this
cost only for a manual restart.

Running recovery once at AutoHotkey load (at least when the `undocked`
or `frozen` marker exists), and not saving while `undocked` is present,
would close the docking gap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@aguil
aguil marked this pull request as ready for review November 23, 2026 00:41
@aguil
aguil merged commit cf2424c into master Nov 23, 2026
1 check passed
@aguil
aguil deleted the fix/komorebi-monitor-labels branch November 23, 2026 00:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant