diff --git a/cmd/agent-desk/main.go b/cmd/agent-desk/main.go index a45570e8..1eb8fcfd 100644 --- a/cmd/agent-desk/main.go +++ b/cmd/agent-desk/main.go @@ -860,6 +860,11 @@ func handleAdd(profile string, args []string) { } } + if err := newInstance.PrepareCopilotSession(); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + os.Exit(1) + } + // Add to instances instances = append(instances, newInstance) @@ -1816,6 +1821,9 @@ func detectTool(cmd string) string { } cmd = strings.ToLower(cmd) + if fields := strings.Fields(cmd); len(fields) > 0 && filepath.Base(fields[0]) == "copilot" { + return "copilot" + } switch { case strings.Contains(cmd, "claude"): return "claude" diff --git a/cmd/agent-desk/session_cmd.go b/cmd/agent-desk/session_cmd.go index df8841a2..ba3764f5 100644 --- a/cmd/agent-desk/session_cmd.go +++ b/cmd/agent-desk/session_cmd.go @@ -98,6 +98,7 @@ func printSessionHelp() { fmt.Println(" wrapper Wrapper command (use {command} to include tool command)") fmt.Println(" claude-session-id Claude conversation ID (for resume)") fmt.Println(" gemini-session-id Gemini conversation ID (for resume)") + fmt.Println(" copilot-session-id Copilot conversation UUID (for recovery)") fmt.Println() fmt.Println("Set examples:") fmt.Println(" agent-desk session set my-project title \"New Title\"") @@ -199,6 +200,9 @@ func handleSessionStart(profile string, args []string) { if inst.ClaudeSessionID != "" { jsonData["claude_session_id"] = inst.ClaudeSessionID } + if inst.CopilotSessionID != "" { + jsonData["copilot_session_id"] = inst.CopilotSessionID + } if initialMessage != "" { jsonData["message"] = initialMessage jsonData["message_pending"] = true @@ -486,6 +490,10 @@ func handleSessionShow(profile string, args []string) { if inst.Command != "" { jsonData["command"] = inst.Command } + if inst.Tool == "copilot" { + jsonData["copilot_session_id"] = inst.CopilotSessionID + jsonData["needs_recovery"] = inst.CopilotSessionID == "" + } if inst.Tool == "claude" { jsonData["claude_session_id"] = inst.ClaudeSessionID @@ -521,6 +529,13 @@ func handleSessionShow(profile string, args []string) { } sb.WriteString(fmt.Sprintf("Tool: %s\n", inst.Tool)) + if inst.Tool == "copilot" { + if inst.CopilotSessionID == "" { + sb.WriteString("Copilot: not linked (press R to recover)\n") + } else { + fmt.Fprintf(&sb, "Copilot: %s\n", inst.CopilotSessionID) + } + } if inst.Command != "" { sb.WriteString(fmt.Sprintf("Command: %s\n", inst.Command)) @@ -588,6 +603,7 @@ func handleSessionSet(profile string, args []string) { fmt.Println(" wrapper Wrapper command (use {command} to include tool command)") fmt.Println(" claude-session-id Claude conversation ID") fmt.Println(" gemini-session-id Gemini conversation ID") + fmt.Println(" copilot-session-id Copilot conversation UUID (for recovery)") fmt.Println() fmt.Println("Options:") fs.PrintDefaults() @@ -616,19 +632,20 @@ func handleSessionSet(profile string, args []string) { // Validate field name validFields := map[string]bool{ - "title": true, - "path": true, - "command": true, - "tool": true, - "wrapper": true, - "claude-session-id": true, - "gemini-session-id": true, + "title": true, + "path": true, + "command": true, + "tool": true, + "wrapper": true, + "claude-session-id": true, + "gemini-session-id": true, + "copilot-session-id": true, } if !validFields[field] { out.Error( fmt.Sprintf( - "invalid field: %s\nValid fields: title, path, command, tool, wrapper, claude-session-id, gemini-session-id", + "invalid field: %s\nValid fields: title, path, command, tool, wrapper, claude-session-id, gemini-session-id, copilot-session-id", field, ), ErrCodeInvalidOperation, @@ -675,6 +692,12 @@ func handleSessionSet(profile string, args []string) { case "wrapper": oldValue = inst.Wrapper inst.Wrapper = value + case "copilot-session-id": + oldValue = inst.CopilotSessionID + if err := inst.BindCopilotConversation(value); err != nil { + out.Error(err.Error(), ErrCodeInvalidOperation) + os.Exit(1) + } case "claude-session-id": oldValue = inst.ClaudeSessionID inst.ClaudeSessionID = value diff --git a/docs/copilot-recovery.md b/docs/copilot-recovery.md new file mode 100644 index 00000000..77dac651 --- /dev/null +++ b/docs/copilot-recovery.md @@ -0,0 +1,57 @@ +# Copilot conversations after a reboot + +Agent Desk's sidebar entries and Copilot's conversation history are persisted +locally. The tmux processes hosting them do not survive a reboot. Restarting an +entry must recreate tmux and resume the correct conversation, not whichever +conversation was used most recently. + +## Recover an existing entry + +Select a Copilot entry and press **Shift+R**. Enter also starts recovery when its +tmux session is gone. + +If the entry has no stored Copilot conversation UUID, a recovery picker opens. +It shows saved conversation names, UUIDs and update times. Type to filter, use +Up/Down to navigate, and Tab to switch between the entry's folder and all folders. +The all-folders option also covers conversations whose working directory changed. +Press Enter to explicitly link and resume the highlighted conversation. Esc +cancels without changing anything. + +The link is saved before restarting. Subsequent restarts use +`copilot --resume=`, including after a reboot. Missing history or a lock +error is reported by Copilot; Agent Desk does not silently start another +conversation or delete lock files. + +For terminal-based recovery: + +```sh +agent-desk session set copilot-session-id +agent-desk session restart +agent-desk session show --json +``` + +The UUID must identify readable local metadata in +`~/.copilot/session-state//workspace.yaml`. Names and folder matches are +discovery aids, never proof that an entry owns a particular conversation. + +## New sessions + +For the standard `copilot` command, Agent Desk allocates a UUID and persists it +before launching `copilot --session-id=`. This requires a Copilot CLI that +supports `--session-id` (checked before launch). Two entries in the same folder +therefore retain distinct identities. + +Custom launch commands are left unchanged. They are not assigned a guessed ID. +Automatic restart refuses to discard or rewrite custom flags; use the standard +`copilot` command for managed recovery, or resume explicitly through the custom +command. Wrappers containing `{command}` continue to wrap managed launch and +resume commands. + +The stored link follows a conversation, not an arbitrary interactive tab. If you +switch to a different conversation inside Copilot with `/new`, `/resume`, or +`/fork`, explicitly rebind the entry using `session set ... copilot-session-id` +to change which conversation Agent Desk will restore. + +Installing a new Agent Desk binary does not update an already-running TUI. +Exit and reopen Agent Desk to use the updated recovery behavior; no Mac reboot +or deletion of Copilot state is needed. diff --git a/go.mod b/go.mod index b2c6c4df..c23d714b 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/charmbracelet/lipgloss v1.1.0 github.com/creack/pty v1.1.24 github.com/fsnotify/fsnotify v1.9.0 + github.com/google/uuid v1.6.0 github.com/mattn/go-runewidth v0.0.16 github.com/muesli/cancelreader v0.2.2 github.com/muesli/termenv v0.16.0 @@ -20,6 +21,7 @@ require ( golang.org/x/term v0.37.0 golang.org/x/time v0.14.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 + gopkg.in/yaml.v3 v3.0.1 modernc.org/sqlite v1.44.3 ) @@ -34,7 +36,6 @@ require ( github.com/dustin/go-humanize v1.0.1 // indirect github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect github.com/godbus/dbus/v5 v5.1.0 // indirect - github.com/google/uuid v1.6.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-localereader v0.0.1 // indirect @@ -46,7 +47,6 @@ require ( golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect golang.org/x/sys v0.38.0 // indirect golang.org/x/text v0.3.8 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect modernc.org/libc v1.67.6 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.11.0 // indirect diff --git a/internal/session/copilot.go b/internal/session/copilot.go new file mode 100644 index 00000000..9bc780b0 --- /dev/null +++ b/internal/session/copilot.go @@ -0,0 +1,198 @@ +package session + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/google/uuid" + "gopkg.in/yaml.v3" +) + +var ErrCopilotRecoveryRequired = errors.New("no Copilot conversation is linked; press R in Agent Desk to choose its saved conversation, or use session set copilot-session-id ") + +type CopilotConversation struct { + ID string `yaml:"id"` + Name string `yaml:"name"` + Cwd string `yaml:"cwd"` + CreatedAt time.Time `yaml:"created_at"` + UpdatedAt time.Time `yaml:"updated_at"` +} + +func copilotStateDir() (string, error) { + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + return filepath.Join(home, ".copilot", "session-state"), nil +} + +func validCopilotID(id string) bool { + parsed, err := uuid.Parse(id) + return err == nil && parsed.String() == id +} + +func readCopilotConversation(root, id string) (CopilotConversation, error) { + var conversation CopilotConversation + if !validCopilotID(id) { + return conversation, fmt.Errorf("invalid Copilot conversation UUID: %q", id) + } + path := filepath.Join(root, id, "workspace.yaml") + info, err := os.Stat(path) + if err != nil { + return conversation, err + } + if info.Size() > 64*1024 { + return conversation, fmt.Errorf("saved Copilot metadata too large: %s", path) + } + data, err := os.ReadFile(path) + if err != nil { + return conversation, err + } + if err := yaml.Unmarshal(data, &conversation); err != nil { + return conversation, fmt.Errorf("read Copilot metadata %s: %w", id, err) + } + if conversation.ID != id { + return conversation, fmt.Errorf("saved Copilot metadata ID does not match directory %s", id) + } + conversation.Name = SanitizeDisplayName(conversation.Name) + if conversation.Name == "" { + conversation.Name = id + } + return conversation, nil +} + +// ListCopilotConversations reads metadata only, never conversation contents. +// Partial failures are returned alongside usable entries so recovery stays available. +func ListCopilotConversations() ([]CopilotConversation, error) { + root, err := copilotStateDir() + if err != nil { + return nil, err + } + entries, err := os.ReadDir(root) + if err != nil { + return nil, fmt.Errorf("list saved Copilot conversations: %w", err) + } + var conversations []CopilotConversation + var failures []error + for _, entry := range entries { + if !entry.IsDir() || !validCopilotID(entry.Name()) { + continue + } + conversation, err := readCopilotConversation(root, entry.Name()) + if err != nil { + failures = append(failures, fmt.Errorf("%s: %w", entry.Name(), err)) + continue + } + conversations = append(conversations, conversation) + } + sort.Slice(conversations, func(a, b int) bool { + if conversations[a].UpdatedAt.Equal(conversations[b].UpdatedAt) { + return conversations[a].ID < conversations[b].ID + } + return conversations[a].UpdatedAt.After(conversations[b].UpdatedAt) + }) + return conversations, errors.Join(failures...) +} + +func (i *Instance) BindCopilotConversation(id string) error { + if i.Tool != "copilot" { + return fmt.Errorf("session is not a Copilot session") + } + root, err := copilotStateDir() + if err != nil { + return err + } + if _, err := readCopilotConversation(root, id); err != nil { + return fmt.Errorf("cannot recover Copilot conversation: %w", err) + } + i.CopilotSessionID = id + i.CopilotSessionPending = false + return nil +} + +// PrepareCopilotSession is for NEW entries only. Existing unlinked entries must +// use recovery rather than silently receiving a new conversation. +func (i *Instance) PrepareCopilotSession() error { + if i.Tool != "copilot" || i.CopilotSessionID != "" || (i.Command != "" && i.Command != "copilot") { + return nil + } + id, err := uuid.NewRandom() + if err != nil { + return fmt.Errorf("allocate Copilot conversation ID: %w", err) + } + i.CopilotSessionID = id.String() + i.CopilotSessionPending = true + return nil +} + +func (i *Instance) validateCopilotLaunch() error { + if i.Tool != "copilot" || (i.Command != "" && i.Command != "copilot") { + return nil + } + if i.CopilotSessionID == "" { + return ErrCopilotRecoveryRequired + } + if !validCopilotID(i.CopilotSessionID) { + return fmt.Errorf("invalid Copilot conversation UUID: %q", i.CopilotSessionID) + } + if err := i.validateCopilotWrapper(); err != nil { + return err + } + if !i.CopilotSessionPending { + return nil + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + help, err := exec.CommandContext(ctx, "copilot", "--help").Output() + if err != nil { + return fmt.Errorf("check Copilot CLI capabilities: %w", err) + } + if !strings.Contains(string(help), "--session-id") { + return fmt.Errorf("this Copilot CLI does not support --session-id; update Copilot before launching a managed session") + } + return nil +} + +func (i *Instance) copilotResumeCommand() (string, error) { + if i.CopilotSessionID == "" { + return "", ErrCopilotRecoveryRequired + } + if !validCopilotID(i.CopilotSessionID) { + return "", fmt.Errorf("invalid Copilot conversation UUID: %q", i.CopilotSessionID) + } + if i.Command != "" && i.Command != "copilot" { + return "", fmt.Errorf("cannot safely rewrite custom Copilot command; set the command to copilot before recovering, or resume the conversation explicitly in your custom command") + } + if err := i.validateCopilotWrapper(); err != nil { + return "", err + } + if i.CopilotSessionPending { + if err := i.validateCopilotLaunch(); err != nil { + return "", err + } + return "copilot --session-id=" + i.CopilotSessionID, nil + } + // Unlike --session-id, --resume must not create a new conversation when + // history has been removed. Let the CLI report missing or locked history. + return "copilot --resume=" + i.CopilotSessionID, nil +} + +func (i *Instance) validateCopilotWrapper() error { + wrapper := i.Wrapper + if wrapper == "" { + if def := GetToolDef(i.Tool); def != nil { + wrapper = def.Wrapper + } + } + if wrapper != "" && !strings.Contains(wrapper, wrapperPlaceholder) { + return fmt.Errorf("the Copilot wrapper must include {command} to preserve the conversation ID") + } + return nil +} diff --git a/internal/session/copilot_test.go b/internal/session/copilot_test.go new file mode 100644 index 00000000..34a081e6 --- /dev/null +++ b/internal/session/copilot_test.go @@ -0,0 +1,242 @@ +package session + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/millwright-software/agent-desk/internal/tmux" +) + +const copilotTestID = "b6a5a130-786e-4f89-af81-5b9ceff1f262" + +func writeCopilotMetadata(t *testing.T, home, id, content string) { + t.Helper() + dir := filepath.Join(home, ".copilot", "session-state", id) + if err := os.MkdirAll(dir, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "workspace.yaml"), []byte(content), 0600); err != nil { + t.Fatal(err) + } +} + +func TestCopilotIdentitySurvivesStorageAndReboot(t *testing.T) { + s := newTestStorage(t) + var instances []*Instance + for _, name := range []string{"dashboard", "expenses"} { + inst := NewInstanceWithTool(name, "/same/project", "copilot") + inst.Command = "copilot" + if err := inst.PrepareCopilotSession(); err != nil { + t.Fatal(err) + } + if !validCopilotID(inst.CopilotSessionID) { + t.Fatalf("not a UUID: %q", inst.CopilotSessionID) + } + if got := inst.buildCopilotCommand(inst.Command); got != "copilot --session-id="+inst.CopilotSessionID { + t.Fatalf("unexpected first launch command: %q", got) + } + instances = append(instances, inst) + } + if instances[0].CopilotSessionID == instances[1].CopilotSessionID { + t.Fatal("same-directory sessions must have different conversation IDs") + } + if err := s.SaveWithGroups(instances, nil); err != nil { + t.Fatal(err) + } + lite, _, err := s.LoadLite() + if err != nil || len(lite) != 2 { + t.Fatalf("LoadLite: %v, %d rows", err, len(lite)) + } + full, _, err := s.LoadWithGroups() + if err != nil || len(full) != 2 { + t.Fatalf("LoadWithGroups: %v, %d rows", err, len(full)) + } + expected := map[string]string{} + for _, inst := range instances { + expected[inst.ID] = inst.CopilotSessionID + } + for _, inst := range lite { + if inst.CopilotSessionID != expected[inst.ID] || !inst.CopilotSessionPending { + t.Fatalf("lite load lost identity: %+v", inst) + } + } + for _, inst := range full { + if !inst.CopilotSessionPending { + t.Fatal("pre-launch state must survive a reload") + } + inst.CopilotSessionPending = false + inst.tmuxSession = nil // A reboot removes processes, not persisted identity. + cmd, err := inst.copilotResumeCommand() + if err != nil || cmd != "copilot --resume="+expected[inst.ID] { + t.Fatalf("wrong recovery command: %q, %v", cmd, err) + } + if !inst.CanRestart() { + t.Fatal("persisted Copilot entry should be recoverable") + } + } + if err := s.SaveWithGroups(full, nil); err != nil { + t.Fatal(err) + } + reloaded, _, err := s.LoadLite() + if err != nil { + t.Fatal(err) + } + for _, inst := range reloaded { + if inst.CopilotSessionPending { + t.Fatal("launched conversation must not become a new conversation after reload") + } + } +} + +func TestCopilotLegacyRestartDoesNotStartAnotherConversation(t *testing.T) { + inst := NewInstanceWithTool("legacy", "/same/project", "copilot") + inst.Command = "copilot" + if !errors.Is(inst.Restart(), ErrCopilotRecoveryRequired) { + t.Fatal("legacy restart must request recovery, not run --continue") + } + if !errors.Is(inst.Start(), ErrCopilotRecoveryRequired) { + t.Fatal("start must not silently discard legacy history either") + } + if !errors.Is(inst.StartWithMessage("hello"), ErrCopilotRecoveryRequired) { + t.Fatal("message launch must also require identity") + } +} + +func TestCopilotMetadataAndBinding(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + writeCopilotMetadata(t, home, copilotTestID, "id: "+copilotTestID+"\nname: Dashboard\ncwd: /project\nupdated_at: 2026-10-22T12:00:00Z\n") + badID := "b6a5a130-786e-4f89-af81-5b9ceff1f263" + writeCopilotMetadata(t, home, badID, "id: wrong\n") + conversations, err := ListCopilotConversations() + if len(conversations) != 1 || err == nil { + t.Fatalf("expected one usable entry and a visible metadata error: %v, %v", conversations, err) + } + if conversations[0].Name != "Dashboard" || conversations[0].Cwd != "/project" { + t.Fatalf("wrong metadata: %+v", conversations[0]) + } + inst := &Instance{Tool: "copilot"} + if err := inst.BindCopilotConversation(copilotTestID); err != nil { + t.Fatal(err) + } + for _, invalid := range []string{"../other", badID, "not-a-uuid"} { + if err := inst.BindCopilotConversation(invalid); err == nil { + t.Errorf("accepted invalid conversation %q", invalid) + } + if inst.CopilotSessionID != copilotTestID { + t.Fatal("failed recovery changed existing binding") + } + } +} + +func TestCopilotCapabilityAndCustomCommands(t *testing.T) { + bin := t.TempDir() + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) + fake := filepath.Join(bin, "copilot") + if err := os.WriteFile(fake, []byte("#!/bin/sh\necho '--resume'\n"), 0700); err != nil { + t.Fatal(err) + } + inst := &Instance{Tool: "copilot", Command: "copilot", CopilotSessionID: copilotTestID, CopilotSessionPending: true} + if err := inst.validateCopilotLaunch(); err == nil || !strings.Contains(err.Error(), "--session-id") { + t.Fatalf("unsupported CLI must report an actionable error: %v", err) + } + if err := os.WriteFile(fake, []byte("#!/bin/sh\necho '--session-id '\n"), 0700); err != nil { + t.Fatal(err) + } + if err := inst.validateCopilotLaunch(); err != nil { + t.Fatal(err) + } + inst.CopilotSessionID = "bad; command" + if err := inst.validateCopilotLaunch(); err == nil { + t.Fatal("invalid ID accepted") + } + custom := &Instance{Tool: "copilot", Command: "copilot --model custom"} + if err := custom.PrepareCopilotSession(); err != nil || custom.CopilotSessionID != "" { + t.Fatal("custom command must not claim an ID it does not pass to Copilot") + } + custom.CopilotSessionID = copilotTestID + if _, err := custom.copilotResumeCommand(); err == nil { + t.Fatal("custom flags must not silently be discarded") + } +} + +func TestCopilotRestartRecreatesThenRespawnsSameIdentity(t *testing.T) { + bin := t.TempDir() + log := filepath.Join(bin, "commands") + t.Setenv("COPILOT_TEST_LOG", log) + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) + // A fake tmux keeps this regression independent of the user's real server. + script := "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$COPILOT_TEST_LOG\"\ncase \"$1\" in\nhas-session) exit 1;;\nlist-windows) exit 0;;\nesac\n" + if err := os.WriteFile(filepath.Join(bin, "tmux"), []byte(script), 0700); err != nil { + t.Fatal(err) + } + tmux.RefreshSessionCache() + t.Cleanup(tmux.RefreshSessionCache) + inst := NewInstanceWithTool("copilot-recovery-test", bin, "copilot") + inst.Command = "copilot" + inst.CopilotSessionID = copilotTestID + inst.Wrapper = "env RECOVERY_TEST=1 {command}" + if err := inst.Restart(); err != nil { + t.Fatal(err) + } + name := inst.tmuxSession.Name + if err := inst.Restart(); err != nil { + t.Fatal(err) + } + if name != inst.tmuxSession.Name { + t.Fatal("live restart unnecessarily recreated tmux") + } + data, err := os.ReadFile(log) + if err != nil { + t.Fatal(err) + } + output := string(data) + if !strings.Contains(output, "new-session") || !strings.Contains(output, "respawn-pane") { + t.Fatalf("did not exercise both reboot and live restart: %s", output) + } + if strings.Count(output, "copilot --resume="+copilotTestID) < 2 || strings.Contains(output, "--continue") { + t.Fatalf("wrong conversation selected: %s", output) + } + if !strings.Contains(output, "RECOVERY_TEST=1") { + t.Fatal("wrapper lost on restart") + } + if err := os.WriteFile(filepath.Join(bin, "copilot"), []byte("#!/bin/sh\necho '--session-id '\n"), 0700); err != nil { + t.Fatal(err) + } + pending := NewInstanceWithTool("copilot-not-yet-launched", bin, "copilot") + if err := pending.PrepareCopilotSession(); err != nil { + t.Fatal(err) + } + if err := pending.Restart(); err != nil { + t.Fatal(err) + } + if pending.CopilotSessionPending { + t.Fatal("successful first launch did not clear pending state") + } + if err := pending.Restart(); err != nil { + t.Fatal(err) + } + data, err = os.ReadFile(log) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), "copilot --session-id="+pending.CopilotSessionID) || + !strings.Contains(string(data), "copilot --resume="+pending.CopilotSessionID) { + t.Fatal("pre-launch recovery must allocate once, then resume") + } +} + +func TestCopilotPreparationIsStable(t *testing.T) { + inst := &Instance{Tool: "copilot", CreatedAt: time.Now()} + if err := inst.PrepareCopilotSession(); err != nil { + t.Fatal(err) + } + id := inst.CopilotSessionID + if err := inst.PrepareCopilotSession(); err != nil || inst.CopilotSessionID != id { + t.Fatal("preparation changed an already assigned identity") + } +} diff --git a/internal/session/instance.go b/internal/session/instance.go index 0fc02237..7fcc40f5 100644 --- a/internal/session/instance.go +++ b/internal/session/instance.go @@ -82,6 +82,9 @@ type Instance struct { CodexDetectedAt time.Time `json:"codex_detected_at,omitempty"` CodexStartedAt int64 `json:"-"` // Unix millis when we started Codex (for session matching, not persisted) + CopilotSessionID string `json:"copilot_session_id,omitempty"` + CopilotSessionPending bool `json:"copilot_session_pending,omitempty"` + // ColorScheme is the per-session visual theme (preset name from ColorSchemes). // Empty = Default. Applied to the tmux window and the preview pane. ColorScheme string `json:"color_scheme,omitempty"` @@ -868,14 +871,18 @@ func (i *Instance) buildCodexCommand(baseCommand string) string { } // buildCopilotCommand builds the launch command for GitHub Copilot CLI. -// Copilot tracks sessions per directory, so resume needs no captured ID: -// `copilot --continue` picks up the most recent session in the working dir. func (i *Instance) buildCopilotCommand(baseCommand string) string { if i.Tool != "copilot" { return baseCommand } - // Bare "copilot" (or empty): start fresh. + // Bare "copilot" (or empty): launch the entry's own conversation. if baseCommand == "" || baseCommand == "copilot" { + if i.CopilotSessionID != "" { + if i.CopilotSessionPending { + return "copilot --session-id=" + i.CopilotSessionID + } + return "copilot --resume=" + i.CopilotSessionID + } return "copilot" } // Custom command (e.g. an explicit resume/flags command): return as-is. @@ -1356,6 +1363,9 @@ func (i *Instance) Start() error { if i.tmuxSession == nil { return fmt.Errorf("tmux session not initialized") } + if err := i.validateCopilotLaunch(); err != nil { + return err + } // Build command based on tool type // Priority: built-in tools (claude, gemini, opencode, codex) → custom tools from config.toml → raw command @@ -1402,6 +1412,7 @@ func (i *Instance) Start() error { if err := i.tmuxSession.Start(command); err != nil { return fmt.Errorf("failed to start tmux session: %w", err) } + i.CopilotSessionPending = false // Set AGENTDESK_INSTANCE_ID for Claude hooks to identify this session // This enables real-time status updates via Stop/SessionStart hooks @@ -1444,6 +1455,9 @@ func (i *Instance) StartWithMessage(message string) error { if i.tmuxSession == nil { return fmt.Errorf("tmux session not initialized") } + if err := i.validateCopilotLaunch(); err != nil { + return err + } // Start session normally (no embedded message logic) // Priority: built-in tools (claude, gemini) → custom tools from config.toml → raw command @@ -1482,6 +1496,7 @@ func (i *Instance) StartWithMessage(message string) error { if err := i.tmuxSession.Start(command); err != nil { return fmt.Errorf("failed to start tmux session: %w", err) } + i.CopilotSessionPending = false // Set AGENTDESK_INSTANCE_ID for Claude hooks to identify this session // This enables real-time status updates via Stop/SessionStart hooks @@ -2819,6 +2834,26 @@ func (i *Instance) Kill() error { // For Claude sessions with known ID: sends Ctrl+C twice and resume command to existing session // For dead sessions or unknown ID: recreates the tmux session func (i *Instance) Restart() error { + var copilotCommand string + if i.Tool == "copilot" { + var err error + copilotCommand, err = i.copilotResumeCommand() + if err != nil { + return err + } + if i.tmuxSession != nil && i.tmuxSession.Exists() { + command, err := i.applyWrapper(copilotCommand) + if err != nil { + return err + } + if err := i.tmuxSession.RespawnPane(command); err != nil { + return fmt.Errorf("failed to restart Copilot session: %w", err) + } + i.CopilotSessionPending = false + i.Status = StatusWaiting + return nil + } + } mcpLog.Debug("restart_called", slog.String("tool", i.Tool), slog.String("claude_session_id", i.ClaudeSessionID), slog.Bool("tmux_session", i.tmuxSession != nil), slog.Bool("tmux_exists", i.tmuxSession != nil && i.tmuxSession.Exists())) // Clear flag immediately to prevent it staying set if restart fails @@ -3044,6 +3079,7 @@ func (i *Instance) Restart() error { i.tmuxSession = tmux.NewSession(i.Title, i.ProjectPath) i.tmuxSession.InstanceID = i.ID // Pass instance ID for activity hooks i.tmuxSession.SetInjectStatusLine(GetTmuxSettings().GetInjectStatusLine()) + applyColorSchemeToTmux(i.tmuxSession, i.ColorScheme) var command string if i.Tool == "claude" && i.ClaudeSessionID != "" { @@ -3059,9 +3095,7 @@ func (i *Instance) Restart() error { command = fmt.Sprintf("tmux set-environment CODEX_SESSION_ID %s; codex%s resume %s", i.CodexSessionID, i.resolveCodexYoloFlag(), i.CodexSessionID) } else if i.Tool == "copilot" { - // Copilot tracks sessions per directory; --continue resumes the most - // recent one in the working dir, so no captured session ID is needed. - command = "copilot --continue" + command = copilotCommand } else { // Route to appropriate command builder based on tool switch i.Tool { @@ -3077,8 +3111,6 @@ func (i *Instance) Restart() error { command = i.buildCodexCommand(i.Command) // Record start time for async session ID detection i.CodexStartedAt = time.Now().UnixMilli() - case "copilot": - command = i.buildCopilotCommand(i.Command) default: // Check if this is a custom tool with session resume config if toolDef := GetToolDef(i.Tool); toolDef != nil { @@ -3108,6 +3140,7 @@ func (i *Instance) Restart() error { i.Status = StatusError return fmt.Errorf("failed to restart tmux session: %w", err) } + i.CopilotSessionPending = false mcpLog.Debug("restart_start_succeeded") @@ -3217,6 +3250,9 @@ func (i *Instance) SetGeminiModel(model string) error { // For custom tools with session resume config: can restart if session ID available // For other sessions: only if dead/error state func (i *Instance) CanRestart() bool { + if i.Tool == "copilot" { + return true // Unknown identities are recovered through the conversation picker. + } // Gemini sessions with known session ID can always be restarted if i.Tool == "gemini" && i.GeminiSessionID != "" { return true diff --git a/internal/session/storage.go b/internal/session/storage.go index 7387536a..2477a3c8 100644 --- a/internal/session/storage.go +++ b/internal/session/storage.go @@ -92,8 +92,10 @@ type InstanceData struct { OpenCodeDetectedAt time.Time `json:"opencode_detected_at,omitempty"` // Codex session (persisted for resume after app restart) - CodexSessionID string `json:"codex_session_id,omitempty"` - CodexDetectedAt time.Time `json:"codex_detected_at,omitempty"` + CodexSessionID string `json:"codex_session_id,omitempty"` + CodexDetectedAt time.Time `json:"codex_detected_at,omitempty"` + CopilotSessionID string `json:"copilot_session_id,omitempty"` + CopilotSessionPending bool `json:"copilot_session_pending,omitempty"` // Per-session color scheme (preset name; empty = Default) ColorScheme string `json:"color_scheme,omitempty"` @@ -281,6 +283,8 @@ func (s *Storage) SaveWithGroups(instances []*Instance, groupTree *GroupTree) er inst.CodexSessionID, inst.CodexDetectedAt, inst.LoadedMCPNames, inst.ToolOptionsJSON, inst.ColorScheme, int(inst.Flag), lastLogActivity, snoozeUntil, inst.SnoozeFromGroup, + inst.CopilotSessionID, + inst.CopilotSessionPending, ) rows[i] = &statedb.InstanceRow{ @@ -430,44 +434,46 @@ func (s *Storage) LoadLite() ([]*InstanceData, []*GroupData, error) { opencodeSID, opencodeAt, codexSID, codexAt, loadedMCPs, - toolOpts, colorScheme, flag, lastLogUnix, snoozeUnix, snoozeFrom := statedb.UnmarshalToolData(r.ToolData) + toolOpts, colorScheme, flag, lastLogUnix, snoozeUnix, snoozeFrom, copilotSID, copilotPending := statedb.UnmarshalToolData(r.ToolData) instances[i] = &InstanceData{ - Acknowledged: r.Acknowledged, - ID: r.ID, - Title: SanitizeDisplayName(r.Title), - ProjectPath: normalizeProjectPath(r.ProjectPath), - GroupPath: r.GroupPath, - Order: r.Order, - ParentSessionID: r.ParentSessionID, - Command: r.Command, - Wrapper: r.Wrapper, - Tool: r.Tool, - Status: Status(r.Status), - CreatedAt: r.CreatedAt, - LastAccessedAt: r.LastAccessed, - TmuxSession: r.TmuxSession, - WorktreePath: r.WorktreePath, - WorktreeRepoRoot: r.WorktreeRepo, - WorktreeBranch: r.WorktreeBranch, - ClaudeSessionID: claudeSID, - ClaudeDetectedAt: claudeAt, - ClaudeModel: claudeModel, - GeminiSessionID: geminiSID, - GeminiDetectedAt: geminiAt, - GeminiYoloMode: geminiYolo, - GeminiModel: geminiModel, - OpenCodeSessionID: opencodeSID, - OpenCodeDetectedAt: opencodeAt, - CodexSessionID: codexSID, - CodexDetectedAt: codexAt, - ToolOptionsJSON: toolOpts, - LoadedMCPNames: loadedMCPs, - ColorScheme: colorScheme, - Flag: SessionFlag(flag), - SnoozeUntil: unixToTime(snoozeUnix), - SnoozeFromGroup: snoozeFrom, - LastLogActivityAt: unixToTime(lastLogUnix), + Acknowledged: r.Acknowledged, + ID: r.ID, + Title: SanitizeDisplayName(r.Title), + ProjectPath: normalizeProjectPath(r.ProjectPath), + GroupPath: r.GroupPath, + Order: r.Order, + ParentSessionID: r.ParentSessionID, + Command: r.Command, + Wrapper: r.Wrapper, + Tool: r.Tool, + Status: Status(r.Status), + CreatedAt: r.CreatedAt, + LastAccessedAt: r.LastAccessed, + TmuxSession: r.TmuxSession, + WorktreePath: r.WorktreePath, + WorktreeRepoRoot: r.WorktreeRepo, + WorktreeBranch: r.WorktreeBranch, + ClaudeSessionID: claudeSID, + ClaudeDetectedAt: claudeAt, + ClaudeModel: claudeModel, + GeminiSessionID: geminiSID, + GeminiDetectedAt: geminiAt, + GeminiYoloMode: geminiYolo, + GeminiModel: geminiModel, + OpenCodeSessionID: opencodeSID, + OpenCodeDetectedAt: opencodeAt, + CodexSessionID: codexSID, + CodexDetectedAt: codexAt, + CopilotSessionID: copilotSID, + CopilotSessionPending: copilotPending, + ToolOptionsJSON: toolOpts, + LoadedMCPNames: loadedMCPs, + ColorScheme: colorScheme, + Flag: SessionFlag(flag), + SnoozeUntil: unixToTime(snoozeUnix), + SnoozeFromGroup: snoozeFrom, + LastLogActivityAt: unixToTime(lastLogUnix), } } @@ -518,44 +524,46 @@ func (s *Storage) LoadWithGroups() ([]*Instance, []*GroupData, error) { opencodeSID, opencodeAt, codexSID, codexAt, loadedMCPs, - toolOpts, colorScheme, flag, lastLogUnix, snoozeUnix, snoozeFrom := statedb.UnmarshalToolData(r.ToolData) + toolOpts, colorScheme, flag, lastLogUnix, snoozeUnix, snoozeFrom, copilotSID, copilotPending := statedb.UnmarshalToolData(r.ToolData) data.Instances[i] = &InstanceData{ - Acknowledged: r.Acknowledged, - ID: r.ID, - Title: SanitizeDisplayName(r.Title), - ProjectPath: normalizeProjectPath(r.ProjectPath), - GroupPath: r.GroupPath, - Order: r.Order, - ParentSessionID: r.ParentSessionID, - Command: r.Command, - Wrapper: r.Wrapper, - Tool: r.Tool, - Status: Status(r.Status), - CreatedAt: r.CreatedAt, - LastAccessedAt: r.LastAccessed, - TmuxSession: r.TmuxSession, - WorktreePath: r.WorktreePath, - WorktreeRepoRoot: r.WorktreeRepo, - WorktreeBranch: r.WorktreeBranch, - ClaudeSessionID: claudeSID, - ClaudeDetectedAt: claudeAt, - ClaudeModel: claudeModel, - GeminiSessionID: geminiSID, - GeminiDetectedAt: geminiAt, - GeminiYoloMode: geminiYolo, - GeminiModel: geminiModel, - OpenCodeSessionID: opencodeSID, - OpenCodeDetectedAt: opencodeAt, - CodexSessionID: codexSID, - CodexDetectedAt: codexAt, - ToolOptionsJSON: toolOpts, - LoadedMCPNames: loadedMCPs, - ColorScheme: colorScheme, - Flag: SessionFlag(flag), - SnoozeUntil: unixToTime(snoozeUnix), - SnoozeFromGroup: snoozeFrom, - LastLogActivityAt: unixToTime(lastLogUnix), + Acknowledged: r.Acknowledged, + ID: r.ID, + Title: SanitizeDisplayName(r.Title), + ProjectPath: normalizeProjectPath(r.ProjectPath), + GroupPath: r.GroupPath, + Order: r.Order, + ParentSessionID: r.ParentSessionID, + Command: r.Command, + Wrapper: r.Wrapper, + Tool: r.Tool, + Status: Status(r.Status), + CreatedAt: r.CreatedAt, + LastAccessedAt: r.LastAccessed, + TmuxSession: r.TmuxSession, + WorktreePath: r.WorktreePath, + WorktreeRepoRoot: r.WorktreeRepo, + WorktreeBranch: r.WorktreeBranch, + ClaudeSessionID: claudeSID, + ClaudeDetectedAt: claudeAt, + ClaudeModel: claudeModel, + GeminiSessionID: geminiSID, + GeminiDetectedAt: geminiAt, + GeminiYoloMode: geminiYolo, + GeminiModel: geminiModel, + OpenCodeSessionID: opencodeSID, + OpenCodeDetectedAt: opencodeAt, + CodexSessionID: codexSID, + CodexDetectedAt: codexAt, + CopilotSessionID: copilotSID, + CopilotSessionPending: copilotPending, + ToolOptionsJSON: toolOpts, + LoadedMCPNames: loadedMCPs, + ColorScheme: colorScheme, + Flag: SessionFlag(flag), + SnoozeUntil: unixToTime(snoozeUnix), + SnoozeFromGroup: snoozeFrom, + LastLogActivityAt: unixToTime(lastLogUnix), } } @@ -691,41 +699,43 @@ func (s *Storage) convertToInstances(data *StorageData) ([]*Instance, []*GroupDa projectPath := expandTilde(instData.ProjectPath) inst := &Instance{ - Acknowledged: acknowledged, - ID: instData.ID, - Title: instData.Title, - ProjectPath: projectPath, - GroupPath: groupPath, - Order: instData.Order, - ParentSessionID: instData.ParentSessionID, - Command: instData.Command, - Wrapper: instData.Wrapper, - Tool: instData.Tool, - Status: instData.Status, - CreatedAt: instData.CreatedAt, - LastAccessedAt: instData.LastAccessedAt, - WorktreePath: instData.WorktreePath, - WorktreeRepoRoot: instData.WorktreeRepoRoot, - WorktreeBranch: instData.WorktreeBranch, - ClaudeSessionID: instData.ClaudeSessionID, - ClaudeDetectedAt: instData.ClaudeDetectedAt, - ClaudeModel: instData.ClaudeModel, - GeminiSessionID: instData.GeminiSessionID, - GeminiDetectedAt: instData.GeminiDetectedAt, - GeminiYoloMode: instData.GeminiYoloMode, - GeminiModel: instData.GeminiModel, - OpenCodeSessionID: instData.OpenCodeSessionID, - OpenCodeDetectedAt: instData.OpenCodeDetectedAt, - CodexSessionID: instData.CodexSessionID, - CodexDetectedAt: instData.CodexDetectedAt, - ToolOptionsJSON: instData.ToolOptionsJSON, - LoadedMCPNames: instData.LoadedMCPNames, - ColorScheme: instData.ColorScheme, - Flag: instData.Flag, - SnoozeUntil: instData.SnoozeUntil, - SnoozeFromGroup: instData.SnoozeFromGroup, - lastLogActivityAt: instData.LastLogActivityAt, - tmuxSession: tmuxSess, + Acknowledged: acknowledged, + ID: instData.ID, + Title: instData.Title, + ProjectPath: projectPath, + GroupPath: groupPath, + Order: instData.Order, + ParentSessionID: instData.ParentSessionID, + Command: instData.Command, + Wrapper: instData.Wrapper, + Tool: instData.Tool, + Status: instData.Status, + CreatedAt: instData.CreatedAt, + LastAccessedAt: instData.LastAccessedAt, + WorktreePath: instData.WorktreePath, + WorktreeRepoRoot: instData.WorktreeRepoRoot, + WorktreeBranch: instData.WorktreeBranch, + ClaudeSessionID: instData.ClaudeSessionID, + ClaudeDetectedAt: instData.ClaudeDetectedAt, + ClaudeModel: instData.ClaudeModel, + GeminiSessionID: instData.GeminiSessionID, + GeminiDetectedAt: instData.GeminiDetectedAt, + GeminiYoloMode: instData.GeminiYoloMode, + GeminiModel: instData.GeminiModel, + OpenCodeSessionID: instData.OpenCodeSessionID, + OpenCodeDetectedAt: instData.OpenCodeDetectedAt, + CodexSessionID: instData.CodexSessionID, + CodexDetectedAt: instData.CodexDetectedAt, + CopilotSessionID: instData.CopilotSessionID, + CopilotSessionPending: instData.CopilotSessionPending, + ToolOptionsJSON: instData.ToolOptionsJSON, + LoadedMCPNames: instData.LoadedMCPNames, + ColorScheme: instData.ColorScheme, + Flag: instData.Flag, + SnoozeUntil: instData.SnoozeUntil, + SnoozeFromGroup: instData.SnoozeFromGroup, + lastLogActivityAt: instData.LastLogActivityAt, + tmuxSession: tmuxSess, } // Apply the persisted color scheme to the tmux session styling so a diff --git a/internal/statedb/migrate.go b/internal/statedb/migrate.go index eeea80be..5c86a2e6 100644 --- a/internal/statedb/migrate.go +++ b/internal/statedb/migrate.go @@ -45,8 +45,10 @@ type jsonInstanceData struct { OpenCodeSessionID string `json:"opencode_session_id,omitempty"` OpenCodeDetectedAt time.Time `json:"opencode_detected_at,omitempty"` - CodexSessionID string `json:"codex_session_id,omitempty"` - CodexDetectedAt time.Time `json:"codex_detected_at,omitempty"` + CodexSessionID string `json:"codex_session_id,omitempty"` + CodexDetectedAt time.Time `json:"codex_detected_at,omitempty"` + CopilotSessionID string `json:"copilot_session_id,omitempty"` + CopilotSessionPending bool `json:"copilot_session_pending,omitempty"` ToolOptionsJSON json.RawMessage `json:"tool_options,omitempty"` LoadedMCPNames []string `json:"loaded_mcp_names,omitempty"` @@ -63,24 +65,26 @@ type jsonGroupData struct { // toolDataBlob is the JSON structure stored in the tool_data column. type toolDataBlob struct { - ClaudeSessionID string `json:"claude_session_id,omitempty"` - ClaudeDetectedAt int64 `json:"claude_detected_at,omitempty"` - ClaudeModel string `json:"claude_model,omitempty"` - GeminiSessionID string `json:"gemini_session_id,omitempty"` - GeminiDetectedAt int64 `json:"gemini_detected_at,omitempty"` - GeminiYoloMode *bool `json:"gemini_yolo_mode,omitempty"` - GeminiModel string `json:"gemini_model,omitempty"` - OpenCodeSessionID string `json:"opencode_session_id,omitempty"` - OpenCodeDetectedAt int64 `json:"opencode_detected_at,omitempty"` - CodexSessionID string `json:"codex_session_id,omitempty"` - CodexDetectedAt int64 `json:"codex_detected_at,omitempty"` - LoadedMCPNames []string `json:"loaded_mcp_names,omitempty"` - ToolOptions json.RawMessage `json:"tool_options,omitempty"` - ColorScheme string `json:"color_scheme,omitempty"` - Flag int `json:"flag,omitempty"` - LastLogActivity int64 `json:"last_log_activity,omitempty"` - SnoozeUntil int64 `json:"snooze_until,omitempty"` - SnoozeFromGroup string `json:"snooze_from_group,omitempty"` + ClaudeSessionID string `json:"claude_session_id,omitempty"` + ClaudeDetectedAt int64 `json:"claude_detected_at,omitempty"` + ClaudeModel string `json:"claude_model,omitempty"` + GeminiSessionID string `json:"gemini_session_id,omitempty"` + GeminiDetectedAt int64 `json:"gemini_detected_at,omitempty"` + GeminiYoloMode *bool `json:"gemini_yolo_mode,omitempty"` + GeminiModel string `json:"gemini_model,omitempty"` + OpenCodeSessionID string `json:"opencode_session_id,omitempty"` + OpenCodeDetectedAt int64 `json:"opencode_detected_at,omitempty"` + CodexSessionID string `json:"codex_session_id,omitempty"` + CodexDetectedAt int64 `json:"codex_detected_at,omitempty"` + CopilotSessionID string `json:"copilot_session_id,omitempty"` + CopilotSessionPending bool `json:"copilot_session_pending,omitempty"` + LoadedMCPNames []string `json:"loaded_mcp_names,omitempty"` + ToolOptions json.RawMessage `json:"tool_options,omitempty"` + ColorScheme string `json:"color_scheme,omitempty"` + Flag int `json:"flag,omitempty"` + LastLogActivity int64 `json:"last_log_activity,omitempty"` + SnoozeUntil int64 `json:"snooze_until,omitempty"` + SnoozeFromGroup string `json:"snooze_from_group,omitempty"` // Parked is a legacy bool (superseded by Flag); still read for migration. Parked bool `json:"parked,omitempty"` } @@ -102,14 +106,16 @@ func MigrateFromJSON(jsonPath string, db *StateDB) (int, int, error) { rows := make([]*InstanceRow, 0, len(storage.Instances)) for _, inst := range storage.Instances { td := toolDataBlob{ - ClaudeSessionID: inst.ClaudeSessionID, - GeminiSessionID: inst.GeminiSessionID, - GeminiYoloMode: inst.GeminiYoloMode, - GeminiModel: inst.GeminiModel, - OpenCodeSessionID: inst.OpenCodeSessionID, - CodexSessionID: inst.CodexSessionID, - LoadedMCPNames: inst.LoadedMCPNames, - ToolOptions: inst.ToolOptionsJSON, + ClaudeSessionID: inst.ClaudeSessionID, + GeminiSessionID: inst.GeminiSessionID, + GeminiYoloMode: inst.GeminiYoloMode, + GeminiModel: inst.GeminiModel, + OpenCodeSessionID: inst.OpenCodeSessionID, + CodexSessionID: inst.CodexSessionID, + CopilotSessionID: inst.CopilotSessionID, + CopilotSessionPending: inst.CopilotSessionPending, + LoadedMCPNames: inst.LoadedMCPNames, + ToolOptions: inst.ToolOptionsJSON, } if !inst.ClaudeDetectedAt.IsZero() { td.ClaudeDetectedAt = inst.ClaudeDetectedAt.Unix() @@ -186,22 +192,26 @@ func MarshalToolData( loadedMCPNames []string, toolOptionsJSON json.RawMessage, colorScheme string, flag int, lastLogActivity int64, snoozeUntil int64, snoozeFromGroup string, + copilotSessionID string, + copilotSessionPending bool, ) json.RawMessage { td := toolDataBlob{ - ClaudeSessionID: claudeSessionID, - ClaudeModel: claudeModel, - GeminiSessionID: geminiSessionID, - GeminiYoloMode: geminiYoloMode, - GeminiModel: geminiModel, - OpenCodeSessionID: openCodeSessionID, - CodexSessionID: codexSessionID, - LoadedMCPNames: loadedMCPNames, - ToolOptions: toolOptionsJSON, - ColorScheme: colorScheme, - Flag: flag, - LastLogActivity: lastLogActivity, - SnoozeUntil: snoozeUntil, - SnoozeFromGroup: snoozeFromGroup, + ClaudeSessionID: claudeSessionID, + ClaudeModel: claudeModel, + GeminiSessionID: geminiSessionID, + GeminiYoloMode: geminiYoloMode, + GeminiModel: geminiModel, + OpenCodeSessionID: openCodeSessionID, + CodexSessionID: codexSessionID, + CopilotSessionID: copilotSessionID, + CopilotSessionPending: copilotSessionPending, + LoadedMCPNames: loadedMCPNames, + ToolOptions: toolOptionsJSON, + ColorScheme: colorScheme, + Flag: flag, + LastLogActivity: lastLogActivity, + SnoozeUntil: snoozeUntil, + SnoozeFromGroup: snoozeFromGroup, } if !claudeDetectedAt.IsZero() { td.ClaudeDetectedAt = claudeDetectedAt.Unix() @@ -230,6 +240,8 @@ func UnmarshalToolData(data json.RawMessage) ( loadedMCPNames []string, toolOptionsJSON json.RawMessage, colorScheme string, flag int, lastLogActivity int64, snoozeUntil int64, snoozeFromGroup string, + copilotSessionID string, + copilotSessionPending bool, ) { if len(data) == 0 { return @@ -254,6 +266,8 @@ func UnmarshalToolData(data json.RawMessage) ( openCodeDetectedAt = time.Unix(td.OpenCodeDetectedAt, 0) } codexSessionID = td.CodexSessionID + copilotSessionID = td.CopilotSessionID + copilotSessionPending = td.CopilotSessionPending if td.CodexDetectedAt > 0 { codexDetectedAt = time.Unix(td.CodexDetectedAt, 0) } diff --git a/internal/statedb/tooldata_test.go b/internal/statedb/tooldata_test.go index f46f543f..b4934ecd 100644 --- a/internal/statedb/tooldata_test.go +++ b/internal/statedb/tooldata_test.go @@ -17,6 +17,8 @@ func TestToolDataRoundtripFlag(t *testing.T) { []string{"mcp-a"}, nil, "ocean", 3, 1750009999, // FlagParkedBlue, lastLogActivity 1750020000, "Work", // snoozeUntil, snoozeFromGroup + "copilot-sid", + true, ) claudeSID, claudeAt, claudeModel, @@ -25,8 +27,11 @@ func TestToolDataRoundtripFlag(t *testing.T) { _, _, _, _, mcps, - _, colorScheme, flag, lastLog, snooze, snoozeFrom := UnmarshalToolData(blob) + _, colorScheme, flag, lastLog, snooze, snoozeFrom, copilotSID, copilotPending := UnmarshalToolData(blob) + if copilotSID != "copilot-sid" || !copilotPending { + t.Fatalf("copilotSID = %q, pending = %v", copilotSID, copilotPending) + } if claudeSID != "claude-sid" { t.Errorf("claudeSID = %q, want claude-sid", claudeSID) } @@ -59,9 +64,9 @@ func TestToolDataRoundtripFlag(t *testing.T) { blob = MarshalToolData( "", time.Time{}, "", "", time.Time{}, nil, "", "", time.Time{}, "", time.Time{}, - nil, nil, "", 0, 0, 0, "", + nil, nil, "", 0, 0, 0, "", "", false, ) - _, _, _, _, _, _, _, _, _, _, _, _, _, _, flag, lastLog, snooze, _ = UnmarshalToolData(blob) + _, _, _, _, _, _, _, _, _, _, _, _, _, _, flag, lastLog, snooze, _, _, _ = UnmarshalToolData(blob) if flag != 0 || lastLog != 0 || snooze != 0 { t.Errorf("expected clean flag/lastLog/snooze, got %d/%d/%d", flag, lastLog, snooze) } @@ -71,7 +76,7 @@ func TestToolDataRoundtripFlag(t *testing.T) { // parked bool (before the Flag enum existed) maps to FlagParkedRed (2). func TestToolDataLegacyParkedMigration(t *testing.T) { legacy, _ := json.Marshal(map[string]any{"parked": true}) - _, _, _, _, _, _, _, _, _, _, _, _, _, _, flag, _, _, _ := UnmarshalToolData(legacy) + _, _, _, _, _, _, _, _, _, _, _, _, _, _, flag, _, _, _, _, _ := UnmarshalToolData(legacy) if flag != 2 { t.Errorf("legacy parked should migrate to flag 2 (FlagParkedRed), got %d", flag) } diff --git a/internal/ui/copilot_recovery_dialog.go b/internal/ui/copilot_recovery_dialog.go new file mode 100644 index 00000000..782e6327 --- /dev/null +++ b/internal/ui/copilot_recovery_dialog.go @@ -0,0 +1,192 @@ +package ui + +import ( + "fmt" + "log/slog" + "path/filepath" + "strings" + "time" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/millwright-software/agent-desk/internal/session" +) + +type copilotRecoveryLoadedMsg struct { + instanceID string + conversations []session.CopilotConversation + err error +} + +type CopilotRecoveryDialog struct { + instanceID string + title string + projectPath string + conversations []session.CopilotConversation + input textinput.Model + cursor int + allFolders bool + warning string +} + +func NewCopilotRecoveryDialog(inst *session.Instance, conversations []session.CopilotConversation, err error) *CopilotRecoveryDialog { + input := textinput.New() + input.Placeholder = "Filter by name, UUID, or folder..." + input.Focus() + d := &CopilotRecoveryDialog{ + instanceID: inst.ID, title: inst.Title, projectPath: inst.ProjectPath, + conversations: conversations, input: input, + } + if err != nil { + d.warning = "Some saved metadata could not be read. See Agent Desk logs." + uiLog.Warn("copilot_recovery_metadata", slog.String("error", err.Error())) + } + if len(d.filtered()) == 0 { + d.allFolders = true + } + return d +} + +func (d *CopilotRecoveryDialog) filtered() []session.CopilotConversation { + query := strings.ToLower(strings.TrimSpace(d.input.Value())) + var result []session.CopilotConversation + for _, c := range d.conversations { + if !d.allFolders && filepath.Clean(c.Cwd) != filepath.Clean(d.projectPath) { + continue + } + if query == "" || strings.Contains(strings.ToLower(c.Name+" "+c.ID+" "+c.Cwd), query) { + result = append(result, c) + } + } + return result +} + +func (d *CopilotRecoveryDialog) selected() *session.CopilotConversation { + rows := d.filtered() + if d.cursor < 0 || d.cursor >= len(rows) { + return nil + } + return &rows[d.cursor] +} + +func (d *CopilotRecoveryDialog) update(msg tea.KeyMsg) tea.Cmd { + switch msg.String() { + case "up", "ctrl+p": + if d.cursor > 0 { + d.cursor-- + } + case "down", "ctrl+n": + if d.cursor+1 < len(d.filtered()) { + d.cursor++ + } + case "tab": + d.allFolders = !d.allFolders + d.cursor = 0 + default: + var cmd tea.Cmd + d.input, cmd = d.input.Update(msg) + d.cursor = 0 + return cmd + } + return nil +} + +func (d *CopilotRecoveryDialog) View(width, height int) string { + innerWidth := max(24, min(90, width-8)) + d.input.Width = innerWidth - 4 + scope := "this folder" + if d.allFolders { + scope = "all folders" + } + lines := []string{ + lipgloss.NewStyle().Bold(true).Foreground(ColorAccent).Render("Recover Copilot conversation"), + "Agent Desk entry: " + d.title, + "Choose its saved conversation. Enter confirms the link.", + d.input.View(), + fmt.Sprintf("Showing %s (Tab toggles)", scope), + } + rows := d.filtered() + if len(rows) == 0 { + lines = append(lines, "No matching conversations. Try Tab or clear the filter.") + } else { + pageSize := max(1, min(7, (height-14)/2)) + start := max(0, d.cursor-pageSize+1) + end := min(len(rows), start+pageSize) + for idx := start; idx < end; idx++ { + c := rows[idx] + label := c.Name + if idx == d.cursor { + label = "> " + label + label = lipgloss.NewStyle().Bold(true).Foreground(ColorAccent).Render(label) + } else { + label = " " + label + } + lines = append(lines, label, + fmt.Sprintf(" %s | %s", c.UpdatedAt.Local().Format("Jan 02 15:04"), c.ID)) + } + if selected := d.selected(); selected != nil { + lines = append(lines, "Folder: "+session.SanitizeDisplayName(selected.Cwd)) + } + lines = append(lines, fmt.Sprintf("%d of %d", d.cursor+1, len(rows))) + } + if d.warning != "" { + lines = append(lines, d.warning) + } + lines = append(lines, "Enter link + resume | Esc cancel | Up/Down navigate") + box := DialogBoxStyle.Width(innerWidth).Render(strings.Join(lines, "\n")) + return centerInScreen(box, width, height) +} + +func (h *Home) handleCopilotRecoveryKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + d := h.copilotRecoveryDialog + switch msg.String() { + case "esc": + h.copilotRecoveryDialog = nil + return h, nil + case "enter": + chosen := d.selected() + if chosen == nil { + return h, nil + } + inst := h.getInstanceByID(d.instanceID) + if inst == nil { + d.warning = "This Agent Desk entry no longer exists. Press Esc." + return h, nil + } + // A storage reload may have linked this entry while the picker was open. + if inst.CopilotSessionID != "" { + d.warning = "This entry was linked elsewhere. Press Esc and retry." + return h, nil + } + for _, other := range h.instances { + if other.ID != inst.ID && other.CopilotSessionID == chosen.ID { + d.warning = "Already linked to: " + other.Title + return h, nil + } + } + if h.storage == nil { + d.warning = "Storage unavailable; conversation was not changed." + return h, nil + } + if err := inst.BindCopilotConversation(chosen.ID); err != nil { + d.warning = err.Error() + return h, nil + } + if h.storageWatcher != nil { + h.storageWatcher.NotifySave() + } + // Save just this entry. Failure must leave the picker open, not launch + // an unpersisted binding that will be lost at the next reboot. + if err := h.storage.SaveWithGroups([]*session.Instance{inst}, nil); err != nil { + inst.CopilotSessionID = "" + d.warning = fmt.Sprintf("Could not save conversation link: %v", err) + return h, nil + } + h.copilotRecoveryDialog = nil + h.resumingSessions[inst.ID] = time.Now() + return h, h.restartSession(inst) + default: + return h, d.update(msg) + } +} diff --git a/internal/ui/copilot_recovery_dialog_test.go b/internal/ui/copilot_recovery_dialog_test.go new file mode 100644 index 00000000..4ff83f07 --- /dev/null +++ b/internal/ui/copilot_recovery_dialog_test.go @@ -0,0 +1,120 @@ +package ui + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/millwright-software/agent-desk/internal/session" +) + +func TestCopilotRecoveryPickerFilteringAndCancel(t *testing.T) { + inst := &session.Instance{ID: "entry", Title: "Work", ProjectPath: "/project"} + conversations := []session.CopilotConversation{ + {ID: "one", Name: "Dashboard", Cwd: "/project"}, + {ID: "two", Name: "Expenses", Cwd: "/other"}, + } + d := NewCopilotRecoveryDialog(inst, conversations, nil) + if len(d.filtered()) != 1 || d.selected().ID != "one" { + t.Fatal("picker should initially show this folder") + } + d.update(tea.KeyMsg{Type: tea.KeyTab}) + if len(d.filtered()) != 2 { + t.Fatal("other folders must remain discoverable") + } + d.input.SetValue("Expenses") + if d.selected().ID != "two" { + t.Fatal("search did not find conversation") + } + if !strings.Contains(d.View(100, 30), "Expenses") { + t.Fatal("selection is not visible") + } + h := &Home{copilotRecoveryDialog: d} + h.handleCopilotRecoveryKey(tea.KeyMsg{Type: tea.KeyEsc}) + if h.copilotRecoveryDialog != nil || inst.CopilotSessionID != "" { + t.Fatal("cancel changed the conversation") + } +} + +func TestCopilotRestartRequestsPickerForLegacyEntry(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + inst := &session.Instance{ID: "entry", Tool: "copilot"} + h := &Home{instanceByID: map[string]*session.Instance{inst.ID: inst}} + msg := h.restartSession(inst)() + if _, ok := msg.(copilotRecoveryLoadedMsg); !ok { + t.Fatalf("wanted recovery, got %T", msg) + } + if inst.CopilotSessionID != "" { + t.Fatal("legacy ID was guessed") + } +} + +func TestCopilotRecoverySavesBeforeRestart(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + id := "b6a5a130-786e-4f89-af81-5b9ceff1f262" + dir := filepath.Join(home, ".copilot", "session-state", id) + if err := os.MkdirAll(dir, 0700); err != nil { + t.Fatal(err) + } + + metadata := fmt.Sprintf("id: %s\nname: Dashboard\ncwd: /project\n", id) + if err := os.WriteFile(filepath.Join(dir, "workspace.yaml"), []byte(metadata), 0600); err != nil { + t.Fatal(err) + } + storage, err := session.NewStorageWithProfile("_test") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = storage.GetDB().Close() }) + inst := session.NewInstanceWithTool("entry", "/project", "copilot") + inst.Command = "copilot" + if err := storage.SaveWithGroups([]*session.Instance{inst}, nil); err != nil { + t.Fatal(err) + } + conversations, err := session.ListCopilotConversations() + if err != nil { + t.Fatal(err) + } + h := &Home{ + storage: storage, instances: []*session.Instance{inst}, + instanceByID: map[string]*session.Instance{inst.ID: inst}, + resumingSessions: make(map[string]time.Time), + copilotRecoveryDialog: NewCopilotRecoveryDialog(inst, conversations, nil), + } + _, cmd := h.handleCopilotRecoveryKey(tea.KeyMsg{Type: tea.KeyEnter}) + if cmd == nil || h.copilotRecoveryDialog != nil { + t.Fatal("successful recovery should queue restart and close picker") + } + loaded, _, err := storage.LoadLite() + if err != nil || len(loaded) != 1 || loaded[0].CopilotSessionID != id { + t.Fatalf("identity not saved before executing restart: %v, %v", loaded, err) + } + + inst.CopilotSessionID = "" + h.copilotRecoveryDialog = NewCopilotRecoveryDialog(inst, conversations, nil) + if err := storage.GetDB().Close(); err != nil { + t.Fatal(err) + } + _, cmd = h.handleCopilotRecoveryKey(tea.KeyMsg{Type: tea.KeyEnter}) + if cmd != nil || h.copilotRecoveryDialog == nil || inst.CopilotSessionID != "" { + t.Fatal("failed save must not queue restart or retain an unpersisted binding") + } +} + +func TestCopilotPrelaunchReloadDoesNotDuplicateEntry(t *testing.T) { + old := &session.Instance{ID: "same-id"} + current := &session.Instance{ID: old.ID, CopilotSessionID: "saved-conversation"} + h := &Home{ + instances: []*session.Instance{old}, + instanceByID: map[string]*session.Instance{old.ID: old}, + } + h.registerCreatedInstance(current) + if len(h.instances) != 1 || h.instances[0] != current || h.instanceByID[old.ID] != current { + t.Fatal("prelaunch storage reload duplicated or lost the new entry") + } +} diff --git a/internal/ui/home.go b/internal/ui/home.go index a1f10d2c..72f65f5d 100644 --- a/internal/ui/home.go +++ b/internal/ui/home.go @@ -142,22 +142,23 @@ type Home struct { flatItems []session.Item // Flattened view for cursor navigation // Components - search *Search - globalSearch *GlobalSearch // Global session search across all Claude conversations - globalSearchIndex *session.GlobalSearchIndex // Search index (nil if disabled) - newDialog *NewDialog - groupDialog *GroupDialog // For creating/renaming groups - confirmDialog *ConfirmDialog // For confirming destructive actions - helpOverlay *HelpOverlay // For showing keyboard shortcuts - setupWizard *SetupWizard // For first-run setup - settingsPanel *SettingsPanel // For editing settings - analyticsPanel *AnalyticsPanel // For displaying session analytics - geminiModelDialog *GeminiModelDialog // For selecting Gemini model - colorSchemeDialog *ColorSchemeDialog // For picking a per-session color scheme - snoozeDialog *SnoozeDialog // For parking a session until a wake time (s key) - sessionPickerDialog *SessionPickerDialog // For sending output to another session - worktreeFinishDialog *WorktreeFinishDialog // For finishing worktree sessions (merge + cleanup) - worktreeManager *WorktreeManager // For listing worktrees and removing orphans + search *Search + globalSearch *GlobalSearch // Global session search across all Claude conversations + globalSearchIndex *session.GlobalSearchIndex // Search index (nil if disabled) + newDialog *NewDialog + groupDialog *GroupDialog // For creating/renaming groups + confirmDialog *ConfirmDialog // For confirming destructive actions + helpOverlay *HelpOverlay // For showing keyboard shortcuts + setupWizard *SetupWizard // For first-run setup + settingsPanel *SettingsPanel // For editing settings + analyticsPanel *AnalyticsPanel // For displaying session analytics + geminiModelDialog *GeminiModelDialog // For selecting Gemini model + colorSchemeDialog *ColorSchemeDialog // For picking a per-session color scheme + snoozeDialog *SnoozeDialog // For parking a session until a wake time (s key) + sessionPickerDialog *SessionPickerDialog // For sending output to another session + copilotRecoveryDialog *CopilotRecoveryDialog + worktreeFinishDialog *WorktreeFinishDialog // For finishing worktree sessions (merge + cleanup) + worktreeManager *WorktreeManager // For listing worktrees and removing orphans // Analytics cache (async fetching with TTL) currentAnalytics *session.SessionAnalytics // Current analytics for selected session (Claude) @@ -2366,6 +2367,16 @@ func (h *Home) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } return h, nil + case copilotRecoveryLoadedMsg: + delete(h.resumingSessions, msg.instanceID) + inst := h.getInstanceByID(msg.instanceID) + if inst == nil { + h.setError(fmt.Errorf("session no longer exists")) + return h, nil + } + h.copilotRecoveryDialog = NewCopilotRecoveryDialog(inst, msg.conversations, msg.err) + return h, nil + case sessionCreatedMsg: // Handle reload scenario: session was already started in tmux, we MUST save it to JSON // even during reload, otherwise the session becomes orphaned (exists in tmux but not in storage) @@ -2376,9 +2387,7 @@ func (h *Home) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // CRITICAL: Save the new session to JSON immediately to prevent orphaning // Skip in-memory state update (reload will handle that), but persist to disk uiLog.Debug("reload_save_session_created", slog.String("id", msg.instance.ID), slog.String("title", msg.instance.Title)) - h.instancesMu.Lock() - h.instances = append(h.instances, msg.instance) - h.instancesMu.Unlock() + h.registerCreatedInstance(msg.instance) // Force save to persist the session even during reload h.forceSaveInstances() // Trigger another reload to pick up the new session in the UI @@ -2390,9 +2399,11 @@ func (h *Home) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if msg.err != nil { h.setError(msg.err) } else { + if previous := h.getInstanceByID(msg.instance.ID); previous != nil { + h.groupTree.RemoveSession(previous) + } + h.registerCreatedInstance(msg.instance) h.instancesMu.Lock() - h.instances = append(h.instances, msg.instance) - h.instanceByID[msg.instance.ID] = msg.instance // Run dedup to ensure the new session doesn't have a duplicate ID session.UpdateClaudeSessionsWithDedup(h.instances) h.instancesMu.Unlock() @@ -2595,6 +2606,17 @@ func (h *Home) Update(msg tea.Msg) (tea.Model, tea.Cmd) { inst.CaptureLoadedMCPs() } h.invalidatePreviewCache(msg.sessionID) + if msg.persisted { + state := h.preserveState() + return h, func() tea.Msg { + mtime, _ := h.storage.GetFileMtime() + instances, groups, err := h.storage.LoadWithGroups() + return loadSessionsMsg{ + instances: instances, groups: groups, err: err, + restoreState: &state, loadMtime: mtime, + } + } + } // Save the updated session state (new tmux session name) h.saveInstances() } @@ -3243,6 +3265,9 @@ func (h *Home) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case tea.KeyMsg: // Track user activity for adaptive status updates h.lastUserInputTime = time.Now() + if h.copilotRecoveryDialog != nil { + return h.handleCopilotRecoveryKey(msg) + } // Handle setup wizard first (modal, blocks everything) if h.setupWizard.IsVisible() { @@ -3772,6 +3797,10 @@ func (h *Home) handleMainKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { h.isAttaching.Store(true) // Prevent View() output during transition (atomic) return h, h.attachSession(item.Session) } + if item.Session.Tool == "copilot" { + h.resumingSessions[item.Session.ID] = time.Now() + return h, h.restartSession(item.Session) + } // tmux session is gone (e.g. server killed) — tell the user // how to get it back instead of silently ignoring Enter if item.Session.CanRestart() { @@ -5085,6 +5114,11 @@ func (h *Home) createSessionInGroupWithWorktreeAndOptions(name, path, command, g tool = "codex" case "opencode": tool = "opencode" + case "copilot": + tool = "copilot" + if toolDef := session.GetToolDef(command); toolDef != nil { + command = toolDef.Command + } default: // Check custom tools: tool identity stays as the custom name (e.g. "glm") // so config lookup works, but command resolves to the actual binary (e.g. "claude") @@ -5119,6 +5153,19 @@ func (h *Home) createSessionInGroupWithWorktreeAndOptions(name, path, command, g inst.ToolOptionsJSON = toolOptionsJSON } + if tool == "copilot" { + if err := inst.PrepareCopilotSession(); err != nil { + return sessionCreatedMsg{err: err} + } + // Persist identity before the CLI starts, not in a delayed detector. + if h.storage == nil { + return sessionCreatedMsg{err: fmt.Errorf("cannot save Copilot identity: storage unavailable")} + } + if err := h.storage.SaveWithGroups([]*session.Instance{inst}, nil); err != nil { + return sessionCreatedMsg{err: fmt.Errorf("save Copilot identity: %w", err)} + } + } + if err := inst.Start(); err != nil { return sessionCreatedMsg{err: err} } @@ -5228,6 +5275,20 @@ func (h *Home) quickCreateSession() tea.Cmd { ) } +// A pre-launch save may already have been loaded by the storage watcher. +func (h *Home) registerCreatedInstance(inst *session.Instance) { + h.instancesMu.Lock() + defer h.instancesMu.Unlock() + h.instanceByID[inst.ID] = inst + for index, existing := range h.instances { + if existing.ID == inst.ID { + h.instances[index] = inst + return + } + } + h.instances = append(h.instances, inst) +} + // mostRecentPathInGroup returns the project path of the most recently created // session in the given group, or empty string if no sessions exist. func (h *Home) mostRecentPathInGroup(groupPath string) string { @@ -5280,6 +5341,7 @@ func (h *Home) deleteSession(inst *session.Instance) tea.Cmd { type sessionRestartedMsg struct { sessionID string err error + persisted bool } // mcpRestartedMsg signals that an MCP-triggered restart completed and should auto-attach @@ -5306,8 +5368,23 @@ func (h *Home) restartSession(inst *session.Instance) tea.Cmd { return sessionRestartedMsg{sessionID: id, err: err} } + if current.Tool == "copilot" && current.CopilotSessionID == "" { + conversations, err := session.ListCopilotConversations() + return copilotRecoveryLoadedMsg{instanceID: id, conversations: conversations, err: err} + } + if current.Tool == "copilot" && h.storage == nil { + return sessionRestartedMsg{sessionID: id, err: fmt.Errorf("cannot restart Copilot: storage unavailable")} + } err := current.Restart() mcpUILog.Debug("restart_session_result", slog.String("id", id), slog.Any("error", err)) + if err == nil && current.Tool == "copilot" { + // Persist the new tmux name even if a watcher replaced this pointer. + // The completion handler reloads instead of saving a stale UI copy. + if err := h.storage.SaveWithGroups([]*session.Instance{current}, nil); err != nil { + return sessionRestartedMsg{sessionID: id, err: fmt.Errorf("session restarted but its Copilot state could not be saved: %w", err)} + } + return sessionRestartedMsg{sessionID: id, persisted: true} + } return sessionRestartedMsg{sessionID: id, err: err} } } @@ -5867,6 +5944,9 @@ func (h *Home) View() string { if h.colorSchemeDialog.IsVisible() { return h.colorSchemeDialog.View() } + if h.copilotRecoveryDialog != nil { + return h.copilotRecoveryDialog.View(h.width, h.height) + } if h.sessionPickerDialog.IsVisible() { return h.sessionPickerDialog.View() }