Skip to content

Reflow on Resize - #2

Merged
mitchellh merged 20 commits into
mainfrom
reflow
Aug 9, 2022
Merged

mitchellh merged 20 commits into
mainfrom
reflow

Conversation

@mitchellh

Copy link
Copy Markdown
Contributor

This introduces text and cursor reflow on resize.

Admittedly, this is not the most efficient implementation. Specifically, shrinking columns is awful. I think I have to rethink parts of the Screen data structure to make this more efficient (and I have ideas). In the mean time, this makes reflow mostly work and starts to add a fairly significant test suite for reflow.

This 100% needs another pass, but the test suite should be solid for refactoring and it gives us a place to keep adding more reflow tests as we find bugs.

CleanShot.2022-08-08.at.20.53.24.2.mp4

@mitchellh
mitchellh merged commit febec6f into main Aug 9, 2022
@mitchellh
mitchellh deleted the reflow branch August 9, 2022 04:17
hallh added a commit to hallh/ghostty that referenced this pull request Aug 4, 2025
mitchellh added a commit that referenced this pull request Feb 18, 2026
This PR introduces unit tests and a supporting Mock NSView for testing
the SplitTree implementation in Swift. It includes 51 tests which
achieve approximately 93.13% (949/1019) coverage of SplitTree.swift's
branches.

<details>
  <summary>Coverage</summary>
  <pre>
./ghostty/macos/Sources/Features/Splits/SplitTree.swift 93.13%
(949/1019)
SplitTree.Path.isEmpty.getter 100.00% (1/1)
SplitTree.isEmpty.getter 100.00% (3/3)
SplitTree.isSplit.getter 100.00% (3/3)
SplitTree.init() 100.00% (3/3)
SplitTree.init(view:) 100.00% (3/3)
SplitTree.contains(_:) 100.00% (4/4)
SplitTree.inserting(view:at:direction:) 100.00% (6/6)
SplitTree.find(id:) 100.00% (4/4)
SplitTree.removing(_:) 93.75% (15/16)
SplitTree.replacing(node:with:) 93.75% (15/16)
SplitTree.focusTarget(for:from:) 82.14% (46/56)
closure #1 in SplitTree.focusTarget(for:from:) 100.00% (1/1)
closure #2 in SplitTree.focusTarget(for:from:) 100.00% (1/1)
closure #3 in SplitTree.focusTarget(for:from:) 100.00% (3/3)
implicit closure #1 in SplitTree.focusTarget(for:from:) 0.00% (0/1)
SplitTree.equalized() 100.00% (5/5)
SplitTree.resizing(node:by:in:with:) 92.00% (69/75)
closure #1 in SplitTree.resizing(node:by:in:with:) 100.00% (1/1)
SplitTree.viewBounds() 100.00% (4/4)
SplitTree.init(from:) 76.00% (19/25)
SplitTree.encode(to:) 100.00% (15/15)
SplitTree.Node.find(id:) 100.00% (13/13)
SplitTree.Node.node(view:) 88.89% (16/18)
SplitTree.Node.path(to:) 100.00% (32/32)
search #1 <A>(_:) in SplitTree.Node.path(to:) 100.00% (27/27)
SplitTree.Node.node(at:) 89.47% (17/19)
SplitTree.Node.inserting(view:at:direction:) 86.84% (33/38)
SplitTree.Node.replacingNode(at:with:) 100.00% (43/43)
replaceInner #1 <A>(current:pathOffset:) in
SplitTree.Node.replacingNode(at:with:) 96.67% (29/30)
SplitTree.Node.remove(_:) 70.27% (26/37)
implicit closure #1 in SplitTree.Node.remove(_:) 100.00% (1/1)
SplitTree.Node.resizing(to:) 100.00% (16/16)
SplitTree.Node.leftmostLeaf() 87.50% (7/8)
SplitTree.Node.rightmostLeaf() 87.50% (7/8)
SplitTree.Node.equalize() 100.00% (4/4)
SplitTree.Node.equalizeWithWeight() 100.00% (30/30)
SplitTree.Node.weightForDirection(_:) 83.33% (10/12)
SplitTree.Node.calculateViewBounds(in:) 100.00% (50/50)
SplitTree.Node.viewBounds() 100.00% (26/26)
SplitTree.Node.spatial(within:) 100.00% (18/18)
SplitTree.Node.dimensions() 80.77% (21/26)
SplitTree.Node.spatialSlots(in:) 100.00% (53/53)
SplitTree.Spatial.slots(in:from:) 100.00% (47/47)
closure #1 in SplitTree.Spatial.slots(in:from:) 100.00% (1/1)
distance #1 <A>(from:to:) in SplitTree.Spatial.slots(in:from:) 100.00%
(6/6)
closure #2 in SplitTree.Spatial.slots(in:from:) 100.00% (3/3)
implicit closure #1 in closure #2 in SplitTree.Spatial.slots(in:from:)
100.00% (1/1)
closure #3 in SplitTree.Spatial.slots(in:from:) 100.00% (3/3)
closure #4 in SplitTree.Spatial.slots(in:from:) 100.00% (3/3)
implicit closure #1 in closure #4 in SplitTree.Spatial.slots(in:from:)
100.00% (1/1)
closure #5 in SplitTree.Spatial.slots(in:from:) 100.00% (3/3)
closure #6 in SplitTree.Spatial.slots(in:from:) 100.00% (3/3)
implicit closure #1 in closure #6 in SplitTree.Spatial.slots(in:from:)
100.00% (1/1)
closure #7 in SplitTree.Spatial.slots(in:from:) 100.00% (3/3)
closure #8 in SplitTree.Spatial.slots(in:from:) 100.00% (3/3)
implicit closure #1 in closure #8 in SplitTree.Spatial.slots(in:from:)
100.00% (1/1)
closure #9 in SplitTree.Spatial.slots(in:from:) 100.00% (3/3)
SplitTree.Spatial.doesBorder(side:from:) 100.00% (20/20)
closure #1 in SplitTree.Spatial.doesBorder(side:from:) 100.00% (1/1)
closure #2 in SplitTree.Spatial.doesBorder(side:from:) 100.00% (3/3)
static SplitTree.Node.== infix(_:_:) 100.00% (13/13)
SplitTree.Node.init(from:) 66.67% (12/18)
SplitTree.Node.encode(to:) 100.00% (11/11)
SplitTree.Node.leaves() 100.00% (9/9)
SplitTree.makeIterator() 100.00% (3/3)
implicit closure #1 in SplitTree.makeIterator() 100.00% (1/1)
SplitTree.Node.makeIterator() 0.00% (0/3)
SplitTree.startIndex.getter 100.00% (3/3)
SplitTree.endIndex.getter 100.00% (3/3)
implicit closure #1 in SplitTree.endIndex.getter 100.00% (1/1)
SplitTree.subscript.getter 100.00% (5/5)
implicit closure #1 in SplitTree.subscript.getter 100.00% (1/1)
implicit closure #2 in implicit closure #1 in SplitTree.subscript.getter
100.00% (1/1)
implicit closure #3 in SplitTree.subscript.getter 0.00% (0/1)
implicit closure #4 in SplitTree.subscript.getter 0.00% (0/1)
SplitTree.index(after:) 100.00% (4/4)
implicit closure #1 in SplitTree.index(after:) 100.00% (1/1)
implicit closure #2 in SplitTree.index(after:) 0.00% (0/1)
SplitTree.Node.structuralIdentity.getter 100.00% (3/3)
SplitTree.Node.StructuralIdentity.init(_:) 100.00% (3/3)
static SplitTree.Node.StructuralIdentity.== infix(_:_:) 100.00% (3/3)
SplitTree.Node.StructuralIdentity.hash(into:) 100.00% (3/3)
SplitTree.Node.isStructurallyEqual(to:) 100.00% (18/18)
implicit closure #1 in SplitTree.Node.isStructurallyEqual(to:) 100.00%
(1/1)
implicit closure #2 in SplitTree.Node.isStructurallyEqual(to:) 100.00%
(1/1)
SplitTree.Node.hashStructure(into:) 100.00% (14/14)
SplitTree.structuralIdentity.getter 100.00% (3/3)
SplitTree.StructuralIdentity.init(_:) 100.00% (4/4)
static SplitTree.StructuralIdentity.== infix(_:_:) 100.00% (4/4)
implicit closure #1 in static SplitTree.StructuralIdentity.==
infix(_:_:) 100.00% (1/1)
SplitTree.StructuralIdentity.hash(into:) 80.00% (8/10)
static SplitTree.StructuralIdentity.areNodesStructurallyEqual(_:_:)
90.00% (9/10)
  </pre>
</details>

I chose this as a good place to start contributing to Ghostty because I
was curious about the macOS implementation, and there was a specific
request for help with testing (#7879).

My process for writing the tests was basically reading
[SplitTree.swift](./macos/Sources/Features/Splits/SplitTree.swift) to
understand it, then writing tests for each high-level method and
checking against code coverage to capture all the code paths:

## Running
```bash
rm -rf /tmp/ghostty-test.xcresult
xcodebuild -project macos/Ghostty.xcodeproj \
    -scheme GhosttyTest \
    -configuration Debug \
    test \
    -destination 'platform=macOS' \
    -enableCodeCoverage YES \
    -resultBundlePath /tmp/ghostty-test.xcresult \
    -only-testing:GhosttyTests/SplitTreeTests \
    2>&1 | xcbeautify
```

## Coverage
```bash
xcrun xccov view --report /tmp/ghostty-test.xcresult | grep 'SplitTree\.'
```

This was originally implemented in [~38
commits](https://github.com/pouwerkerk/ghostty/pull/1/commits), but I
squashed them down to 1 commit for easier review.

## AI Disclosure
The tests were written by me, but I used Opus 4.6 to explain some parts
of the code, and then finally to provide feedback on the tests. It
suggested tests for `nodeStructuralIdentityInSet` and
`nodeStructuralIdentityDistinguishesLeaves` as well as [the
Parameterized
test](pouwerkerk@6a0bca4),
`resizingAdjustsRatio`, which seemed like a clever way to collapse 12
individual tests into 3 parameterized ones that still run 12 cases
total. I didn't know this feature existed, and it seems like a great way
to write tests that are more maintainable. I read this relatively new
feature in the [Swift
Docs](https://developer.apple.com/documentation/testing/parameterizedtesting).
I find this to be a particularly useful feature of Claude/related
agents, where it can suggest better ways of writing something in a more
idiomatic way, and it taught me something new, which is always fun.

I'm more than happy to continue work on tests for #7879 and always
welcome to any feedback you have.
NianDUI pushed a commit to NianDUI/ghostty that referenced this pull request May 3, 2026
Section 1 macOS:

- Done now lists the close-code-aware reconnect path: handleDisconnect
  reads URLSessionWebSocketTask.closeCode, disconnectAction recognizes
  4401 (tokenExpired) and resets the backoff for an immediate
  reconnect, 4408 (timeoutOrSlow) keeps the standard exponential
  ramp. Covered by the new controllerRecoveryDisconnectAction*
  Swift Testing cases.
- Remaining drops the corresponding P0 ("Token refresh / re-register
  flow when a long-lived session approaches its TTL"). The relay's
  4401 close + the host's reset-and-reconnect now closes that loop
  without user action.

E2E flow step 11 promoted from ⚠️ to ✅: the relay → host → browser
round-trip on token expiry is now end-to-end automatic.

Section 6 macOS P0 (`SessionSharingController` fake-driven tests):

- Annotated with the architectural blocker. The controller is
  file-private and constructs through Ghostty.SurfaceView (NSView
  subclass requiring a real ghostty_app_t opaque pointer), so a
  proper component-level test suite needs splitting the controller
  into an internal SessionSharingControllerCore (state machine +
  collaborator orchestration, no NSView dependency) wrapped by the
  current AppKit class. That refactor is now an explicit
  Recommended Next Step (ghostty-org#2) ahead of any further controller-level
  test work.
- Recommended Next Steps reordered: mobile IME stays ghostty-org#1, the
  controller-core refactor is ghostty-org#2 (precondition), browser smoke
  becomes ghostty-org#3 (gated on IME), GTK / persistence trigger-gated ghostty-org#4.
DAmesberger added a commit to DAmesberger/ghostty that referenced this pull request May 22, 2026
Four open items from the consolidated reviewer brief.

Issue ghostty-org#1 (MUST FIX) — broadcastConnectionState lock-nesting
SshConnectionManager.zig:720 nested listener_mutex inside surfaces_mutex
even though both the design and the commit message documented them as
independent. Scope-block the surface fan-out so its defer releases
surfaces_mutex before listener_mutex is acquired. Also adopt the
stricter posture: dupe the listeners slice under listener_mutex and
release the lock BEFORE invoking callbacks — listeners that re-enter
the listener API from inside on_state (e.g. an embedder that
unregisters from its own callback) would otherwise deadlock.
Allocation-failure fallback iterates under the lock with the deadlock
risk documented inline.

Issue ghostty-org#2 (MUST FIX) — ssh_listeners leak in SshConnectionManager.release
The Entry-teardown path on `release` (last ref dropped) destroyed the
Entry without deinit'ing ssh_listeners — only Manager.deinit at app
shutdown cleaned them up. Long-running session-manager processes
leaked the ArrayListUnmanaged backing buffer once per Entry. Added
the deinit call immediately before entry destroy.

Issue ghostty-org#3 (MUST FIX) — translateState dangling password.host pointer
The password_required prong was returning a State whose host pointer
referenced the switch-prong local's stack frame, which is dead as
soon as translateState returns. The fix:

  * translateState's password_required branch now returns
    `host = ""` (no dangling pointer, exhaustive testing still passes).
  * New helper SshHandle.emitStateFromConnectionState() runs
    translateState, then for password_required copies the host
    bytes from the ConnectionState argument (whose lifetime extends
    through the broadcast call) into a handle-owned stable buffer
    (`last_password_host: [129]u8`) under SshHandle.mutex, NUL-
    terminates, rewrites state.payload.password.host to point at
    the stable storage, and only THEN releases the mutex before
    firing the embedder callback. Buffer lifetime: valid for the
    callback duration AND until the next PASSWORD_REQUIRED arrives.
  * Mutex released BEFORE the callback so embedders can call
    entry points (which take SshHandle.mutex) from inside on_state
    without deadlocking. Two concurrent password_required broadcasts
    on the same handle are impossible today because the manager
    serializes listener fan-out on the SSH thread.
  * onStateListener now uses the new helper.
  * Regression test forces stack reuse between the broadcast call
    and the host-bytes assertion — distinctive 0xAB pattern written
    into an 8 KiB stack frame after the broadcast returns. The
    embedder's recorded copy must still equal the input host.
  * Second test asserts the buffer survives across a non-password
    state (e.g. CONNECTED) and is rewritten by a subsequent
    PASSWORD_REQUIRED, locking down the documented lifetime.
  * Old "carries host" test rewritten to assert translateState
    alone returns "" for the host (catches re-introduction of the
    dangling pointer at the source).

Issue ghostty-org#6 (MUST FIX) — threading doc widening for synchronous FAILED
ghostty_ssh_open emits emitState(.failed) synchronously on four error
branches (mgr.acquire, dupe(target), dupe(jump), registerStateListener)
before returning, but the threading exception paragraph only mentioned
the initial CONNECTING. Broadened the wording in three places — the
THREADING & OWNERSHIP RULES preamble in include/ghostty.h, the
ghostty_ssh_open declaration comment, and the mirrored module doc
block in ssh_capi.zig — to call out that FAILED transitions may also
fire synchronously on the open caller's thread.

Build verification: aarch64-linux-gnu cross-compile, app-runtime=none
→ 87/87 steps succeeded. Daemon target → 83/83 succeeded. C header
syntax check via `cc -fsyntax-only -Wall -x c` clean. Zig
ast-check clean on both edited Zig files. macOS test target
remains blocked on the pre-existing Metal Toolchain gap; the new
tests will run on reviewer's metal-equipped CI.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ehs5 added a commit to ehs5/ghostty that referenced this pull request Aug 8, 2026
Adds coastty's attention sidebar directly into Ghostty's own terminal
window as a split-view pane, wrapping the existing terminal content
(native tabs untouched) as the other pane — per the ticket's final
architecture correction on ghostty-org#2.

- CoastySidebarModel: pure data model (CoastySpace, CoastyAgentTab,
  CoastyAgentStatus, CoastySidebarModel.agentRows) with the
  red > green > working > checkmark aggregation priority from the
  visual reference (`prototype/sidebar-design` branch in the coastty
  repo, variant C). Covered by CoastySidebarModelTests.
- CoastyStatusIconView: the four status icons reproduced exactly —
  green/checkmark/red as plain circles (no glow), working as a small
  square outline whose dashed stroke animates around its actual
  perimeter (real corners, not a smooth rotation).
- CoastySidebarView: "Spaces" (one collapsed row per workspace, no
  nested tab list) and "Agents" (two-line `folder · tab` / agent-name
  rows), split by a real draggable divider that defaults to giving
  "Agents" exactly the bottom half and persists its ratio
  (CoastySidebarSplitRatioStore, backed by UserDefaults).
- CoastySplitView / CoastyTerminalSplitViewController: the outer
  NSSplitViewController wiring the sidebar (fixed 260pt width, matching
  the reference's non-resizable sidebar) alongside the terminal pane.
  Forwards intrinsicContentSize to the terminal pane so
  window-width/height config and "Return to Default Size" keep working
  now that the terminal container is nested one level deeper.
- TerminalController: installs the split view in windowDidLoad instead
  of setting the terminal container directly as contentView; builds the
  sidebar's data model from this window's own native tabs (no agent
  status yet — wiring real detected workspace/agent state is the next
  ticket, per this ticket's own scope) and refreshes it from
  relabelTabs() whenever the tab list changes.
- TerminalViewContainer.terminalViewContainer: now also finds the
  container nested inside the sidebar split view, so glass-effect and
  appearance sync (which read `window.contentView` directly) keep
  working for sidebar-bearing windows.

Verified: `xcodebuild ... build` succeeds, `CoastySidebarModelTests`
pass, and the built Ghostty.app launches, shows the sidebar with real
tabs open, and exits cleanly with no crash log.

Not in scope here (explicitly deferred by the ticket): wiring the
sidebar to real detected workspace/agent state.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WSiMu3mfaPBs7sL95JCvV2
RIvance referenced this pull request in RIvance/ghostty-with-sidebar Oct 3, 2026
Add dim inactive tab colors toggle and fix red/pink distinction
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