Skip to content

feat: add existing-only session attach - #22

Merged
serabi merged 56 commits into
mainfrom
feat/attach-existing
Nov 7, 2026
Merged

serabi merged 56 commits into
mainfrom
feat/attach-existing

Conversation

@edequalsawesome

@edequalsawesome edequalsawesome commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Why

Attach to an existing session without creating a replacement. This also brings the session leadership work already used by awesoMux onto main.

What's Included

  • Add attach --existing. It verifies a responsive daemon and reuses the verified connection. Ordinary attach keeps its best-effort identity probe.
  • Encode list paths and commands as cwd_b64 and cmd_b64, and reserve metadata label names so tabs and newlines cannot add false records.
  • Add watch-only attachments, explicit takeover, ordered input and size changes, and recovery when the leader disconnects.
  • Keep CSI arrows, Home, End, and Shift-Tab as keyboard input. Exclude arrow sequences with intermediates and kitty status replies.
  • Add socket leadership and session creation tests, preserve the frozen wire layout, and document the behavior in LEADERSHIP.md.
  • List the fork additions in the README. Clarify that a blocked PTY write can leave recovery queued during snapshot serialization, and that only an actual leader change changes the reply epoch for ordinary input.

UI / UX

Not applicable. This changes backend session and terminal behavior.

Notes

Models: Codex

Merge risk: high. This changes session leadership and live-daemon behavior; old/new daemon pairs and the rebased revision through awesoMux have not been checked. Recovery: revert for future builds; running daemons keep their state, and sent input or ended work cannot be restored.

Rebased onto main with merge topology retained. The kitty status fix was already on main; its duplicate was dropped. A GPT-6.1 Sol source review at 250dad4 found no defects. The 16 older Kody threads remain resolved; the newer src/loop.zig:1268 thread remains open for Sarah. The fork-fit review judged that path unreachable. The managed summary below retains older wording. eD! left review comments, but no human approval is recorded.

Current-head check: git diff --check passes. Changes since 250dad4 are documentation only; runtime source is unchanged. At 250dad4, macOS Zig 0.16 formatting, unit tests, build, 3 reattach cases, 49 CLI/session cases, 21 leadership regression scenarios, 24 creator scenarios, and the main leadership harness passed. These are prior-head results. No new physical-device or awesoMux runtime result is claimed.

Original heads and downstream pins are preserved in task notes and safety refs. Keep the remote tags awesomux-pin-cc24771 and awesomux-pin-ffa16fa. Merge with a merge commit and keep the branches.

Summary

Adds attach --existing for attaching only to an already-responsive session, plus a new read-only watch <name> client and a typed attachment/authority protocol for the daemon. The change also replaces the single PTY write buffer with a bounded, ordered operation queue and hardens session-list and label output framing.

What Changed

  • Existing-only attach

    • zmx attach --existing <name> verifies the session socket exists and the daemon responds before attaching.
    • It never creates a replacement session, removes an unresponsive socket, or falls back to creation.
    • --existing is rejected with --labels.
    • The verified probe socket is reused as the attach socket to avoid a second race-prone connection.
  • watch <name>

    • Connects to an existing session only and sends AttachRole as watch.
    • Requires positive AttachAccepted within one second; old daemons fail closed with no legacy fallback.
    • Sends no Init, stdin, focus, resize, or terminal replies.
    • Writes session output to stdout and authority diagnostics to stderr.
    • Watch role is restricted to Authority, Info, History, CwdQuery, LabelGet, and Detach; it cannot mutate labels/env, inject output, resize, take over, or kill.
  • Typed roles and authority

    • Adds IPC tags 26–33 for attachment roles, authority, user batches, terminal replies, takeover, requested size, and downgrade.
    • Clients receive an attachment ID and revision; typed operations must match them.
    • Terminal replies are accepted only from the current interactive leader and only for the current authority epoch.
    • Disconnect, downgrade, explicit takeover, and actual leader changes update authority/ownership epochs and invalidate stale queued replies or resizes.
    • Downgrade converts an interactive client to permanent watch, drops its unforwarded operations, and clears leadership.
    • Automation is classified before Init through Send, Run, Write, or Output; it permanently loses session-creation eligibility but normal user input can still claim leadership.
    • Non-task sessions keep a one-use creation right for the first valid terminal handshake; watch and automation never consume it.
  • Leaderless recovery

    • Applies only to legacy terminal attachments that are not automation.
    • Queues an ordered recovery claim when a leaderless legacy pane resizes or reattaches.
    • Elects the most recently attached/resized Mac pane on disconnect or downgrade.
    • A dropped typed leader holds leadership open for 5 seconds before Mac-pane recovery to avoid double reflow on reconnect.
    • Typed attachments, watch clients, and automation never recover leadership.
  • Ordered PTY operation queue

    • Replaces pty_write_buf with a bounded queue: 256 KiB payload and 4096 operations.
    • Reserves capacity and payload ownership before accepting new work.
    • Applies user/takeover sizing at the first byte or empty takeover barrier.
    • A partially written batch holds the queue head; later input, resize, and takeover cannot overtake it.
    • Queue-full rejects the new operation without claiming leadership or evicting accepted work.
    • No automatic retry, replay, or per-batch acknowledgment.
  • Input and parser hardening

    • Rejects invalid resize dimensions outside 1–4096.
    • History accepts only an empty payload or exactly one supported format byte; malformed requests are ignored.
    • Legacy input classification now recognizes bare C0 controls except ESC, DEL, ordinary/modified CSI arrows, Shift-Tab, and Home/End, while excluding intermediate CSI sequences and terminal replies.
  • List and label framing

    • list now emits cwd_b64 and cmd_b64 instead of raw cwd and cmd; no raw compatibility aliases are emitted.
    • Base64 framing prevents tabs/newlines in paths or commands from injecting extra list fields or records.
    • Reserved label keys are expanded to cover all list/status fields, preventing label collisions with name, pid, clients, created, cwd, cmd, daemon_pid, status, etc.
    • README picker example now uses list --short.
  • Tests and docs

    • Adds real-socket leadership, creator-order, and regression harnesses covering watch mutation bypasses, typed/legacy handshakes, queue saturation, reply epochs, downgrade/disconnect revocation, Mac-pane recovery, resize ordering, and existing-only verification.
    • Updates reattach tests for snapshot grid layout and SIGWINCH behavior.

Security Impact

  • Existing-only attach avoids stale-socket deletion and unintended session creation.
  • Watch is allowlisted, so a read-only client cannot mutate labels/env, inject output, resize, take over, kill sessions, or send terminal replies.
  • Typed handshakes require positive capability acceptance; old-daemon fallback is removed for watch.
  • Reply forwarding is gated by leader identity and authority epoch.
  • Disconnect/downgrade removes unforwarded queued operations.
  • List output and reserved labels close metadata-injection and field-collision paths.
  • Queue bounds and size validation prevent unbounded memory growth and absurd terminal dimensions from being accepted.

Performance / Behavior Impact

  • Introduces deliberate head-of-line ordering for PTY writes; a blocked partial batch can delay later input and resize until drained.
  • Queue saturation now rejects new work instead of growing or evicting accepted work.
  • Typed leader disconnect adds a 5-second recovery grace period.
  • Operation flushing scans clients and operation state; dropSource and queueResize also perform linear scans, which may matter under heavy multi-client/queue pressure.

Review Notes / Cleanup Opportunities

  • The branch title is existing-only attach, but the change also adds a broad typed protocol, authority system, bounded queue, docs, and large test harnesses. This is significant scope creep for the title; consider splitting if the typed protocol is not required for the existing-only feature.
  • writeSessionLine allocates a fresh page_allocator buffer for each cwd_b64/cmd_b64 field. A reusable buffer or direct writer-based encoding would be simpler and lighter for list.
  • queueOperation heap-duplicates every payload, including empty barrier operations. Avoiding allocations for empty data would reduce churn.
  • The long inline queueOperation call in handleTyped and the large role-dispatch block are hard to audit; smaller helpers would improve maintainability.
  • The new Python harnesses are large and duplicate fixture/setup patterns across leadership.py, creator_leadership.py, and leadership_regressions.py. Consolidating shared helpers would reduce maintenance cost.
  • LEADERSHIP.md is detailed but very long and overlaps heavily with test expectations; keep it as the protocol contract only, not a second behavioral test log.

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

@kody-ai

kody-ai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Code Review Could Not Complete ⚠️

The review failed before suggestions could be generated.

Reason: Rate limit reached on the provider (openai_compatible). Try again in a few minutes.

openai_compatible · hf:deepseek-ai/DeepSeek-V4.1-Flash · generalist

After fixing the issue, comment @kody review on this PR to re-run the review.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the @kody start-review command at the root of your PR.

  • Validate Business Logic: Ask Kody to validate your code against business rules by adding a comment with the @kody -v business-logic command.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ✅

Access your configuration settings here.

​

Comment thread README.md Resolved
Comment thread src/main.zig Resolved
Comment thread src/main.zig Resolved
Comment thread src/main.zig Resolved
@kody-ai

kody-ai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Additional context used: Interactive-Buffoonery/awesomux@main

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the @kody start-review command at the root of your PR.

  • Validate Business Logic: Ask Kody to validate your code against business rules by adding a comment with the @kody -v business-logic command.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ✅

Access your configuration settings here.

​

Comment thread README.md Resolved
Comment thread src/main.zig Resolved
Comment thread src/main.zig Resolved
Comment thread src/main.zig Resolved
Comment thread src/main.zig Resolved
Comment thread src/util.zig Resolved
@kody-ai

kody-ai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

⚠️ Note: some checks couldn't be completed in this run, so auto-approval (when enabled) was skipped. Check the details at https://app.kodus.io/pull-requests and then comment @kody review on this PR to retry once the issue is resolved.

Additional context used: Interactive-Buffoonery/awesomux@main

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the @kody start-review command at the root of your PR.

  • Validate Business Logic: Ask Kody to validate your code against business rules by adding a comment with the @kody -v business-logic command.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ✅

Access your configuration settings here.

​

Comment thread src/main.zig Resolved
Comment thread src/main.zig Resolved
Comment thread src/main.zig Resolved
Comment thread src/main.zig Resolved
@kody-ai

This comment has been minimized.

Comment thread src/main.zig Resolved
Comment thread src/main.zig Resolved
@kody-ai

This comment has been minimized.

@edequalsawesome

Copy link
Copy Markdown
Contributor Author

Review disposition for 480fc5e: the nested-switch finding is fixed and its thread resolved. The auto-generated PR summary still says --existing carries into switch recursion; that sentence is now stale. Existing-only applies to the originally named recovery target, while a later explicit nested switch uses ordinary create-or-attach. The slow-daemon fallback suggestion was not adopted because reconnecting to an unverified peer would break recovery identity fencing; the rationale is in its still-open thread. Zig tests/build and an isolated PTY switch smoke passed. The latest Kody run failed in its review provider before completing, without a new inline code finding.

Add permanently restricted typed attachments and explicit takeover while
preserving frozen legacy tags. Serialize size claims and user batches
through owned PTY operations and invalidate stale replies on epoch changes.

Keep legacy attach's mixed-stdin limitation explicit. Add socket regression
coverage and update retained-grid reattach expectations.

Refs: Interactive-Buffoonery/awesomux#827
serabi added 21 commits November 6, 2026 23:41
A reattached Mac pane, or one left behind when the phone stops leading,
dropped every resize until the user typed. Full-screen apps kept drawing
at the old width and garbled.

While no client leads, a legacy terminal attachment's Init or Resize now
queues an ordered recovery claim at its requested size. When the leader
leaves and exactly one such attachment remains, it claims too. Typed
attachments, Watch and automation keep explicit claims.
A leaderless session now elects the Mac pane whose Init, Resize or
ResizePixels arrived most recently, instead of only a sole survivor.
awesoMux sends a pane's attach client SIGWINCH on focus, so the pane
the user last looked at wins.

A typed leader whose socket closes holds the session leaderless for
5 seconds first, so a phone that reconnects and claims again reflows
the grid once. Any claim ends the wait; downgrades still elect at once.
…adership

fix(pty): restore initial creator leadership
…ize-claim

fix(pty): let Mac panes lead a leaderless session
…f-followups

feat(pty): hand a dropped phone's grid to the last-focused pane
@serabi
serabi force-pushed the feat/attach-existing branch from 0f1ac1f to 250dad4 Compare November 7, 2026 04:46
@kody-ai

This comment has been minimized.

@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown

External contributor checklist

Thanks for contributing. A maintainer will handle the trusted checks and final merge.

  • A maintainer has reviewed the change.
  • The PR description follows the template.
  • Visible changes include screenshots or a clear not-applicable explanation.
  • A maintainer confirmed no untrusted fork code was run with repository secrets.

@github-actions github-actions Bot added the size:XXL 1,000+ effective changed lines. label Nov 7, 2026
@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Large pull request

This PR has 1215 effective changed lines and is labeled size:XXL.
The label is informational and does not block merging. Please consider splitting the
change where practical so each part is easier to review. See CONTRIBUTING.md for
the project's small-PR guidance.

Comment thread src/loop.zig Resolved
@kody-ai

kody-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Kody Review Complete

Great news! 🎉
No issues were found that match your current review configurations.

Keep up the excellent work! 🚀

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the @kody start-review command at the root of your PR.

  • Validate Business Logic: Ask Kody to validate your code against business rules by adding a comment with the @kody -v business-logic command.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Access your configuration settings here.

​

@serabi
serabi merged commit 347243d into main Nov 7, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XXL 1,000+ effective changed lines.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants