Commit Graph

491 Commits

Author SHA1 Message Date
Brian Krabach 7f42d6cbe2 feat: add view dropdown trigger and menu to app header (task-4)
- Add #view-dropdown-trigger button between wordmark and header-actions
- Add #view-dropdown-menu container with role='menu' and hidden class
- Add #view-dropdown-label with default text 'All Sessions'
- Add caret span with aria-hidden='true'
- Trigger has aria-haspopup='true', aria-expanded='false', aria-controls attributes
- All wrapped in .view-dropdown div with id='view-dropdown'

Tests added:
- test_view_dropdown_trigger_exists
- test_view_dropdown_container_exists
- test_view_dropdown_trigger_has_aria
- test_view_dropdown_menu_has_role_menu

All 93 tests pass (4 new + 89 existing).
2026-04-15 17:23:00 -07:00
Brian Krabach ecca48a1ad feat: auto-add new session to active user view on creation
When a session is created via the + button while a user view is active,
auto-add the new session's key to that view's sessions list.

- In createNewSession(), after the successful POST call, check _activeView
- Skip auto-add for reserved views ('all', 'hidden')
- Build sessionKey correctly using device_id or remoteId
- PATCH /api/settings with updated views, catch errors gracefully
- Update local _serverSettings.views cache immediately

Test: test_create_new_session_references_active_view
2026-04-15 17:17:11 -07:00
Brian Krabach c3eb714977 feat: rewrite getVisibleSessions() to honor active view (task-2)
- Add _activeView state variable with default 'all' in App state section
- Rewrite getVisibleSessions() to filter by active view:
  - 'all' view: excludes hidden sessions
  - 'hidden' view: shows only hidden sessions
  - user view: filters to view's sessions list using sessionKey
  - Falls back to 'all' if active view no longer exists
- Add _getActiveView() and _setActiveView() test helpers
- Export new test helpers in window.MuxplexApp (module.exports)
- Add 6 new tests covering all acceptance criteria

Tests added:
- test_active_view_state_variable_exists
- test_get_visible_sessions_all_view_excludes_hidden
- test_get_visible_sessions_hidden_view_shows_hidden
- test_get_visible_sessions_user_view_filters_by_session_key
- test_get_active_view_helper_exported
- test_set_active_view_helper_exported

All 220 tests pass.
2026-04-15 17:08:04 -07:00
Brian Krabach acdfc9bafd docs: update patch_state docstring to include active_view 2026-04-15 17:03:17 -07:00
Brian Krabach b69a1f8c15 feat: add active_view to StatePatch model and patch_state handler
- Add optional active_view field to StatePatch Pydantic model
- Add active_view handling in patch_state to persist the field
- Add test_patch_state_sets_active_view: verifies PATCH persists active_view
- Add test_patch_state_active_view_defaults_to_all: verifies GET returns 'all' by default

Closes task-1: Add active_view to StatePatch Model
2026-04-15 16:56:43 -07:00
Brian Krabach ab5560a623 fix: address COE verification findings — bell-clear regression, active_view fallback, device_id consistency
- BUG 1: Replace isinstance(active_remote_id, int) guard with _lookup_remote_by_device_id()
  so bell-clear fires correctly when active_remote_id is a UUID string (new format).
  Old code silently skipped the POST for all non-integer active_remote_id values.
  Regression test: test_poll_cycle_fires_federation_bell_clear_for_remote_session_with_uuid

- GAP 4: Add _resolveActiveView(activeView, views) helper in app.js.
  Falls back to 'all' when active_view references a deleted/unknown view name.
  Ready for Phase 2 view-switching code to call at read time.

- ISSUE 6: _createDeviceSelect now uses remotes[i].device_id || String(i) for option
  values instead of always String(i), so session creation routes receive correct device_id.

- ISSUE 9: identity.json written with indent=2 + trailing newline, consistent with
  settings.json and state.json formatting conventions.

- ISSUE 11: Fix state.py module docstring — 'tmux-web muxplex' → 'muxplex'.

- ISSUE 12: Settings panel hidden_sessions checkboxes now use s.sessionKey || s.name
  as the checkbox value (and checked state) so remote sessions are stored in
  device_id:name format, consistent with getVisibleSessions() lookups.
2026-04-15 14:42:50 -07:00
Brian Krabach 70822d8033 feat: remove 'filtered' gridViewMode, keep only flat and grouped
- renderGrid: remove all _gridViewMode === 'filtered' branches (device
  filter application and filter bar rendering); filter bar is now always
  cleared for flat/grouped modes
- loadGridViewMode: add 'filtered' → 'flat' fallback so existing users
  who had the setting stored don't get a broken state
- _setGridViewMode (test helper): same guard so tests can't accidentally
  set the removed mode
- test_frontend_js.py: three new static-analysis tests assert the guards
  are present and the renderGrid filtered checks are gone
2026-04-15 14:05:28 -07:00
Brian Krabach 68fa80b694 feat: update frontend to use device_id-based session keys and API URLs
- buildTileHTML: prefer session.deviceId over legacy integer remoteId for data-remote-id
- buildSidebarHTML: prefer session.deviceId over legacy integer remoteId for data-remote-id
- getVisibleSessions: check s.sessionKey (device_id:name) in hidden_sessions list for
  backward compatibility with both old (plain name) and new (device_id:name) formats
- openSession: rename _remoteId → _deviceId to reflect value is now a device_id string
- createNewSession: rename internal remoteId variable → deviceId for clarity

All federation API URLs continue to work via opts.remoteId (now contains deviceId value).
Backward compatibility maintained: fallback to remoteId when deviceId not present (old server).

Tests: updated test_open_session_fires_bell_clear_for_remote to check _deviceId guard;
added 5 new tests covering all structural changes.
2026-04-15 13:59:03 -07:00
Brian Krabach 5510d9d008 feat: tag sessions with device_id-based sessionKey in federation_sessions 2026-04-15 13:48:39 -07:00
Brian Krabach c26c61b7da fix: extract auth_headers to local var to prevent ruff splitting inline guards
Ruff was reformatting the ternary header constructions to multi-line form:
  headers={"Authorization": f"Bearer {remote_key}"}\n  if remote_key\n  else {},

This caused test_federation_auth_headers_guard_empty_key to fail because
the source-inspection test requires 'if' to appear on the same line as
the Authorization header dict.

Fix: assign to a local variable before use so ruff has no reason to split:
  auth_headers = {"Authorization": f"Bearer {key}"} if key else {}

Applied at two sites:
- poll-cycle bell-clear (line ~232)
- federation WS proxy endpoint (line ~1094)
2026-04-15 13:02:32 -07:00
Brian Krabach 665b74b455 style: apply ruff format to main.py (task-9 follow-up) 2026-04-15 12:42:56 -07:00
Brian Krabach 8d7990b1c5 feat: switch federation proxy endpoints to device_id lookup (task-9)
Change all 5 federation proxy URL patterns from {remote_id:int} to
{device_id} (str) and use _lookup_remote_by_device_id() for lookup.

Affected endpoints:
- federation_connect: /api/federation/{device_id}/connect/{session_name}
- federation_bell_clear: /api/federation/{device_id}/sessions/{session_name}/bell/clear
- federation_create_session: /api/federation/{device_id}/sessions
- federation_delete_session: /api/federation/{device_id}/sessions/{session_name}
- federation_terminal_ws_proxy: /federation/{device_id}/terminal/ws

All endpoints now use _lookup_remote_by_device_id(device_id) which
provides integer index fallback for backward compatibility.

Also update existing test to expect 404 instead of 422 for non-integer
device_id (since str type accepts any string, lookup returns None->404).

Tests:
- test_federation_connect_by_device_id: POST with device_id='aaa-111-bbb' returns 200
- test_federation_connect_device_id_not_found: unknown device_id returns 404
2026-04-15 12:16:56 -07:00
Brian Krabach cc9bb81bc9 feat: add _lookup_remote_by_device_id helper for federation proxy
Implements _lookup_remote_by_device_id(device_id: str) -> dict | None
in muxplex/main.py, inserted before the federation WebSocket proxy section.

Logic:
- Load settings and get remote_instances list
- Primary: iterate remotes, return first where remote.get('device_id') == device_id
- Fallback: if device_id parses as integer, use index-based lookup for
  transition compatibility (0 <= idx < len(remotes))
- Return None if not found

Tests added:
- test_lookup_remote_by_device_id_found: two remotes with device_ids
  'aaa-111' and 'bbb-222'; lookup 'bbb-222' returns Desktop remote
- test_lookup_remote_by_device_id_not_found: one remote with device_id
  'aaa-111'; lookup 'zzz-999' returns None

Task: task-8
2026-04-15 11:45:06 -07:00
Brian Krabach 6984c71823 style: add explanatory comment and remove redundant import
- Add clarifying comment to lazy import of enforce_mutual_exclusion
  in apply_synced_settings() to document circular-import avoidance pattern
- Remove redundant 'import json' from inside
  test_apply_synced_settings_enforces_mutual_exclusion()
  since json is already imported at module level

No behavior changes. All 62 tests pass.

Generated with Amplifier

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
2026-04-15 11:37:00 -07:00
Brian Krabach a3ff22dc02 feat: wire post-sync mutual exclusion invariant repair into apply_synced_settings
- Call enforce_mutual_exclusion(current) in apply_synced_settings() after
  applying SYNCABLE_KEYS and before save_settings()
- Import enforce_mutual_exclusion from muxplex.views inside the function
  to avoid circular import issues
- Update docstring to describe the mutual exclusion invariant repair step
- Add test_apply_synced_settings_enforces_mutual_exclusion to verify that
  sessions present in both hidden_sessions and a view's sessions are
  removed from hidden_sessions after sync (task-7)
2026-04-15 11:33:49 -07:00
Brian Krabach 569ba44848 feat: add --reset-device-id CLI command (task-6)
Add reset_device_id_command() function to cli.py that:
- loads the current device_id via load_device_id()
- generates a new device_id via reset_device_id()
- prints new device_id, identity file path, previous device_id
- warns that existing session keys are now orphaned

Register 'reset-device-id' subparser with appropriate help text
and add dispatch branch in main().

Tests added:
- test_reset_device_id_writes_new_id: verifies command writes new ID
  and prints required output including orphan warning
- test_main_dispatches_to_reset_device_id: verifies CLI routing
2026-04-15 11:26:32 -07:00
Brian Krabach ad2c0e1fe2 feat: extend /api/instance-info to return device_id
Add load_device_id import from muxplex.identity and include device_id
in the instance-info response dict. Update endpoint docstring to
mention device identity.

Test: test_instance_info_includes_device_id verifies device_id is
present as a non-empty string when IDENTITY_PATH is redirected to
tmp_path.
2026-04-15 11:20:08 -07:00
Brian Krabach 353ea5fd76 feat: add views.py with mutual exclusion invariant and name validation 2026-04-15 11:10:34 -07:00
Brian Krabach eb2c02b477 feat: add views to DEFAULT_SETTINGS and SYNCABLE_KEYS
- Add 'views': [] to DEFAULT_SETTINGS (after 'hidden_sessions')
- Add 'views' to SYNCABLE_KEYS in Session behavior section (after 'hidden_sessions')
- Add 4 new tests: test_views_in_default_settings, test_views_in_syncable_keys,
  test_views_roundtrip_through_save_and_load, test_patch_settings_syncs_views

All 61 tests pass (57 existing + 4 new).
2026-04-15 11:03:42 -07:00
Brian Krabach d9e9ab2fb6 feat: update state path to muxplex, add MUXPLEX_STATE_DIR env var, add active_view field
- Change _default_state_dir from 'tmux-web' to 'muxplex'
- Update STATE_DIR to prefer MUXPLEX_STATE_DIR env var with TMUX_WEB_STATE_DIR fallback
- Add 'active_view': 'all' to empty_state() between active_remote_id and session_order
- Update module docstring schema to document active_view field
- Add tests: test_empty_state_has_active_view_key, test_empty_state_active_view_defaults_to_all, test_state_dir_uses_muxplex_name
2026-04-15 10:59:57 -07:00
Brian Krabach 59b1672275 feat: add device identity module with persistent UUID v4 storage
- Add muxplex/identity.py with IDENTITY_PATH, load_device_id(), reset_device_id()
- load_device_id() creates identity.json when absent, regenerates on corrupt JSON
  or missing device_id key, creates parent directories as needed
- reset_device_id() generates a new UUID v4, overwrites identity.json, returns it
- Add muxplex/tests/test_identity.py with 8 tests covering all spec requirements
2026-04-15 10:56:11 -07:00
Brian Krabach 93889f7dda docs: add Views feature design
Adds design specification for user-defined Views — curated session
collections that span devices and replace the filtered gridViewMode.

Covers:
- Stable device identity prerequisite (device_id UUID in identity.json)
- Data model: views array in settings, active_view in state
- Three view tiers: All (virtual), user-created, Hidden (virtual)
- Mutual exclusion invariant between hidden and view membership
- UI: header dropdown view switcher, tile flyout menu, add sessions panel
- Migration strategy for session key format change
- Known limitations: rename breakage, atomic sync, shortcut cap
2026-04-15 09:38:29 -07:00
Brian Krabach 3894a585c5 chore: release v0.3.6 -- browser context menu fix 2026-04-14 11:10:18 -07:00
Brian Krabach 56f7b99fd8 fix: suppress browser context menu on plain right-click in terminal pane 2026-04-14 11:10:15 -07:00
Brian Krabach 655b9ecab0 chore: release v0.3.5 -- connection pool exhaustion fix 2026-04-14 06:36:07 -07:00
Brian Krabach 2e57358e2e fix: replace setInterval with self-scheduling setTimeout for async polls
setInterval fires regardless of whether the previous async call has
completed. When federation requests time out (5s) during 2s poll cycles,
multiple requests stack up. Chrome's 6-connection-per-origin limit is
quickly exhausted → ERR_INSUFFICIENT_RESOURCES → death spiral.

Fix: self-scheduling setTimeout pattern — poll completes → wait → next
poll. At most one in-flight request at a time. Applied to both
pollSessions and sendHeartbeat loops.

A sentinel (true) is set on _pollingTimer/_heartbeatTimer immediately in
startPolling/startHeartbeat so the double-start guard works even during
the first async call before the real timer ID is assigned.
2026-04-14 05:30:39 -07:00
Brian Krabach 8345ee3323 chore: release v0.3.4 -- federation UI fixes 2026-04-13 14:56:42 -07:00
Brian Krabach b247f01ebc fix: remoteId=0 falsy bug in renderSheetList — use null check
The first remote instance (index 0) couldn't be opened from the mobile
bottom sheet because s.remoteId ? treated 0 as falsy. Changed to
s.remoteId != null to match buildTileHTML and buildSidebarHTML.
2026-04-13 14:18:25 -07:00
Brian Krabach f7519a8058 fix: zero-session devices show 'No sessions' tile + grace period prevents flapping
Two federation UX fixes:

1. Zero-session devices: when remote returns empty sessions list, return
   {status: 'empty'} entry. Frontend renders 'No sessions' status tile
   instead of making the device invisible.

2. Flapping prevention: server-side cache of last-known-good federation
   results per remote. On transient failure, return cached sessions for
   up to 3 consecutive failures before marking unreachable. Eliminates
   the visible on/off/on/off pattern caused by occasional 5-second
   timeouts during 2-second poll cycles.

Tests added:
- test_fetch_remote_returns_empty_status_for_zero_sessions (Python)
- test_fetch_remote_uses_cache_on_transient_failure (Python)
- test_fetch_remote_marks_unreachable_after_grace_period (Python)
- renderGrid shows 'No sessions' status tile for status=empty devices (JS)

Also adds reset_federation_cache autouse fixture to prevent cross-test
contamination from the new module-level _federation_cache dict.
2026-04-13 14:12:18 -07:00
Brian Krabach 26a4d30d6f fix: status tiles show device name instead of blank — use deviceName not name
buildStatusTileHTML received session.name (undefined for status entries)
instead of session.deviceName. Offline/unreachable tiles showed blank.
Fixed all 4 call sites in renderGrid to pass session.deviceName.

Updated two existing tests to use deviceName (not name) in status entry
objects — reflecting the real federation data shape.
2026-04-13 13:20:29 -07:00
Brian Krabach 2c65e5b4c2 fix: filter status entries from visible sessions — no more duplicate blank/offline tiles
Unreachable/auth_failed status entries from the federation response
were rendered twice: once as a blank session tile (no name) by
buildTileHTML, and again as an 'Offline' status tile by the separate
status rendering loop. Fix: getVisibleSessions() now filters out
entries with a status field. Status tiles are still rendered separately
from the full sessions array.
2026-04-13 12:01:32 -07:00
Brian Krabach 8d271ddd58 chore: release v0.3.3 -- iOS/iPadOS touch scroll fix 2026-04-13 08:50:50 -07:00
Brian Krabach e3cedb70a2 Merge pull request #4 from samueljklee/fix/ios-touch-scroll
Fix touch scrolling on iOS and iPadOS devices
2026-04-13 08:34:04 -07:00
Samuel Lee f206485f0a Fix touch scrolling on iOS and iPadOS devices
The touch scroll handler was only enabled for Android devices,
leaving iOS/iPad users unable to scroll through terminal history.

Changes:
- Extend UA detection to include iPhone, iPad, and iPod
- Add iPadOS 13+ detection (reports as MacIntel with touch points)
- Rename function to initMobileTerminalScroll for clarity

Fixes #3
2026-04-11 13:01:41 -07:00
Brian Krabach 0b2ec74ee5 chore: release v0.3.2 -- hidden sessions federation fix 2026-04-09 02:38:22 -07:00
Brian Krabach df1960b7f9 fix: apply hidden sessions filter to all sessions including remote/federated 2026-04-09 02:37:18 -07:00
Brian Krabach 9424dcff5b chore: release v0.3.1 -- federation auth hotfix 2026-04-08 23:17:55 -07:00
Brian Krabach d541612843 fix: read federation key live on each request and check PUT sync response
Bug 1 (auth.py): AuthMiddleware.dispatch() was using self.federation_key
(set once at startup) for Bearer token validation. If the key was generated
or rotated via POST /api/federation/generate-key after startup, the old
(often empty) value caused all federation auth to silently return 401.

Fix: import load_federation_key from muxplex.settings and call it fresh on
every non-exempt, non-cookie request. Also adds a warning log when a Bearer
token is received but no key is configured on this server.

Bug 2 (main.py): _sync_settings_with_remotes() discarded the PUT response,
silently swallowing 401/500 errors from the remote sync endpoint.

Fix: capture the PUT response as put_resp. Handle 409 (Conflict = remote is
newer) with a debug log; raise_for_status() for any other non-2xx so errors
propagate to the outer except and are logged as warnings.

Tests:
- test_dispatch_calls_load_federation_key_live: pattern test confirming
  load_federation_key() is called inside dispatch()
- test_dispatch_does_not_use_stale_self_federation_key_for_bearer: pattern
  test confirming self.federation_key is gone from the live bearer check
- test_sync_put_response_calls_raise_for_status: pattern test confirming
  raise_for_status() is called on the PUT response in the sync function
- Updated existing bearer tests to monkeypatch load_federation_key so they
  are isolated from any real key file on disk
2026-04-08 22:39:03 -07:00
Brian Krabach c4ff5c618f chore: release v0.3.0 -- federation state propagation 2026-04-08 22:06:20 -07:00
Brian Krabach 2ebd3b9929 feat: add settings sync logic to poll cycle with 30-second interval
- Add SETTINGS_SYNC_INTERVAL = 15 constant (15 poll cycles × 2s ≈ 30s)
- Add _settings_sync_counter module-level counter
- Add _sync_settings_with_remotes() async function that:
  - GETs /api/settings/sync from each remote instance
  - Adopts remote settings if remote timestamp is newer
  - Pushes local settings via PUT if local timestamp is newer
  - Silently skips 404/405 (older muxplex without sync endpoints)
  - Catches all per-remote errors and logs as warnings
- Wire sync call into _run_poll_cycle() step 13 (runs outside state_lock)
- Add test_settings_sync_poll.py with 10 tests covering all sync behaviours
2026-04-08 21:15:44 -07:00
Brian Krabach a0ad4921cf feat: add PUT /api/settings/sync federation endpoint with newer-wins logic 2026-04-08 21:03:23 -07:00
Brian Krabach 349f49824b feat: add GET /api/settings/sync federation endpoint 2026-04-08 20:50:46 -07:00
Brian Krabach 29cfb3c141 feat: sync-aware patch_settings and apply_synced_settings 2026-04-08 20:37:52 -07:00
Brian Krabach ce001d2b05 feat: add SYNCABLE_KEYS allowlist and settings_updated_at to settings 2026-04-08 20:35:08 -07:00
Brian Krabach 783611d143 fix: filter hidden sessions in browser indicators + add federation plan 2026-04-08 20:32:19 -07:00
Brian Krabach e7379c46c9 chore: fix step numbering in _run_poll_cycle comments 2026-04-08 19:40:04 -07:00
Brian Krabach 8fcb25adee fix: capture exception in federation bell clear warning log
Captures the exception as 'exc' in the except clause and includes it
as the third argument to the warning log message. This ensures that
the failure reason is observable in logs, improving diagnostics for
federation heartbeat failures.

Generated with Amplifier

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
2026-04-08 19:32:20 -07:00
Brian Krabach f5ae0df9f5 feat: add heartbeat-driven bell clearing for remote sessions in poll cycle
- Add module-level _federation_client reference for use in background poll task
- Assign _federation_client in lifespan startup; clear on shutdown
- Add step 12 to _run_poll_cycle: iterate devices viewing a remote session
  in fullscreen with recent interaction (<60s), fire POST bell/clear to
  the active remote instance with Bearer auth (fire-and-forget, errors logged)
- Add test_poll_cycle_fires_federation_bell_clear_for_remote_session test

Closes task-3 of federation-state-propagation-plan
2026-04-08 18:50:17 -07:00
Brian Krabach 5eb727fe86 fix: use s.remoteId == null check instead of !s.remoteId in getVisibleSessions()
Fixes falsy-0 bug where sessions with remoteId=0 (first remote instance) were
incorrectly hidden because !s.remoteId treats 0 as falsy. The null check
s.remoteId == null correctly handles:
- remoteId=0 (first remote instance) → truthy, not hidden
- remoteId=null or undefined (local sessions) → falsy, hidden if in hidden list

Changes:
- muxplex/frontend/app.js: Line 533 condition in getVisibleSessions()
- muxplex/frontend/tests/test_app.mjs: Added 2 tests for remoteId=0 behavior
- muxplex/tests/test_frontend_js.py: Added pattern test verifying source code

All 330 JS tests pass, all 200 Python tests pass.

Generated with Amplifier (https://github.com/microsoft/amplifier)

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
2026-04-08 18:04:45 -07:00
Brian Krabach 4856094ca9 docs: add federation state propagation design 2026-04-08 17:38:08 -07:00