Skip to content

Conversation

@jellydn
Copy link

@jellydn jellydn commented Sep 7, 2025

Summary

πŸ”„ Stack PR: This builds on PR #202 and should be merged after #202

🎯 Major Features

βœ… Toast notifications for resume operations (worktree setup feedback)
βœ… Toast notifications for pause/checkout operations (worktree cleanup feedback)
βœ… Configurable toast dismiss timeouts via user configuration
βœ… Unified 3-second default timeout for better readability

🚨 Critical Bug Fix

βœ… Fixed session auto-deletion after terminal restart - Previously, closing terminal tab and restarting cs would auto-pause and delete existing sessions. This is now fixed.

Changes

πŸ†• New Operations Coverage

  • Resume Operations (app.go:811-817): Shows "Resuming session..." β†’ "Session resumed successfully!"
  • Pause/Checkout Operations (app.go:796-802): Shows "Pausing session..." β†’ "Session paused successfully!"

πŸ› Critical Bug Fix Details

Problem: After terminal restart, sessions were being deleted instead of recovered
Root Cause: Start(false) directly called tmuxSession.Restore() without checking if tmux session exists
Solution: Added proper session existence check like Resume() method - creates new tmux session if old one is gone

Impact: Sessions now survive terminal restarts instead of being destroyed

βš™οΈ Configurable Timeouts

Users can customize toast durations in ~/.claude-squad/config.json:

{
  "toast_timeouts": {
    "info": 3000,    // milliseconds (3 seconds default)
    "success": 3000, // milliseconds (3 seconds default) 
    "warning": 3000, // milliseconds (3 seconds default)
    "error": 3000    // milliseconds (3 seconds default)
  }
}

πŸ“š Enhanced Documentation

  • Updated ADR with new features and configuration options
  • Documented integration points for resume/pause operations
  • Added configuration examples and usage guidelines

Technical Implementation

Config System Integration

  • Added ToastTimeouts struct to main Config with JSON serialization
  • Updated NewToastManager(config) to accept configuration
  • Modified timeout logic to use config values instead of hardcoded durations

Session Recovery Fix

// Before: Direct restore (fails after terminal restart)  
if err := tmuxSession.Restore(); err != nil {
    return err  // This would kill the session
}

// After: Check existence first (survives terminal restart)
if tmuxSession.DoesSessionExist() {
    tmuxSession.Restore()  // Restore if exists
} else {
    tmuxSession.Start()    // Create new if gone
}

Test Plan

  • All existing tests pass with configurable toast manager
  • Resume operations show appropriate toast feedback
  • Pause/checkout operations show appropriate toast feedback
  • Config system loads and applies custom timeouts correctly
  • Default 3-second timeout provides optimal user experience
  • Session recovery works after terminal restart
  • Test files updated to use config.DefaultConfig() for initialization

Stack Dependencies

⚠️ Merge Order:

  1. ⬅️ Base Toast System: Add 'b' key for branch-based session creationΒ #202
  2. ➑️ This PR: Configurable timeouts + resume/pause operations + session recovery fix

Files Changed

  • config/config.go - Added toast timeout configuration
  • ui/overlay/toast.go - Enhanced with configurable timeouts
  • app/app.go - Added resume/pause operation toasts
  • session/instance.go - Fixed session recovery after terminal restart
  • docs/adr/001-toast-notifications.md - Updated documentation
  • Test files - Updated for configurable toast manager

πŸ€– Generated with Claude Code

jellydn and others added 10 commits August 30, 2025 13:43
Add comprehensive branch workflow with three-step process:
1. Session name input (same as 'n' key)
2. Branch name input (e.g., feat/new-feature)
3. Source branch selection (with smart defaults)

Key improvements:
- Fix modal display issues by switching from textarea to textinput
- Fix title setting timing to prevent "cannot change title" errors
- Remove branch prefix for user-specified names (respect exact input)
- Convert if-else chains to tagged switches for better linting
- Fix all import issues and errcheck warnings

πŸ€– Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
…rvation

This commit implements two major enhancements to the branch creation workflow:

## 1. Remote Branch Sync Detection and Confirmation

### Source Branch Sync Check
- Check if source branch (the "from" branch) needs sync with remote origin
- Prompt user: "Source branch 'main' is out of sync with remote. Sync before creating? (y/n)"
- Prevents creating branches from outdated local source branches

### Target Branch Sync Check
- Check if target branch name already exists on remote with different commits
- Prompt user: "Target branch 'feature' has different commits. Sync before creating? (y/n)"
- Ensures branch creation uses most up-to-date remote state

### Implementation Details
- Added `CheckRemoteBranchStatic()` and `SyncWithRemoteBranchStatic()` static methods
- Enhanced `stateSourceBranch` workflow with two-stage sync confirmation
- Added new helper methods: `syncSourceThenCheckTarget()`, `checkTargetBranchAndProceed()`
- Uses `stateSyncConfirm` state with contextual confirmation overlays

## 2. Session Name Preservation

### Problem Fixed
- 'b' key workflow was overwriting user session names with branch names
- User enters session name "my-auth-session" but gets "feat/auth-flow" instead

### Solution
- Modified `finalizeBranchCreation()` to only set branch name as title when no title exists
- Preserves user-entered session names from 'b' key workflow
- Maintains backward compatibility for direct branch creation

## Key Files Changed

### Core Logic
- `app/app.go`: Enhanced branch creation workflow with remote sync checks
- `session/git/worktree_ops.go`: Added static remote branch checking methods
- `session/instance.go`: Added wrapper functions for static git operations

### Tests Added
- `app/branch_sync_test.go`: Comprehensive tests for sync functionality and session preservation
- `session/git/util_test.go`: Tests for remote branch detection and sync operations

## User Experience Flow

**Before**:
```
1. Press 'b' β†’ Enter session name β†’ Enter branch β†’ Session renamed to branch name
2. No remote sync checking β†’ potential outdated branches
```

**After**:
```
1. Press 'b' β†’ Enter session name β†’ Enter branch name
2. Check source branch sync β†’ Optional sync source
3. Check target branch sync β†’ Optional sync target
4. Create session with preserved name and up-to-date branches
```

This enhancement ensures branch creation workflows are more reliable and user-friendly by preventing common git sync issues and respecting user session naming choices.

πŸ€– Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
This commit fixes an issue where using the same branch name for both source
and target in branch creation workflow would cause problems.

## Problem
When a user enters the same branch name for both "from branch" and "new branch":
- System tried to create a "new" branch with existing name
- Showed confusing sync confirmation for non-existent new branch
- Could fail or create unexpected behavior
- Session would be empty/broken after sync confirmation

## Solution
Added intelligent detection for same-branch scenario:

### Edge Case Detection
```go
if sourceBranch == m.pendingBranchName {
    // This is existing branch checkout, not new branch creation
    return m.handleSameBranchCheckout(selected, sourceBranch)
}
```

### New Workflow for Same Branch Names
1. **`handleSameBranchCheckout()`** - Detects this is existing branch operation
2. **Single sync check** - Only check if the existing branch needs sync
3. **`finalizeExistingBranchCheckout()`** - Sets up session with existing branch
4. **Clear messaging** - "Branch 'main' is out of sync. Sync before checkout? (y/n)"

### Key Differences from New Branch Creation
- **No new branch creation** - Uses existing branch directly
- **Single sync check** - Only one confirmation instead of two
- **Checkout vs Create** - Language reflects the actual operation
- **Source = Target** - Both CustomBranch and SourceBranch set to same value

## Implementation Details

### Methods Added
- `handleSameBranchCheckout()` - Entry point for same-branch scenario
- `finalizeSameBranchCheckout()` - Handles sync then checkout
- `finalizeExistingBranchCheckout()` - Final session setup for existing branch

### User Experience
**Before (broken)**:
```
Enter branch: "main" β†’ Enter source: "main"
β†’ "Target branch 'main' has different commits. Sync? (y/n)"
β†’ Empty/broken session
```

**After (fixed)**:
```
Enter branch: "main" β†’ Enter source: "main"
β†’ "Branch 'main' is out of sync with remote. Sync before checkout? (y/n)"
β†’ Working session with branch "main"
```

### Tests Added
- `TestSameBranchEdgeCase` - Comprehensive testing of same-branch scenario
- Verifies no panics, correct branch setup, and session title preservation
- Ensures both CustomBranch and SourceBranch are set to same value

This fix ensures the branch creation workflow handles all valid user inputs
gracefully, including the edge case of checking out existing branches.

πŸ€– Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
…origins

**Problem:**
- After creating branches via 'b' workflow from remote origins, branches lacked proper upstream tracking
- `git pull` would fail with "There is no tracking information for the current branch"
- Users had to manually run `git branch --set-upstream-to=origin/<branch>`

**Root Cause:**
- `setupFromExistingBranch()` created worktrees from remote branches but didn't set upstream tracking
- Both paths (remote-only and local+remote scenarios) missed explicit upstream configuration

**Solution:**
- Added explicit `git branch --set-upstream-to=origin/<branch>` calls in both scenarios:
  1. When local branch doesn't exist but remote does (line 84-87)
  2. When both local and remote exist (line 95-100)
- Added warning logging for tracking setup failures (non-fatal)
- Preserves existing functionality while ensuring proper git pull/push behavior

**Testing:**
- All existing git tests pass (session/git package)
- Fix handles both new and existing branch scenarios
- Graceful degradation with warnings if upstream setup fails

**Files Modified:**
- session/git/worktree_ops.go: Added upstream tracking setup
- .github/ISSUE_TEMPLATE/ux_enhancement.md: Created template for future UX issues

This resolves the git pull tracking issue reported in auth-flow worktree scenario.

πŸ€– Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Applied gofmt formatting to session/git/worktree_ops.go to resolve
make lint-basic errors. No functional changes.

πŸ€– Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
**Enhanced User Experience:**
- Added comprehensive guidance messages when upstream tracking setup fails
- Provides exact command for users to run manually: `git branch --set-upstream-to=origin/<branch> <branch>`
- Created reusable helper function `showUpstreamTrackingMessage()` for consistent messaging
- Improved error messages in worktree setup with actionable instructions

**Key Improvements:**
1. **Helpful Error Messages**: Replace generic warnings with specific guidance
2. **User Empowerment**: Show exact commands to fix tracking issues manually
3. **Edge Case Support**: Especially beneficial for same-name branch scenarios
4. **Consistent UX**: Standardized messaging across different failure modes

**User Journey Enhancement:**
```
Before: "Warning: failed to set upstream tracking for branch feature: exit status 128"
After:  "Warning: Unable to automatically set upstream tracking for branch 'feature'.
        To enable git pull/push, run this command in your worktree:
          git branch --set-upstream-to=origin/feature feature"
```

**Files Modified:**
- session/git/worktree_ops.go: Enhanced error messages with actionable guidance
- app/app.go: Added helper function for consistent upstream tracking messages

This addresses user feedback about needing manual upstream tracking setup,
especially after sync confirmations and in same-name branch edge cases.

πŸ€– Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
…tional operations

- Add toast notifications for resume operations (worktree setup feedback)
- Add toast notifications for pause/checkout operations (worktree cleanup feedback)
- Make toast dismiss timeout configurable via user config (~/.claude-squad/config.json)
- Set unified 3-second default timeout for all toast types
- Update ADR documentation with new features and configuration options
- Update all tests to use configurable toast manager

Enhances user experience by providing feedback for all long-running git operations
with customizable timing preferences.

πŸ€– Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Fix critical bug where closing terminal tab and restarting `cs` would
auto-pause and delete existing sessions.

Root cause: Start(false) directly called tmuxSession.Restore() without
checking if tmux session still exists after terminal restart. When restore
failed, the defer cleanup would delete the instance entirely.

Solution: Apply same pattern as Resume() method - check DoesSessionExist()
first and create new session if tmux session is gone instead of failing.

This allows sessions to survive terminal restarts by recreating the tmux
session instead of destroying the entire session.

πŸ€– Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
@jellydn jellydn closed this Sep 23, 2025
@github-actions github-actions bot locked and limited conversation to collaborators Sep 23, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant