From 066dca774764e5decf58cc0ee992bcd7144789fb Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Tue, 24 Nov 2026 09:54:19 -0500 Subject: [PATCH] feat(tui): replace the terminal client with a Bloom workspace Route interactive commands through one Bubble Tea client. Share layout and picker behavior across screens and restore reply timing and copy actions when history is reopened or paged. --- AGENTS.md | 10 +- cli/go.mod | 3 +- cli/go.sum | 2 + cli/internal/component/detach_other.go | 10 + cli/internal/component/detach_unix.go | 11 + cli/internal/daemon/events.go | 102 ++-- cli/internal/daemon/session_stream.go | 10 +- cli/internal/pickersearch/search.go | 222 +++++++++ cli/internal/pickersearch/search_test.go | 63 +++ cli/internal/terminal/bootstrap_test.go | 4 +- cli/internal/terminal/service.go | 32 +- cli/internal/terminalclient/client.go | 174 +++++++ cli/internal/terminalui/conversation.go | 49 ++ cli/internal/terminalui/dialog.go | 20 + cli/internal/terminalui/graph.go | 67 +++ cli/internal/terminalui/layout.go | 113 +++++ cli/internal/terminalui/layout_test.go | 45 ++ cli/internal/terminalui/list.go | 96 ++++ cli/internal/testutil/tuishots/gallery.go | 144 ++++++ cli/internal/tui/accounts.go | 100 ++-- cli/internal/tui/agents/canvas.go | 58 +++ .../{agents_events.go => agents/events.go} | 13 +- .../tui/{agents_find.go => agents/find.go} | 37 +- .../tui/{agents_graph.go => agents/graph.go} | 91 ++-- .../operations.go} | 58 +-- .../tui/{agents_order.go => agents/order.go} | 2 +- .../order_test.go} | 8 +- .../{agents_preview.go => agents/preview.go} | 11 +- cli/internal/tui/agents/render.go | 295 +++++++++++ cli/internal/tui/agents/reopen_test.go | 33 ++ .../tui/{ => agents}/shot_agents_test.go | 50 +- cli/internal/tui/agents/shot_test.go | 9 + .../subscription.go} | 14 +- .../tui/{agents_view.go => agents/view.go} | 136 ++--- .../weight_test.go} | 3 +- cli/internal/tui/agents_canvas.go | 106 ---- cli/internal/tui/agents_render.go | 311 ------------ cli/internal/tui/app.go | 468 +++++++++--------- cli/internal/tui/app_chat.go | 3 +- cli/internal/tui/app_commands.go | 22 +- cli/internal/tui/app_login.go | 8 +- cli/internal/tui/app_navigation.go | 36 +- cli/internal/tui/app_preferences.go | 16 +- cli/internal/tui/app_session_facts.go | 16 +- cli/internal/tui/app_sessions.go | 38 +- cli/internal/tui/app_terms.go | 8 +- cli/internal/tui/app_view.go | 87 +--- cli/internal/tui/artifact.go | 12 +- cli/internal/tui/bounded_history.go | 42 +- cli/internal/tui/burst.go | 22 +- cli/internal/tui/capability_pages.go | 124 ++--- cli/internal/tui/cards.go | 58 +-- cli/internal/tui/cd_checklist.go | 52 +- cli/internal/tui/cd_checklist_test.go | 18 +- cli/internal/tui/cd_move.go | 48 +- cli/internal/tui/cd_question.go | 111 +++-- cli/internal/tui/cd_question_test.go | 56 ++- cli/internal/tui/chat.go | 166 +++---- cli/internal/tui/chat_btw.go | 10 +- cli/internal/tui/chat_direnv.go | 8 +- cli/internal/tui/chat_footer.go | 62 +-- cli/internal/tui/chat_history.go | 71 ++- cli/internal/tui/chat_messages.go | 32 +- cli/internal/tui/chat_moved.go | 14 +- cli/internal/tui/chat_queue_edit.go | 4 +- cli/internal/tui/chat_queue_edit_test.go | 9 +- cli/internal/tui/chat_shell.go | 1 + cli/internal/tui/chat_shell_test.go | 1 + cli/internal/tui/chat_stream.go | 5 + cli/internal/tui/chat_subscription.go | 2 +- cli/internal/tui/chat_view.go | 101 ++-- cli/internal/tui/chips.go | 16 +- cli/internal/tui/chroma_patch_test.go | 8 +- cli/internal/tui/chrome/cell.go | 23 + cli/internal/tui/chrome/confirm.go | 55 ++ cli/internal/tui/chrome/field.go | 12 + cli/internal/tui/chrome/footer.go | 49 ++ cli/internal/tui/chrome/hints.go | 29 ++ cli/internal/tui/{ => chrome}/ink.go | 171 ++++--- cli/internal/tui/{ => chrome}/ink_other.go | 2 +- cli/internal/tui/{ => chrome}/ink_unix.go | 4 +- cli/internal/tui/chrome/operation_error.go | 14 + cli/internal/tui/{ => chrome}/rename.go | 46 +- cli/internal/tui/chrome/text.go | 14 + cli/internal/tui/{ => chrome}/theme.go | 239 +++++---- cli/internal/tui/clipboard_terminal_test.go | 9 +- cli/internal/tui/commands.go | 6 +- cli/internal/tui/config_form.go | 6 +- cli/internal/tui/config_page.go | 83 ++-- cli/internal/tui/confirm.go | 55 -- cli/internal/tui/context_inspector.go | 77 +-- cli/internal/tui/discord_form.go | 24 +- cli/internal/tui/discord_page.go | 67 +-- cli/internal/tui/discord_render.go | 141 +++--- cli/internal/tui/editor.go | 5 +- cli/internal/tui/effort_selector.go | 8 +- cli/internal/tui/effort_selector_test.go | 7 +- cli/internal/tui/extension_picker.go | 83 ++-- cli/internal/tui/extension_shelves.go | 22 +- cli/internal/tui/folder_picker.go | 67 ++- cli/internal/tui/folder_picker_view.go | 201 ++++---- cli/internal/tui/folder_query.go | 13 +- cli/internal/tui/form.go | 27 +- cli/internal/tui/frame.go | 151 +----- cli/internal/tui/frame_cache_test.go | 40 ++ cli/internal/tui/list_view.go | 227 ++++----- cli/internal/tui/location.go | 7 +- cli/internal/tui/login.go | 50 +- cli/internal/tui/login_accounts.go | 39 +- cli/internal/tui/login_profile.go | 10 +- cli/internal/tui/login_test.go | 2 +- cli/internal/tui/login_view.go | 104 ++-- cli/internal/tui/markdown.go | 93 ++-- cli/internal/tui/mcp_form.go | 8 +- cli/internal/tui/mcp_sign_in.go | 18 +- cli/internal/tui/model_picker.go | 39 +- cli/internal/tui/model_picker_view.go | 144 +++--- cli/internal/tui/model_search.go | 230 +-------- cli/internal/tui/operation_error.go | 7 - cli/internal/tui/page_render.go | 93 ++-- cli/internal/tui/page_view.go | 32 +- cli/internal/tui/page_views_test.go | 17 + cli/internal/tui/perf_bench_test.go | 71 +-- cli/internal/tui/picker.go | 21 +- cli/internal/tui/quota_view.go | 57 ++- cli/internal/tui/rowactions.go | 7 +- cli/internal/tui/selection.go | 9 +- cli/internal/tui/session_choice.go | 14 +- cli/internal/tui/session_viewer.go | 48 +- cli/internal/tui/session_viewer_view.go | 187 ++++--- cli/internal/tui/shot_accounts_test.go | 66 +-- cli/internal/tui/shot_btw_test.go | 20 +- cli/internal/tui/shot_caps_test.go | 106 ++-- cli/internal/tui/shot_cards_test.go | 20 +- cli/internal/tui/shot_cd_test.go | 84 ++-- cli/internal/tui/shot_chat_test.go | 83 ++-- cli/internal/tui/shot_config_test.go | 68 +-- cli/internal/tui/shot_context_test.go | 44 +- cli/internal/tui/shot_discord_test.go | 58 +-- cli/internal/tui/shot_extensions_test.go | 42 +- cli/internal/tui/shot_folders_test.go | 36 +- cli/internal/tui/shot_login_test.go | 122 ++--- cli/internal/tui/shot_model_test.go | 113 +++-- cli/internal/tui/shot_pages_test.go | 46 +- cli/internal/tui/shot_queue_edit_test.go | 13 +- cli/internal/tui/shot_quota_test.go | 36 +- cli/internal/tui/shot_sessions_test.go | 47 +- cli/internal/tui/shot_terms_test.go | 30 +- cli/internal/tui/shot_test.go | 142 +----- cli/internal/tui/shot_transcript_test.go | 41 +- cli/internal/tui/shot_tree_test.go | 26 +- cli/internal/tui/shot_usage_test.go | 36 +- cli/internal/tui/shot_webhooks_test.go | 56 ++- cli/internal/tui/terms.go | 12 +- cli/internal/tui/transcript.go | 105 ++-- cli/internal/tui/transcript_paging_test.go | 79 +++ cli/internal/tui/transcript_state.go | 58 ++- cli/internal/tui/tree_picker.go | 85 ++-- cli/internal/tui/usage_view.go | 39 +- cli/internal/tui/webhook_form.go | 18 +- cli/internal/tui/webhooks_page.go | 24 +- cli/internal/tui/webhooks_render.go | 79 +-- cli/internal/tui/window_title_test.go | 18 +- cli/test/e2e/tui_harness_test.go | 15 +- nix/devShells.nix | 4 +- nix/packages/tui.nix | 6 +- release/inside.sh | 2 +- robot-docs/agent-sessions.md | 2 +- robot-docs/tui-contributing.md | 28 +- robot-docs/tui.md | 47 +- test/manual/README.md | 2 +- test/manual/tui_shot.py | 6 +- web/src/lib/format.ts | 2 +- 173 files changed, 5252 insertions(+), 4265 deletions(-) create mode 100644 cli/internal/component/detach_other.go create mode 100644 cli/internal/component/detach_unix.go create mode 100644 cli/internal/pickersearch/search.go create mode 100644 cli/internal/pickersearch/search_test.go create mode 100644 cli/internal/terminalclient/client.go create mode 100644 cli/internal/terminalui/conversation.go create mode 100644 cli/internal/terminalui/dialog.go create mode 100644 cli/internal/terminalui/graph.go create mode 100644 cli/internal/terminalui/layout.go create mode 100644 cli/internal/terminalui/layout_test.go create mode 100644 cli/internal/terminalui/list.go create mode 100644 cli/internal/testutil/tuishots/gallery.go create mode 100644 cli/internal/tui/agents/canvas.go rename cli/internal/tui/{agents_events.go => agents/events.go} (93%) rename cli/internal/tui/{agents_find.go => agents/find.go} (71%) rename cli/internal/tui/{agents_graph.go => agents/graph.go} (87%) rename cli/internal/tui/{agents_operations.go => agents/operations.go} (74%) rename cli/internal/tui/{agents_order.go => agents/order.go} (99%) rename cli/internal/tui/{agents_order_test.go => agents/order_test.go} (97%) rename cli/internal/tui/{agents_preview.go => agents/preview.go} (93%) create mode 100644 cli/internal/tui/agents/render.go create mode 100644 cli/internal/tui/agents/reopen_test.go rename cli/internal/tui/{ => agents}/shot_agents_test.go (70%) create mode 100644 cli/internal/tui/agents/shot_test.go rename cli/internal/tui/{agents_subscription.go => agents/subscription.go} (90%) rename cli/internal/tui/{agents_view.go => agents/view.go} (82%) rename cli/internal/tui/{agents_weight_test.go => agents/weight_test.go} (98%) delete mode 100644 cli/internal/tui/agents_canvas.go delete mode 100644 cli/internal/tui/agents_render.go create mode 100644 cli/internal/tui/chrome/cell.go create mode 100644 cli/internal/tui/chrome/confirm.go create mode 100644 cli/internal/tui/chrome/field.go create mode 100644 cli/internal/tui/chrome/footer.go create mode 100644 cli/internal/tui/chrome/hints.go rename cli/internal/tui/{ => chrome}/ink.go (64%) rename cli/internal/tui/{ => chrome}/ink_other.go (89%) rename cli/internal/tui/{ => chrome}/ink_unix.go (94%) create mode 100644 cli/internal/tui/chrome/operation_error.go rename cli/internal/tui/{ => chrome}/rename.go (56%) create mode 100644 cli/internal/tui/chrome/text.go rename cli/internal/tui/{ => chrome}/theme.go (58%) delete mode 100644 cli/internal/tui/confirm.go create mode 100644 cli/internal/tui/page_views_test.go create mode 100644 cli/internal/tui/transcript_paging_test.go diff --git a/AGENTS.md b/AGENTS.md index fa3aaf603..39872a9fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -134,11 +134,11 @@ detached work, so finishing the CLI command does not prove the daemon stopped. Render UI changes and inspect the result before calling them done. Code review and text output do not replace a visual check. -For TUI changes, use the [shot gallery](cli/internal/tui/shot_test.go). Cover -the relevant normal, empty, error, pending, and confirmation states at wide and -narrow sizes. Set `ALBEDO_SHOT_DIR`, run the matching `TestShotGallery` -selection, and render its output with -`python3 test/manual/tui_shot.py /tmp/shots`. +For TUI changes, use the +[shot gallery](cli/internal/testutil/tuishots/gallery.go). Cover the relevant +normal, empty, error, pending, and confirmation states at wide and narrow sizes. +Set `ALBEDO_SHOT_DIR`, run the matching `TestShotGallery` selection, and render +its output with `python3 test/manual/tui_shot.py /tmp/shots`. For web changes, use a private daemon, build with `npm --prefix web run build`, and run `albedo web --no-open` against that private home. Inspect desktop and diff --git a/cli/go.mod b/cli/go.mod index 59e8ca306..f0f8bba72 100644 --- a/cli/go.mod +++ b/cli/go.mod @@ -1,8 +1,9 @@ module albedo/cli -go 1.26.8 +go 1.27.3 require ( + bloomfx.dev/bloom v0.0.0-alpha.14 charm.land/bubbles/v2 v2.2.2 charm.land/bubbletea/v2 v2.1.2 charm.land/glamour/v2 v2.0.1 diff --git a/cli/go.sum b/cli/go.sum index 278cca9f2..080368d55 100644 --- a/cli/go.sum +++ b/cli/go.sum @@ -1,3 +1,5 @@ +bloomfx.dev/bloom v0.0.0-alpha.14 h1:jeqvYwVxeR/yCb2u53dXsjgkPHu2NLr7y8O8akI3J9M= +bloomfx.dev/bloom v0.0.0-alpha.14/go.mod h1:Oljd93ovkj1z8nxlx8cUQxOc2gYt01gjD0RMZBHwS1g= charm.land/bubbles/v2 v2.2.2 h1:lXTAX9eRzW4t92r+pG4qTzkV1vU6rIO6TaIoETFf7v4= charm.land/bubbles/v2 v2.2.2/go.mod h1:fuhrxpXZGQ6D+Yl2cr+/72Vyp/JNhpZFqsuIEmUiyLk= charm.land/lipgloss/v2 v2.1.1 h1:F+vKWis9Kz3MFRsbICSDFtT1ZwVL+8f+36Dtg+OpKwc= diff --git a/cli/internal/component/detach_other.go b/cli/internal/component/detach_other.go new file mode 100644 index 000000000..250496b4f --- /dev/null +++ b/cli/internal/component/detach_other.go @@ -0,0 +1,10 @@ +//go:build !unix + +package component + +import ( + "os/exec" +) + +// Detach lets a background companion survive the launching terminal on Unix. +func Detach(cmd *exec.Cmd) {} diff --git a/cli/internal/component/detach_unix.go b/cli/internal/component/detach_unix.go new file mode 100644 index 000000000..89ac5b42e --- /dev/null +++ b/cli/internal/component/detach_unix.go @@ -0,0 +1,11 @@ +//go:build unix + +package component + +import ( + "os/exec" + "syscall" +) + +// Detach lets a background companion survive the launching terminal on Unix. +func Detach(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} } diff --git a/cli/internal/daemon/events.go b/cli/internal/daemon/events.go index 049cbb677..5cb4183e7 100644 --- a/cli/internal/daemon/events.go +++ b/cli/internal/daemon/events.go @@ -30,19 +30,19 @@ type SkillLoad struct { // ToolActivity records display-only execution evidence, not model-facing tool output. type ToolActivity struct { - Kind string `json:"kind"` // "read" | "search" | "list" | "run" | "web" | "display" | "mcp" | "cua" | "artifact" | "skill" - Target string `json:"target"` Artifact *ArtifactActivity `json:"artifact,omitempty"` Skill *SkillActivity `json:"skill,omitempty"` + // MS and OK are how long the call took and whether it worked, when it + // ended before its cell did; nil otherwise. + MS *int64 `json:"ms,omitempty"` + OK *bool `json:"ok,omitempty"` + Kind string `json:"kind"` // "read" | "search" | "list" | "run" | "web" | "display" | "mcp" | "cua" | "artifact" | "skill" + Target string `json:"target"` // Title and Description are the display() metadata; they are separate from content. Title string `json:"title,omitempty"` Description string `json:"description,omitempty"` // Detail is the markdown a web search answered with or display() showed; empty otherwise. Detail string `json:"detail,omitempty"` - // MS and OK are how long the call took and whether it worked, when it - // ended before its cell did; nil otherwise. - MS *int64 `json:"ms,omitempty"` - OK *bool `json:"ok,omitempty"` } type FileChange struct { @@ -181,7 +181,6 @@ const ( ) type Usage struct { - Model string `json:"model,omitempty"` RecordedAt *int64 `json:"recordedAt,omitempty"` PromptTokens *int `json:"promptTokens,omitempty"` CachedPromptTokens *int `json:"cachedPromptTokens,omitempty"` @@ -199,13 +198,14 @@ type Usage struct { // Spent is the total cost of every call the session made, added up per // statement. The figure for one call stays in the request ledger. Spent *Cost `json:"spent,omitempty"` - // CacheFade is how CachedPromptTokens fades once the session goes quiet, - // in time order. - CacheFade []CacheStep `json:"cacheFade,omitempty"` // Size is set when the token counts are a strategy's size for a request no // call has measured yet, as after a compaction, and not one call's own // report. It says how much of them was measured and how much estimated. - Size *Size `json:"size,omitempty"` + Size *Size `json:"size,omitempty"` + Model string `json:"model,omitempty"` + // CacheFade is how CachedPromptTokens fades once the session goes quiet, + // in time order. + CacheFade []CacheStep `json:"cacheFade,omitempty"` } // CacheStep says that from At (unix ms) on, a request would read Cached @@ -216,38 +216,32 @@ type CacheStep struct { } type StreamEvent struct { + Invalidation *ResourceInvalidation + Status *AgentStatus + // Kernel is the kernel object a kernel event carried, and Glances the + // sidebar values a glances event carried. + Kernel *protocol.Kernel + Snapshot *Session + ShellCommand *ShellCommand + SideQuestion *SideQuestion + Receipt *InputReceipt + Usage *Usage + ToolTrace *ToolTrace + // Skill is the skill a user's slash activation loaded. + Skill *SkillLoad + Timestamp *int64 + ToolArgs map[string]any + Progress *ToolProgress MessageID string - ReplacesAllLive bool - ReplacesLiveIDs []string EntryID string - Position int64 TurnType string Speaker string MailKind string SenderSessionID string - Invalidation *ResourceInvalidation - Status *AgentStatus - // Kernel is the kernel object a kernel event carried, and Glances the - // sidebar values a glances event carried. - Kernel *protocol.Kernel - Glances []PageGlance - Snapshot *Session - ShellCommand *ShellCommand - ShellCommands []ShellCommand - SideQuestion *SideQuestion - Receipt *InputReceipt - OperationID string - Images []ImageMetadata - Usage *Usage - ToolTrace *ToolTrace - // Skill is the skill a user's slash activation loaded. - Skill *SkillLoad - Timestamp *int64 - ToolArgs map[string]any - Progress *ToolProgress - TurnID string - Type EventType - Text string + OperationID string + TurnID string + Type EventType + Text string // Source is who submitted a user entry; Origin names what wrote a note. Source InputSource Origin string @@ -258,28 +252,36 @@ type StreamEvent struct { ToolStatus string ToolTitle string ProgressCallID string - SubmissionIDs []string - Evicted int + // Reset is why a reset replaced the history. + Reset ResetReason + // Code is the failure code of an error event. + Code string + // Outcome is how a turn ended, for a turn_completed event. + Outcome TurnOutcome + ReplacesLiveIDs []string + Glances []PageGlance + ShellCommands []ShellCommand + Images []ImageMetadata + SubmissionIDs []string + Position int64 + Evicted int // ElapsedMs is how long a replayed thought took, when the daemon timed it. - ElapsedMs int64 - ElapsedObserved bool + ElapsedMs int64 // Seq is the newest transcript row an EventCommitted covers. Seq int64 Sequence int64 // Before and More describe the history a reset or page carried: Before is // its first row (the cursor for the next older page), More whether one exists. - Before int64 - More bool - // Reset is why a reset replaced the history. - Reset ResetReason - // Code is the failure code of an error event. - Code string - // Outcome is how a turn ended, for a turn_completed event. - Outcome TurnOutcome + Before int64 + ReplacesAllLive bool + ElapsedObserved bool + More bool // Replayed marks an event from the transcript snapshot that follows a // reset: history, which says nothing about what the session does now. Replayed bool SnapshotOrigin bool + // EndsIdleHistory marks the final history summary of an idle reset snapshot. + EndsIdleHistory bool } // InputSource is who submitted a user entry. @@ -367,8 +369,8 @@ func progressValue(wire protocol.ToolProgress) *ToolProgress { // that the amount belongs to. The daemon derives both values, so all clients // show the same amount for the same reason. type Cost struct { - Usd float64 `json:"usd"` Basis string `json:"basis"` + Usd float64 `json:"usd"` } // The statements an amount can belong to: money charged, a plan allowance diff --git a/cli/internal/daemon/session_stream.go b/cli/internal/daemon/session_stream.go index f7cf23290..dff56bdcd 100644 --- a/cli/internal/daemon/session_stream.go +++ b/cli/internal/daemon/session_stream.go @@ -190,11 +190,11 @@ func (c *ChatClient) readStream(ctx context.Context, scanner *bufio.Scanner, onB var shellSnapshot struct { ShellCommands []ShellCommand `json:"shell_commands"` } - if err := json.Unmarshal(batch.Snapshot, &shellSnapshot); err != nil || len(shellSnapshot.ShellCommands) > 32 { + if err = json.Unmarshal(batch.Snapshot, &shellSnapshot); err != nil || len(shellSnapshot.ShellCommands) > 32 { return streamFailure(StreamProtocol, fieldError("shell commands snapshot")) } for _, command := range shellSnapshot.ShellCommands { - if err := validShellCommand(command); err != nil || command.HistorySeq != nil { + if err = validShellCommand(command); err != nil || command.HistorySeq != nil { return streamFailure(StreamProtocol, fieldError("shell command snapshot")) } } @@ -202,7 +202,7 @@ func (c *ChatClient) readStream(ctx context.Context, scanner *bufio.Scanner, onB if len(snapshot.wire.History.Items) > 0 { before = snapshot.wire.History.Items[0].Position } - events = append(events, wireChatEvent{StreamEvent: StreamEvent{Type: EventReset, Before: before, More: snapshot.wire.History.Older != nil, Snapshot: &snapshot, ShellCommands: shellSnapshot.ShellCommands, SideQuestion: snapshot.SideQuestion}}) + events = append(events, wireChatEvent{Type: EventReset, Before: before, More: snapshot.wire.History.Older != nil, Snapshot: &snapshot, ShellCommands: shellSnapshot.ShellCommands, SideQuestion: snapshot.SideQuestion}) decoded, err := decodeHistoryEntries(snapshot.wire.History.Items) if err != nil { return streamFailure(StreamProtocol, err) @@ -218,14 +218,14 @@ func (c *ChatClient) readStream(ctx context.Context, scanner *bufio.Scanner, onB for _, event := range history { events = append(events, wireChatEvent{StreamEvent: event}) } - events = append(events, wireChatEvent{StreamEvent: StreamEvent{Type: EventUsage, Usage: usageValue(snapshot.wire.Usage), Replayed: true}}) + events = append(events, wireChatEvent{Type: EventUsage, Usage: usageValue(snapshot.wire.Usage), Replayed: true, EndsIdleHistory: snapshot.Status.Idle}) for _, progress := range snapshot.wire.CurrentProgress { parsed, err := validateToolProgress(progress) if err != nil || parsed == nil { return streamFailure(StreamProtocol, fieldError("current progress")) } current = append(current, *parsed) - events = append(events, wireChatEvent{StreamEvent: StreamEvent{Type: EventToolProgress, Progress: parsed}}) + events = append(events, wireChatEvent{Type: EventToolProgress, Progress: parsed}) } } else if batch.Snapshot != nil || generation == "" || generation != batch.Generation { return streamFailure(StreamProtocol, errors.New("initial or changed generation requires a snapshot reset")) diff --git a/cli/internal/pickersearch/search.go b/cli/internal/pickersearch/search.go new file mode 100644 index 000000000..45dc0b95e --- /dev/null +++ b/cli/internal/pickersearch/search.go @@ -0,0 +1,222 @@ +// Package pickersearch ranks picker rows and locates matches in their labels. +package pickersearch + +import ( + "maps" + "slices" + "strings" + "unicode" + "unicode/utf8" +) + +// Key folds case and removes separators for exact comparisons. +func Key(s string) string { + return strings.Map(func(r rune) rune { + if unicode.IsSpace(r) || strings.ContainsRune("-_.:/", r) { + return -1 + } + return unicode.ToLower(r) + }, s) +} + +// Rank orders search matches, compared element by element: an exact id +// first, then the word-match tier sum, then the positional/compactness score. +type Rank [3]int + +func (a Rank) Compare(b Rank) int { return slices.Compare(a[:], b[:]) } + +type searchToken struct { + text []rune + start int +} + +func rangeHits(start, n int) []int { + hits := make([]int, n) + for i := range n { + hits[i] = start + i + } + return hits +} + +func matchWord(qw, rawField string) (rank Rank, hits []int, ok bool) { + q := []rune(qw) + field := []rune(strings.Map(unicode.ToLower, rawField)) + var offsets []int + for offset := range rawField { + offsets = append(offsets, offset) + } + defer func() { + for i, hit := range hits { + hits[i] = offsets[hit] + } + }() + var tokens []searchToken + var folded []rune + var foldedHits []int + isToken := func(r rune) bool { + return unicode.IsLetter(r) || unicode.IsNumber(r) || unicode.IsMark(r) || strings.ContainsRune(qw, r) + } + for i := 0; i < len(field); { + if !isToken(field[i]) { + i++ + continue + } + start := i + for i++; i < len(field) && isToken(field[i]); i++ { + } + tokens = append(tokens, searchToken{field[start:i], start}) + folded = append(folded, field[start:i]...) + foldedHits = append(foldedHits, rangeHits(start, i-start)...) + } + if len(tokens) == 0 { + return Rank{}, nil, false + } + + if slices.Equal(folded[:min(len(folded), len(q))], q) { + tier := 4 + if len(folded) == len(q) { + tier = 5 + } + return Rank{tier, 2, 100}, foldedHits[:len(q)], true + } + for wi, t := range tokens { + if slices.Equal(t.text[:min(len(t.text), len(q))], q) { + sub, score := 1, 85-wi + if wi == 0 { + sub = 2 + } + if len(t.text) == len(q) { + score += 10 + } + return Rank{4, sub, score}, rangeHits(t.start, len(q)), true + } + } + + spaceWords := len(strings.Fields(rawField)) + if spaceWords <= 2 && len(q) >= 2 && len(tokens) >= 2 { + maxSkip := 0 + if spaceWords == 1 && len(tokens) <= 5 { + maxSkip = 1 + } + var chain func(start, qi, ti, skips int) (int, []int, bool) + chain = func(start, qi, ti, skips int) (score int, hits []int, ok bool) { + if qi == len(q) { + return 78 - start*2 - skips*8, nil, true + } + if ti >= len(tokens) { + return 0, nil, false + } + t := tokens[ti] + for n := min(len(t.text), len(q)-qi); n >= 1; n-- { + if slices.Equal(t.text[:n], q[qi:qi+n]) { + if sc, h, found := chain(start, qi+n, ti+1, skips); found { + score, hits, ok = sc+(n-1)*3, append(rangeHits(t.start, n), h...), true + break + } + } + } + if skips < maxSkip { + if sc, h, found := chain(start, qi, ti+1, skips+1); found && (!ok || sc > score) { + score, hits, ok = sc, h, true + } + } + return + } + for st, t := range tokens { + if t.text[0] == q[0] { + if sc, h, found := chain(st, 0, st, 0); found && (!ok || sc > rank[2]) { + rank, hits, ok = Rank{3, 0, sc}, h, true + } + } + } + if ok { + if hits[0] == tokens[0].start { + rank[1] = 1 + } + return + } + } + + for _, t := range tokens { + if before, _, found := strings.Cut(string(t.text), qw); found { + start := t.start + utf8.RuneCountInString(before) + return Rank{2, 0, 65 - min(start, 40)}, rangeHits(start, len(q)), true + } + } + if len(q) >= 2 { + for wi, t := range tokens { + if t.text[0] != q[0] || len(t.text) < len(q) { + continue + } + pos := 0 + var h []int + for _, r := range q { + at := slices.Index(t.text[pos:], r) + if at < 0 { + break + } + pos += at + 1 + h = append(h, t.start+pos-1) + } + if len(h) != len(q) { + continue + } + if sc := 55 - (pos-len(q))*3 - wi; !ok || sc > rank[2] { + rank, hits, ok = Rank{1, 0, sc}, h, true + } + } + } + return +} + +// Words splits a query into the keys its words match by. +func Words(query string) []string { + var words []string + for field := range strings.FieldsSeq(query) { + if word := Key(field); word != "" { + words = append(words, word) + } + } + return words +} + +// Match ranks a row's fields against the search words, which every +// list screen shares: each word must match some field. The hits are +// UTF-8 byte offsets in the first field to underline. An empty search matches +// everything equally. +func Match(words []string, fields ...string) (rank Rank, hits []int, ok bool) { + if len(words) == 0 { + return Rank{}, nil, true + } + if whole := strings.Join(words, ""); whole != "" && slices.ContainsFunc(fields, func(f string) bool { return whole == Key(f) }) { + rank[0] = 1 + } + seenHits := map[int]bool{} + for _, word := range words { + var best Rank + var bestHits []int + matchedAny := false + for i, f := range fields { + r, h, found := matchWord(word, f) + if !found { + continue + } + r[2] -= i * 2 + if i != 0 { + h = nil + } + if !matchedAny || r.Compare(best) > 0 { + best, bestHits, matchedAny = r, h, true + } + } + if !matchedAny { + return Rank{}, nil, false + } + rank[1] += best[0]*4 + best[1] + rank[2] += best[2] + for _, hit := range bestHits { + seenHits[hit] = true + } + } + return rank, slices.Sorted(maps.Keys(seenHits)), true +} diff --git a/cli/internal/pickersearch/search_test.go b/cli/internal/pickersearch/search_test.go new file mode 100644 index 000000000..55e7e2da4 --- /dev/null +++ b/cli/internal/pickersearch/search_test.go @@ -0,0 +1,63 @@ +package pickersearch + +import ( + "encoding/json" + "os" + "slices" + "testing" +) + +// The shared corpus expresses highlights as character indices. Go callers +// slice the displayed label at UTF-8 byte offsets. +func TestSharedSearchCases(t *testing.T) { + var corpus struct { + Cases []struct { + WantHits map[string][]int `json:"want_hits"` + Name, Query string + Items []struct { + ID string + Fields []string + } + Want []string + } + } + data, err := os.ReadFile("../../../apps/albedo/test/fixtures/search/cases.json") + if err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(data, &corpus); err != nil { + t.Fatal(err) + } + for _, tc := range corpus.Cases { + t.Run(tc.Name, func(t *testing.T) { + var matched []string + ranks := map[string]Rank{} + words := Words(tc.Query) + for _, item := range tc.Items { + rank, hits, ok := Match(words, item.Fields...) + if !ok { + continue + } + matched = append(matched, item.ID) + ranks[item.ID] = rank + if indices, check := tc.WantHits[item.ID]; check { + var expected []int + character := 0 + for offset := range item.Fields[0] { + if slices.Contains(indices, character) { + expected = append(expected, offset) + } + character++ + } + if !slices.Equal(hits, expected) { + t.Errorf("%s highlight offsets: got %v, want %v", item.ID, hits, expected) + } + } + } + slices.SortStableFunc(matched, func(a, b string) int { return ranks[b].Compare(ranks[a]) }) + if !slices.Equal(matched, tc.Want) { + t.Errorf("ranked matches: got %v, want %v", matched, tc.Want) + } + }) + } +} diff --git a/cli/internal/terminal/bootstrap_test.go b/cli/internal/terminal/bootstrap_test.go index 612cae140..159bdcedb 100644 --- a/cli/internal/terminal/bootstrap_test.go +++ b/cli/internal/terminal/bootstrap_test.go @@ -117,7 +117,7 @@ func TestPreparedStartupReusesReadsAndRefreshesNoticeValidator(t *testing.T) { if err != nil { t.Fatal(err) } - model := tui.NewAppModel(conn, tui.Bootstrap{Sessions: prepared.Sessions, Settings: settings}, prepared.Selected, prepared.Workspace, prepared.LoginRequired, nil) + model := tui.NewWorkspace(conn, tui.Bootstrap{Sessions: prepared.Sessions, Settings: settings}, prepared.Selected, prepared.Workspace, prepared.LoginRequired, nil) t.Cleanup(func() { _ = model.Close() }) if scenario.selected || scenario.fresh { if model.ActiveSession == nil || !model.Chat.Flags.Thinking || model.Chat.Flags.Tools { @@ -131,7 +131,7 @@ func TestPreparedStartupReusesReadsAndRefreshesNoticeValidator(t *testing.T) { t.Fatal("selected or created session missing from bootstrap") } } else { - runInitialCommands(model, model.Init()) + runInitialCommands(model.Client, model.Client.Init()) if model.SessionPicker.Loading || len(model.Sessions) != len(prepared.Sessions) { t.Fatal("prepared list was discarded, including its known empty state") } diff --git a/cli/internal/terminal/service.go b/cli/internal/terminal/service.go index cd609c6cc..c2aa83c72 100644 --- a/cli/internal/terminal/service.go +++ b/cli/internal/terminal/service.go @@ -14,7 +14,9 @@ import ( "albedo/cli/internal/app" "albedo/cli/internal/daemon" + "albedo/cli/internal/tui" + "albedo/cli/internal/tui/chrome" tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" @@ -81,51 +83,47 @@ func Confirmed(answer string) bool { } func (t *Service) Open(ctx context.Context, prepared app.PreparedOpen) error { - final, err := t.runApp(ctx, prepared, func(settings daemon.Settings) *tui.AppModel { - return tui.NewAppModel(prepared.Connection, tui.Bootstrap{Sessions: prepared.Sessions, Settings: settings}, prepared.Selected, prepared.Workspace, prepared.LoginRequired, t.OpenBrowser) + final, err := t.runApp(ctx, prepared, func(settings daemon.Settings) *tui.Workspace { + return tui.NewWorkspace(prepared.Connection, tui.Bootstrap{Sessions: prepared.Sessions, Settings: settings}, prepared.Selected, prepared.Workspace, prepared.LoginRequired, t.OpenBrowser) }) if err != nil { return err } - if m, ok := final.(*tui.AppModel); ok && m.ActiveSession != nil { - _, err = fmt.Fprintf(t.Out, "To reopen this session, run albedo resume %s\n", m.ActiveSession.ID) + if final.ActiveSession != nil { + _, err = fmt.Fprintf(t.Out, "To reopen this session, run albedo resume %s\n", final.ActiveSession.ID) } return err } func (t *Service) Login(ctx context.Context, prepared app.PreparedOpen, workspace, name string) error { - _, err := t.runApp(ctx, prepared, func(settings daemon.Settings) *tui.AppModel { - return tui.NewLoginAppModel(prepared.Connection, tui.Bootstrap{Settings: settings}, workspace, name, t.OpenBrowser) + _, err := t.runApp(ctx, prepared, func(settings daemon.Settings) *tui.Workspace { + return tui.NewLoginWorkspace(prepared.Connection, tui.Bootstrap{Settings: settings}, workspace, name, t.OpenBrowser) }) return err } -func (t *Service) runApp(ctx context.Context, prepared app.PreparedOpen, build func(daemon.Settings) *tui.AppModel) (tea.Model, error) { +func (t *Service) runApp(ctx context.Context, prepared app.PreparedOpen, build func(daemon.Settings) *tui.Workspace) (*tui.Workspace, error) { settings, err := t.announceMigration(ctx, prepared.Connection, prepared.Settings) if err != nil { return nil, err } - if err = tui.DetectInk(); err != nil { + if err = chrome.DetectInk(); err != nil { return nil, err } tui.LoadPrefs() leanHeap() model := build(settings) - program := tea.NewProgram(model, tea.WithInput(t.In), tea.WithOutput(t.Out)) + program := tea.NewProgram(model.Client, tea.WithInput(t.In), tea.WithOutput(t.Out)) stopCancellation := context.AfterFunc(ctx, func() { program.Send(tea.Quit()) }) defer stopCancellation() - final, err := program.Run() - closed, ok := final.(*tui.AppModel) - if !ok { - closed = model - } - if cleanup := closed.Close(); cleanup != nil { + _, err = program.Run() + if cleanup := model.Close(); cleanup != nil { cleanup() } if ctx.Err() != nil { - return final, ctx.Err() + return model, ctx.Err() } - return final, err + return model, err } func (t *Service) ConfirmCleanup(sessions bool) (bool, error) { diff --git a/cli/internal/terminalclient/client.go b/cli/internal/terminalclient/client.go new file mode 100644 index 000000000..79b65c180 --- /dev/null +++ b/cli/internal/terminalclient/client.go @@ -0,0 +1,174 @@ +// Package terminalclient owns the Bubble Tea event loop, screen routing and +// terminal frame. Each mounted screen keeps its own input and request state. +package terminalclient + +import ( + "albedo/cli/internal/terminalui" + "strings" + "time" + + "bloomfx.dev/bloom/anim" + tea "charm.land/bubbletea/v2" +) + +type Route int + +const ( + Chat Route = iota + Sessions + Models + Extensions + Tree + Context + Page + Accounts + Capabilities + Webhooks + Discord + Config + Agents + Folders + Quota + Usage + RouteCount +) + +// Screen binds a model's three terminal operations to the same route. +type Screen struct { + Page func() terminalui.Page + Draw func() string + Input func(tea.Msg) tea.Cmd + Resize func(int, int) +} + +func BindPage[T any, P interface { + *T + Update(tea.Msg) (T, tea.Cmd) + Page() terminalui.Page + SetSize(int, int) +}](p P) Screen { + return Screen{Page: p.Page, Resize: p.SetSize, Input: func(msg tea.Msg) tea.Cmd { + next, cmd := p.Update(msg) + *p = next + return cmd + }} +} + +type Workspace interface { + Start() tea.Cmd + Route() Route + Receive(tea.Msg) (bool, tea.Cmd) + Size(int, int) + WindowTitle() string + Overlay(string) string + Attached() *Client +} + +type Client struct { + painted *tea.View + theme func() terminalui.Chrome + workspace Workspace + screens [RouteCount]Screen + entrance anim.Presence + width, height int + focused bool +} + +func New(workspace Workspace, screens [RouteCount]Screen, theme func() terminalui.Chrome) *Client { + return &Client{workspace: workspace, screens: screens, theme: theme, focused: true} +} + +func (c *Client) Init() tea.Cmd { return c.workspace.Start() } + +func (c *Client) visible() *Client { + for c.workspace.Attached() != nil { + c = c.workspace.Attached() + } + return c +} + +// Dispatch also serves attached daemons. Only the outermost client schedules +// presentation frames, so a forwarded message cannot start a second animation. +func (c *Client) Dispatch(msg tea.Msg) tea.Cmd { + c.painted = nil + if handled, cmd := c.workspace.Receive(msg); handled { + return cmd + } + if size, ok := msg.(tea.WindowSizeMsg); ok { + c.width, c.height = size.Width, size.Height + c.workspace.Size(size.Width, size.Height) + for _, s := range c.screens { + s.Resize(size.Width, size.Height) + } + return nil + } + return c.screens[c.workspace.Route()].Input(msg) +} + +func (c *Client) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg.(type) { + case anim.FrameMsg: + return c, c.entrance.Update(msg) + case tea.FocusMsg: + c.focused = true + case tea.BlurMsg: + c.focused = false + c.entrance = anim.Presence{} + } + before := c.visible() + route := before.workspace.Route() + cmd := c.Dispatch(msg) + after := c.visible() + if c.focused && (before != after || route != after.workspace.Route()) && after.workspace.Route() != Chat { + c.entrance = anim.NewPresence(anim.Duration(180*time.Millisecond), anim.FPS(24)) + cmd = tea.Batch(cmd, c.entrance.Show()) + } + return c, cmd +} + +func (c *Client) View() tea.View { + host := c.visible() + route := host.workspace.Route() + animated := c.focused && route != Chat && c.entrance.Animating() + if c.painted == nil || !animated { + screen := host.screens[route] + var body string + if screen.Page != nil { + body = screen.Page().Render(host.width, host.height, host.theme()) + } else { + body = screen.Draw() + } + view := tea.NewView(host.workspace.Overlay(body)) + view.WindowTitle = host.workspace.WindowTitle() + view.ReportFocus = true + if route == Chat { + view.MouseMode = tea.MouseModeCellMotion + } + if !animated { + return view + } + c.painted = &view + } + view := *c.painted + header, body, ok := strings.Cut(view.Content, "\n") + if ok { + progress := c.entrance.Progress() + glyph := "·" + if progress >= 0.45 { + glyph = "✧" + } + header = strings.Replace(header, "✦", glyph, 1) + // Pulse the existing rule without shifting the title or the filter below. + offset := 0 + for range int(progress * 12) { + i := strings.Index(header[offset:], "─") + if i < 0 { + break + } + offset += i + len("─") + } + header = header[:offset] + strings.Replace(header[offset:], "─", "━", 1) + view.SetContent(header + "\n" + body) + } + return view +} diff --git a/cli/internal/terminalui/conversation.go b/cli/internal/terminalui/conversation.go new file mode 100644 index 000000000..6e4091bec --- /dev/null +++ b/cli/internal/terminalui/conversation.go @@ -0,0 +1,49 @@ +package terminalui + +import ( + "slices" + "strings" +) + +// Conversation arranges a message viewport above the active composer or +// reasoning picker. Each section already knows how many terminal rows it owns. +type Conversation struct { + Heading, Status, Rule, Footer string + Notices, Messages, Accessories, Input []string +} + +// TranscriptFrame retains the unpadded rows. Paint a margin directly into the +// output builder so unchanged frames don't allocate one new string per line. +type TranscriptFrame struct { + content string + scratch, previous []string + margin int +} + +func (f *TranscriptFrame) Render(page Conversation, margin int, clean func(string) string) string { + rows := append(f.scratch[:0], page.Heading, "") + rows = append(rows, page.Notices...) + rows = append(rows, page.Messages...) + rows = append(rows, page.Status) + rows = append(rows, page.Accessories...) + rows = append(rows, page.Rule) + rows = append(rows, page.Input...) + rows = append(rows, page.Rule, page.Footer) + f.scratch = rows + if f.margin == margin && slices.Equal(rows, f.previous) { + return f.content + } + f.previous = append(f.previous[:0], rows...) + f.margin = margin + pad := strings.Repeat(" ", margin) + var out strings.Builder + for i, row := range rows { + if i != 0 { + out.WriteByte('\n') + } + out.WriteString(pad) + out.WriteString(row) + } + f.content = clean(out.String()) + return f.content +} diff --git a/cli/internal/terminalui/dialog.go b/cli/internal/terminalui/dialog.go new file mode 100644 index 000000000..b2714c2a0 --- /dev/null +++ b/cli/internal/terminalui/dialog.go @@ -0,0 +1,20 @@ +package terminalui + +import ( + "strings" + + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" +) + +// Dialog centers a modal in terminal cells. Strip the background's controls +// before dimming it so hidden links and inline images cannot cover the modal. +func Dialog(screen string, rows []string, width, height int, dim lipgloss.Style) string { + if width < 1 || height < 1 { + return screen + } + base := lipgloss.NewLayer(dim.Width(width).Height(height).MaxWidth(width).MaxHeight(height).Render(ansi.Strip(screen))) + box := lipgloss.NewLayer(lipgloss.NewStyle().MaxWidth(width).Render(strings.Join(rows[:min(height, len(rows))], "\n"))) + box.X(max(0, (width-box.Width())/2)).Y(max(0, (height-box.Height())/2)) + return lipgloss.NewCompositor(base, box).Render() +} diff --git a/cli/internal/terminalui/graph.go b/cli/internal/terminalui/graph.go new file mode 100644 index 000000000..270e2ea9a --- /dev/null +++ b/cli/internal/terminalui/graph.go @@ -0,0 +1,67 @@ +package terminalui + +import ( + "strings" + + "bloomfx.dev/bloom/flex" + "github.com/charmbracelet/x/ansi" +) + +// GraphColumns reserves the left inset and separator before distributing the +// remaining cells. Node positioning and the painter use the same geometry. +func GraphColumns(width int) (graph, detail int) { + if width < SideWidth { + return max(1, width-1), 0 + } + var sizes [2]int + flex.Split(sizes[:], width-1, 1, []flex.Track{flex.Fill(1), flex.Fixed(min(46, max(36, width/3)))}) + return sizes[0], sizes[1] +} + +type Graph struct { + Canvas func(width, height int) []string + Detail func(height int) []string + Header, Divider, Rule string + Summary, Actions []string +} + +func (g Graph) Render(width, height int) string { + if width < 1 || height < 1 { + return "" + } + rows := make([]string, 0, height) + rows = append(rows, " "+g.Header) + graph, detail := GraphColumns(width) + body := max(0, height-1-len(g.Actions)) + summary := g.Summary[:min(len(g.Summary), max(0, body/2-1))] + if len(summary) > 0 { + body -= len(summary) + 1 + } + var pane []string + if detail > 0 { + pane = g.Detail(body) + } + for i, line := range g.Canvas(graph, body) { + if detail > 0 { + line += g.Divider + " " + if i < len(pane) { + line += ansi.Truncate(pane[i], detail-1, "…") + } + } + rows = append(rows, " "+line) + } + if len(summary) > 0 { + rows = append(rows, " "+g.Rule) + for _, row := range summary { + rows = append(rows, " "+ansi.Truncate(row, width-1, "…")) + } + } + rows = append(rows, g.Actions...) + if len(rows) > height { + rows = rows[len(rows)-height:] + } + for i, row := range rows { + rows[i] = ansi.Truncate(row, width, "…") + } + return strings.Join(rows, "\n") +} diff --git a/cli/internal/terminalui/layout.go b/cli/internal/terminalui/layout.go new file mode 100644 index 000000000..dd9dabd4f --- /dev/null +++ b/cli/internal/terminalui/layout.go @@ -0,0 +1,113 @@ +// Package terminalui lays out the terminal client's screens. +package terminalui + +import ( + "charm.land/lipgloss/v2" + "cmp" + "strings" + + "bloomfx.dev/bloom/flex" + "github.com/charmbracelet/x/ansi" +) + +type Rows func(width, height int) []string + +type Page struct { + List, Detail Rows + DetailWidth func(int) int + Title, Meta, Filter, Footer, Summary string + Notices []string +} + +type Chrome struct { + Title func(int, string, string) string + Rule lipgloss.Style + Divider string +} + +const SideWidth = 96 +const SideHeight = 14 + +func (p Page) Render(width, height int, chrome Chrome) string { + width, height = max(1, cmp.Or(width, 80)), max(1, cmp.Or(height, 24)) + margin := 1 + if width >= SideWidth { + margin = 2 + } + inset := strings.Repeat(" ", margin) + inner := max(1, width-2*margin) + // Leave the header and action keys visible even at compact heights. + header := []string{inset + chrome.Title(inner, p.Title, p.Meta)} + if height >= 12 { + header = append(header, "") + } + if p.Filter != "" && height > len(header)+1 { + header = append(header, inset+p.Filter) + if height >= 9 { + header = append(header, "") + } + } + footer := strings.Split(p.Footer, "\n") + if height >= 12 { + footer = append([]string{""}, footer...) + } + // Keep the latest notices and reserve at least one row for the selection. + limit := max(0, height-len(header)-len(footer)-1) + var notices []string + for _, message := range p.Notices[max(0, len(p.Notices)-limit):] { + notices = append(notices, strings.Split(ansi.Wrap(message, inner, ""), "\n")...) + } + for _, line := range notices[max(0, len(notices)-limit):] { + header = append(header, inset+line) + } + body := max(0, height-len(header)-len(footer)) + side := p.Detail != nil && width >= SideWidth && height >= SideHeight + stack := p.Detail != nil && !side && body >= 12 + if !side && !stack && p.Summary != "" && height >= 16 && body > 1 { + footer = append([]string{" " + p.Summary}, footer...) + body-- + } + lines := header + switch { + case body == 0: + case side: + detailWidth := min(max(inner/3, 34), 48) + if p.DetailWidth != nil { + detailWidth = p.DetailWidth(inner) + } + var sizes [2]int + flex.Split(sizes[:], inner, ansi.StringWidth(chrome.Divider), []flex.Track{flex.Fill(1), flex.Fixed(detailWidth)}) + list, pane := p.List(sizes[0], body), p.Detail(sizes[1], body) + for i := range body { + lines = append(lines, inset+list[i]+chrome.Divider+pane[i]) + } + case stack: + var sizes [2]int + flex.Split(sizes[:], body, 1, []flex.Track{flex.Fill(3), flex.Fill(2)}) + rows := p.List(inner, sizes[0]) + for len(rows) > 1 && strings.TrimSpace(ansi.Strip(rows[len(rows)-1])) == "" { + rows = rows[:len(rows)-1] + } + for _, row := range rows { + lines = append(lines, inset+row) + } + lines = append(lines, inset+chrome.Rule.Render(strings.Repeat("─", inner))) + for _, line := range p.Detail(inner, body-len(rows)-1) { + lines = append(lines, inset+line) + } + default: + rows := p.List(inner, body) + for _, row := range rows { + lines = append(lines, inset+row) + } + lines = append(lines, make([]string, max(0, body-len(rows)))...) + } + lines = append(lines, footer...) + if len(lines) > height { + lines = append(lines[:height-1], lines[len(lines)-1]) + } + for i, line := range lines { + lines[i] = ansi.Truncate(line, width, "…") + } + return strings.Join(lines, "\n") +} diff --git a/cli/internal/terminalui/layout_test.go b/cli/internal/terminalui/layout_test.go new file mode 100644 index 000000000..0d63a1eb2 --- /dev/null +++ b/cli/internal/terminalui/layout_test.go @@ -0,0 +1,45 @@ +package terminalui + +import ( + "strings" + "testing" +) + +// The gap after an invalid setting used to pin its heading over the setting. +func TestGroupWindowKeepsTheRowBelowItsHeading(t *testing.T) { + var list ListIndex + list.Heading("Web search") + list.Heading("Exa") + list.Item(false) + list.Gap() + list.Heading("Context") + list.Heading("Rolling") + for range 3 { + list.Item(false) + } + list.Gap() + list.Heading("Next section") + for range 5 { + list.Item(false) + } + rows := list.Window(2, 10, "…", func(i int, selected bool) string { + if i == 0 { + return "invalid endpoint" + } + if selected { + return "selected" + } + return "setting" + }) + if !strings.Contains(strings.Join(rows, "\n"), "Exa\ninvalid endpoint") { + t.Fatalf("group lost its only row: %q", rows) + } +} + +func TestSessionNoticeKeepsItsRecoveryLine(t *testing.T) { + page := Page{Footer: "esc back", Notices: []string{"Could not load sessions: daemon refused the saved configuration.\nRestore the previous configuration and retry."}, List: func(_, h int) []string { return make([]string, h) }} + frame := page.Render(70, 20, Chrome{Title: func(int, string, string) string { return "Sessions" }}) + if !strings.Contains(frame, "\n Restore the previous configuration and retry.\n") || len(strings.Split(frame, "\n")) != 20 { + t.Fatalf("notice did not fit:\n%s", frame) + } +} diff --git a/cli/internal/terminalui/list.go b/cli/internal/terminalui/list.go new file mode 100644 index 000000000..52595ef38 --- /dev/null +++ b/cli/internal/terminalui/list.go @@ -0,0 +1,96 @@ +package terminalui + +// ListIndex maps selectable items to their display lines. A group or section +// heading is part of the scrollable content but cannot acquire keyboard focus. +type ListIndex struct { + lines []listLine + positions []int +} + +type listLine struct { + text string + item int + heading int + isHeading bool +} + +func (v *ListIndex) heading() int { + if len(v.lines) == 0 { + return -1 + } + return v.lines[len(v.lines)-1].heading +} + +func (v *ListIndex) Heading(text string) { + v.lines = append(v.lines, listLine{text: text, item: -1, heading: len(v.lines), isHeading: true}) +} + +func (v *ListIndex) Gap() { + if len(v.lines) > 0 { + v.lines = append(v.lines, listLine{item: -1, heading: v.heading()}) + } +} + +func (v *ListIndex) Item(sticky bool) { + line := len(v.lines) + head := v.heading() + if sticky { + head = line + } + v.lines = append(v.lines, listLine{item: len(v.positions), heading: head, isHeading: sticky}) + v.positions = append(v.positions, line) +} + +// Window keeps the selected item visible. Pin its heading above a clipped +// group and reserve an overflow marker below when more items follow. +func (v *ListIndex) Window(cursor, height int, overflow string, draw func(int, bool) string) []string { + out := make([]string, max(0, height)) + if len(v.positions) == 0 || height <= 0 { + return out + } + cursor = min(max(0, cursor), len(v.positions)-1) + selected := v.positions[cursor] + start := min(max(0, selected-height/2), max(0, len(v.lines)-height)) + // Move a partial window away from an orphaned heading or gap at its foot. + orphan := func() bool { + if height < 3 || start+height >= len(v.lines) { + return false + } + last := v.lines[start+height-2] + return last.item < 0 || last.isHeading && v.lines[start+height-1].item >= 0 + } + for orphan() && start > 0 && selected < start+height-3 { + start-- + } + for orphan() && selected > start+1 { + start++ + } + end := min(start+height, len(v.lines)) + paint := func(l listLine, active bool) string { + if l.item < 0 { + return l.text + } + return draw(l.item, active) + } + for i := start; i < end; i++ { + out[i-start] = paint(v.lines[i], i == selected) + } + if height < 3 { + return out + } + if start > 0 && start < selected { + head := v.lines[start+1].heading + if v.lines[start+1].item >= 0 && head >= 0 && head <= start { + out[0] = paint(v.lines[head], false) + } else { + out[0] = overflow + } + } + if end < len(v.lines) && end-1 != selected { + out[height-1] = overflow + if end-2 != selected && v.lines[end-2].isHeading { + out[height-2] = "" + } + } + return out +} diff --git a/cli/internal/testutil/tuishots/gallery.go b/cli/internal/testutil/tuishots/gallery.go new file mode 100644 index 000000000..5db6d60ea --- /dev/null +++ b/cli/internal/testutil/tuishots/gallery.go @@ -0,0 +1,144 @@ +// Package tuishots renders screen fixtures and checks that they fit the terminal. +package tuishots + +import ( + "maps" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "albedo/cli/internal/tui/chrome" + + "github.com/charmbracelet/x/ansi" +) + +// UseTerminal makes the styles what a catppuccin terminal that reported its +// colors gets, as a user's terminal does, instead of the palette-slot +// fallback tests otherwise see (reverse video selection, no tints). It +// restores them after the test, and does nothing without ALBEDO_SHOT_DIR. +func UseTerminal(t *testing.T) { + t.Helper() + if os.Getenv("ALBEDO_SHOT_DIR") == "" { + return + } + styles, ramp := chrome.DefaultStyles, chrome.CurrentInk + t.Cleanup(func() { chrome.DefaultStyles, chrome.CurrentInk = styles, ramp }) + chrome.UseInk(TestInk(t)) +} + +// TestInk is what a catppuccin terminal that reported its colors gives. +func TestInk(t *testing.T) chrome.Ink { + t.Helper() + palette := map[int]chrome.RGB{} + for slot, hex := range map[int]string{chrome.AnsiRed: "#f38ba8", chrome.AnsiGreen: "#a6e3a1", chrome.AnsiBlue: "#89b4fa", chrome.AnsiMagenta: "#cba6f7", chrome.AnsiCyan: "#94e2d5"} { + palette[slot] = *chrome.ParseHex(hex) + } + colors := chrome.TermColors{Fg: chrome.ParseHex("#cdd6f4"), Bg: chrome.ParseHex("#1e1e2e"), Palette: palette} + mixed, ok := chrome.MixInk(colors) + if !ok { + t.Fatal("the mock terminal colors were not trusted") + } + return mixed +} + +func write(t *testing.T, name, view string) { + t.Helper() + dir := os.Getenv("ALBEDO_SHOT_DIR") + if dir == "" { + return + } + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, name+".ans"), []byte(view), 0o644); err != nil { + t.Fatal(err) + } +} + +// A shot size is a terminal to draw every state in. +type shotSize struct { + name string + width, height int +} + +// wide and narrow are the two layouts; 100x24 and 80x24 sit either side of +// paneMinWidth, where the pane moves from beside the list to under it. +var shotSizes = []shotSize{{"wide", 120, 30}, {"100x24", 100, 24}, {"80x24", 80, 24}, {"narrow", 70, 20}} + +// State draws one screen fixture at the requested terminal size. +type State struct { + View func(width, height int) string + Name string +} + +var screens = map[string][]State{} + +// Register lists the states a screen can be in, from an init in the +// screen's shot__test.go, so the gallery draws all of them in every +// size. Cover what a person would want to look at: the list, a filter typed, +// each confirmation, loading, empty, failure, a notice, a form open. +func Register(screen string, states ...State) { + screens[screen] = append(screens[screen], states...) +} + +// RenderGallery draws every registered state at every size to +// $ALBEDO_SHOT_DIR/----.ans. Run one screen with +// -run TestShotGallery/. +func RenderGallery(t *testing.T) { + if os.Getenv("ALBEDO_SHOT_DIR") == "" { + t.Skip("set ALBEDO_SHOT_DIR to render the manual gallery") + } + UseTerminal(t) + for _, screen := range slices.Sorted(maps.Keys(screens)) { + t.Run(screen, func(t *testing.T) { + for _, state := range screens[screen] { + for _, size := range shotSizes { + view := state.View(size.width, size.height) + if view == "" { + t.Errorf("%s/%s drew nothing at %s", screen, state.Name, size.name) + } + write(t, screen+"--"+state.Name+"--"+size.name, view) + } + } + }) + } +} + +// CheckFits draws every registered state at every +// shot size and checks what a terminal can show: something drawn, no more rows +// than the terminal has, and no row wider than it. A row past the width wraps +// and pushes the frame down; a frame taller than the terminal scrolls its top +// away. The gallery itself stays a manual review tool. +func CheckFits(t *testing.T) { + for _, screen := range slices.Sorted(maps.Keys(screens)) { + for _, state := range screens[screen] { + // The folder states settle their picker with real waits for + // ticks, so they draw side by side. Other states may swap + // package settings while they draw, so they take turns. + t.Run(screen+"/"+state.Name, func(t *testing.T) { + if screen == "folders" { + t.Parallel() + } + for _, size := range shotSizes { + view := state.View(size.width, size.height) + if view == "" { + t.Errorf("drew nothing at %s", size.name) + continue + } + rows := strings.Split(view, "\n") + if len(rows) > size.height { + t.Errorf("at %s draws %d rows in %d", size.name, len(rows), size.height) + } + for index, row := range rows { + if width := ansi.StringWidth(row); width > size.width { + t.Errorf("at %s: row %d is %d cells wide in %d: %q", size.name, index, width, size.width, ansi.Strip(row)) + break + } + } + } + }) + } + } +} diff --git a/cli/internal/tui/accounts.go b/cli/internal/tui/accounts.go index a50cd66d7..e4b004bbe 100644 --- a/cli/internal/tui/accounts.go +++ b/cli/internal/tui/accounts.go @@ -10,6 +10,8 @@ import ( "strings" "time" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" "github.com/charmbracelet/x/ansi" @@ -303,7 +305,7 @@ func (m *LoginModel) buildAccountsPicker() { titles := map[string]func(width int) string{} pendingRow := func(section string) listEntry { return listEntry{key: rowPending, section: section, name: "signing in…", draw: func(int, []int) string { - return DefaultStyles.Agent.Render("◌") + " " + DefaultStyles.Agent.Render("signing in… finish in your browser") + return chrome.DefaultStyles.Agent.Render("◌") + " " + chrome.DefaultStyles.Agent.Render("signing in… finish in your browser") }, detail: m.pendingPane} } var more []listEntry @@ -383,8 +385,8 @@ func (m *LoginModel) buildAccountsPicker() { search: []string{"profiles", "advanced"}, draw: func(width int, hits []int) string { lw, _, _ := accountColumns(width) - return DefaultStyles.Muted.Render("⋯") + " " + markedCell("setups", hits, lw, lipgloss.NewStyle()) + " " + - DefaultStyles.Faint.Render(ansi.Truncate("models, endpoints, protocols, pins", max(1, width-lw-4), "…")) + return chrome.DefaultStyles.Muted.Render("⋯") + " " + markedCell("setups", hits, lw, lipgloss.NewStyle()) + " " + + chrome.DefaultStyles.Faint.Render(ansi.Truncate("models, endpoints, protocols, pins", max(1, width-lw-4), "…")) }, detail: m.advancedPane}) @@ -408,7 +410,7 @@ func (m *LoginModel) buildAccountsPicker() { if title, ok := titles[section]; ok { return title(width) } - return sectionRule(section, 0, width) + return chrome.SectionRule(section, 0, width) } for _, r := range rows { p.items = append(p.items, loginItem{ID: r.key, Label: r.name}) @@ -432,11 +434,11 @@ func accountsRule(label string, count int, extra string, width int) string { if extra != "" { used++ } - out := DefaultStyles.Decor.Render(" ─") + DefaultStyles.Muted.Bold(true).Render(head) + DefaultStyles.Decor.Render(tail) + out := chrome.DefaultStyles.Decor.Render(" ─") + chrome.DefaultStyles.Muted.Bold(true).Render(head) + chrome.DefaultStyles.Decor.Render(tail) if extra != "" { out += extra + " " } - return out + DefaultStyles.Decor.Render(strings.Repeat("─", max(2, width-used))) + return out + chrome.DefaultStyles.Decor.Render(strings.Repeat("─", max(2, width-used))) } // groupTitle is a service's rule: its name, how many accounts it has, and @@ -444,10 +446,10 @@ func accountsRule(label string, count int, extra string, width int) string { func (m LoginModel) groupTitle(g serviceGroup) func(width int) string { extra := "" if back, all := g.allLimited(); all { - extra = DefaultStyles.Faint.Render("· ") + DefaultStyles.Warning.Render("all limited · back "+clock(back)) + extra = chrome.DefaultStyles.Faint.Render("· ") + chrome.DefaultStyles.Warning.Render("all limited · back "+clock(back)) } else if g.rotates() { label, _ := rotationMode(g.Mode) - extra = DefaultStyles.Faint.Render("· " + label) + extra = chrome.DefaultStyles.Faint.Render("· " + label) } return func(width int) string { return accountsRule(g.Label, len(g.Accounts), extra, width) } } @@ -456,15 +458,15 @@ func (m LoginModel) groupTitle(g serviceGroup) func(width int) string { // longer one for the pane, each in its colour. func accountState(a daemon.Account) (dot, short, long string) { if a.NeedsSignIn { - return DefaultStyles.Error.Render("✕"), DefaultStyles.Error.Render("sign in again"), DefaultStyles.Error.Render("needs sign-in") + return chrome.DefaultStyles.Error.Render("✕"), chrome.DefaultStyles.Error.Render("sign in again"), chrome.DefaultStyles.Error.Render("needs sign-in") } if until, limited := limitedUntil(a); limited { - return DefaultStyles.Warning.Render("◐"), DefaultStyles.Warning.Render("back " + clock(until)), DefaultStyles.Warning.Render("limited until " + clock(until)) + return chrome.DefaultStyles.Warning.Render("◐"), chrome.DefaultStyles.Warning.Render("back " + clock(until)), chrome.DefaultStyles.Warning.Render("limited until " + clock(until)) } if a.Source == "env" { - return DefaultStyles.Success.Render("●"), DefaultStyles.Faint.Render("environment"), DefaultStyles.Success.Render("ready") + return chrome.DefaultStyles.Success.Render("●"), chrome.DefaultStyles.Faint.Render("environment"), chrome.DefaultStyles.Success.Render("ready") } - return DefaultStyles.Success.Render("●"), DefaultStyles.Muted.Render("ready"), DefaultStyles.Success.Render("ready") + return chrome.DefaultStyles.Success.Render("●"), chrome.DefaultStyles.Muted.Render("ready"), chrome.DefaultStyles.Success.Render("ready") } // accountPlan is the small tag after an account's label: its plan, or for a @@ -490,7 +492,7 @@ func (m LoginModel) accountRow(a daemon.Account, section string, g serviceGroup, dot, short, _ := accountState(a) status := short + strings.Repeat(" ", max(1, sw-ansi.StringWidth(short))) return dot + " " + markedCell(a.Label, hits, lw, lipgloss.NewStyle()) + " " + - DefaultStyles.Muted.Render(svCell(plan, pw-1, false)) + " " + status + DefaultStyles.Faint.Render(place) + chrome.DefaultStyles.Muted.Render(chrome.Cell(plan, pw-1, false)) + " " + status + chrome.DefaultStyles.Faint.Render(place) }, detail: func(width int) []string { return m.accountPane(a, width) }} } @@ -498,7 +500,7 @@ func (m LoginModel) accountRow(a daemon.Account, section string, g serviceGroup, // addRow closes a section with what adds to it. func (m LoginModel) addRow(key, section, label string, pane func(int) []string) listEntry { return listEntry{key: key, section: section, name: label, draw: func(width int, hits []int) string { - return DefaultStyles.Muted.Render("+") + " " + markedCell(label, hits, max(1, width-3), DefaultStyles.Muted) + return chrome.DefaultStyles.Muted.Render("+") + " " + markedCell(label, hits, max(1, width-3), chrome.DefaultStyles.Muted) }, detail: pane} } @@ -506,9 +508,9 @@ func (m LoginModel) addRow(key, section, label string, pane func(int) []string) func (m LoginModel) moreRow(key, label, blurb string, pane func(int) []string) listEntry { return listEntry{key: key, section: sectionMore, name: label, desc: blurb, draw: func(width int, hits []int) string { lw, _, _ := accountColumns(width) - line := DefaultStyles.Muted.Render("+") + " " + markedCell(label, hits, lw, lipgloss.NewStyle()) + line := chrome.DefaultStyles.Muted.Render("+") + " " + markedCell(label, hits, lw, lipgloss.NewStyle()) if room := width - lw - 4; room > 3 && blurb != "" { - line += " " + DefaultStyles.Muted.Render(ansi.Truncate(blurb, room, "…")) + line += " " + chrome.DefaultStyles.Muted.Render(ansi.Truncate(blurb, room, "…")) } return line }, detail: pane} @@ -622,7 +624,7 @@ func (m LoginModel) pendingPane(width int) []string { label, _ := m.serviceName(m.Provider) lines := paneTitle("Signing in to "+label, "", width) if m.SignInURL == "" { - lines = append(lines, DefaultStyles.Muted.Render(cmp.Or(m.Status, "starting sign-in…"))) + lines = append(lines, chrome.DefaultStyles.Muted.Render(cmp.Or(m.Status, "starting sign-in…"))) } else { lead := "Open this page to sign in, or on another machine:" if m.openBrowser != nil { @@ -654,16 +656,16 @@ func (m LoginModel) pendingPane(width int) []string { } // accountsHints are the keys for the highlighted row of the accounts list. -func (m LoginModel) accountsHints(width int) []hint { +func (m LoginModel) accountsHints(width int) []chrome.Hint { if m.signingInline() { if m.signInOver() { - return []hint{{"enter", "try again"}, {"esc", "back"}} + return []chrome.Hint{{Key: "enter", Does: "try again"}, {Key: "esc", Does: "back"}} } - return []hint{{"enter", "submit code"}, {"ctrl+o", "open browser again"}, {"esc", "cancel sign-in"}} + return []chrome.Hint{{Key: "enter", Does: "submit code"}, {Key: "ctrl+o", Does: "open browser again"}, {Key: "esc", Does: "cancel sign-in"}} } row, ok := m.ChoosePicker.highlighted() if !ok { - return []hint{{"↑↓", "move"}, {"esc", "back"}} + return []chrome.Hint{{Key: "↑↓", Does: "move"}, {Key: "esc", Does: "back"}} } id, isAccount := strings.CutPrefix(row.key, rowAccount) if !isAccount { @@ -674,23 +676,23 @@ func (m LoginModel) accountsHints(width int) []hint { case rowAdvanced: verb = "open" } - return []hint{{"↑↓", "move"}, {"enter", verb}, {"esc", "back"}} + return []chrome.Hint{{Key: "↑↓", Does: "move"}, {Key: "enter", Does: verb}, {Key: "esc", Does: "back"}} } a, _ := m.accountByID(id) if a.Source == "env" { - return []hint{{"↑↓", "move"}, {"esc", "back"}} + return []chrome.Hint{{Key: "↑↓", Does: "move"}, {Key: "esc", Does: "back"}} } if a.NeedsSignIn { - return []hint{{"enter", "sign in again"}, {"↑↓", "move"}, {"ctrl+x", "sign out"}, {"esc", "back"}} + return []chrome.Hint{{Key: "enter", Does: "sign in again"}, {Key: "↑↓", Does: "move"}, {Key: "ctrl+x", Does: "sign out"}, {Key: "esc", Does: "back"}} } - hints := []hint{{"↑↓", "move"}} + hints := []chrome.Hint{{Key: "↑↓", Does: "move"}} if g, ok := m.groupOf(a); ok && g.rotates() { - hints = append(hints, hint{"tab", "rotation"}, hint{"alt+↑↓", "order"}) + hints = append(hints, chrome.Hint{Key: "tab", Does: "rotation"}, chrome.Hint{Key: "alt+↑↓", Does: "order"}) } if width >= 100 { - hints = append(hints, hint{"ctrl+r", "rename"}) + hints = append(hints, chrome.Hint{Key: "ctrl+r", Does: "rename"}) } - return append(hints, hint{"ctrl+x", "sign out"}, hint{"esc", "back"}) + return append(hints, chrome.Hint{Key: "ctrl+x", Does: "sign out"}, chrome.Hint{Key: "esc", Does: "back"}) } // accountsFooter is the list's keys with the status or error beside them, @@ -700,56 +702,56 @@ func (m LoginModel) accountsFooter(width int) string { return m.signOutFooter(width) } if m.Step == StepSaving { - return statusRows(width, DefaultStyles.Faint.Render(cmp.Or(m.listBusy, "saving…"))) + return chrome.StatusRows(width, chrome.DefaultStyles.Faint.Render(cmp.Or(m.listBusy, "saving…"))) } if m.accountsEmpty() { - hints := []hint{{"↑↓", "move"}, {"enter", "sign in"}, {"esc", "later"}} + hints := []chrome.Hint{{Key: "↑↓", Does: "move"}, {Key: "enter", Does: "sign in"}, {Key: "esc", Does: "later"}} if m.Error != "" { - return footerLine(width, hints, DefaultStyles.Error.Render(m.Error), true) + return chrome.FooterLine(width, hints, chrome.DefaultStyles.Error.Render(m.Error), true) } - return footerLine(width, hints, "", false) + return chrome.FooterLine(width, hints, "", false) } hints := m.accountsHints(width) if m.Error != "" { - return footerLine(width, hints, DefaultStyles.Error.Render(m.Error), true) + return chrome.FooterLine(width, hints, chrome.DefaultStyles.Error.Render(m.Error), true) } status := m.Status if m.signingInline() { status = "" } if status != "" { - return footerLine(width, hints, DefaultStyles.Faint.Render(status), true) + return chrome.FooterLine(width, hints, chrome.DefaultStyles.Faint.Render(status), true) } - return footerLine(width, hints, "", false) + return chrome.FooterLine(width, hints, "", false) } // signOutFooter asks before signing out, saying what keeps running or // stops: the question and its consequence on one row when they fit. func (m LoginModel) signOutFooter(width int) string { if m.Removing.Kind != "account" { - return m.confirm.footer(width, m.Error) + return m.confirm.Footer(width, m.Error) } question := " Sign out " + m.Removing.Label + "? " - consequence := m.prompt - style := DefaultStyles.Muted + consequence := m.confirm.Prompt + style := chrome.DefaultStyles.Muted if a, ok := m.accountByID(m.Removing.ID); ok && m.lastOfService(a) { - style = DefaultStyles.Warning + style = chrome.DefaultStyles.Warning } var rows []string if ansi.StringWidth(question+consequence) <= width-1 { - rows = append(rows, DefaultStyles.Bold.Render(question)+style.Render(consequence)) + rows = append(rows, chrome.DefaultStyles.Bold.Render(question)+style.Render(consequence)) } else { - rows = append(rows, DefaultStyles.Bold.Render(ansi.Truncate(question, width-1, "…"))) + rows = append(rows, chrome.DefaultStyles.Bold.Render(ansi.Truncate(question, width-1, "…"))) for line := range strings.SplitSeq(ansi.Wrap(consequence, max(1, width-2), " "), "\n") { rows = append(rows, " "+style.Render(line)) } } verb := "sign out" if m.Error != "" { - rows = append(rows, " "+DefaultStyles.Error.Render(ansi.Truncate(m.Error, max(1, width-1), "…"))) + rows = append(rows, " "+chrome.DefaultStyles.Error.Render(ansi.Truncate(m.Error, max(1, width-1), "…"))) verb = "retry" } - return strings.Join(append(rows, " "+keyHints(hint{"enter", verb}, hint{"esc", "keep"})), "\n") + return strings.Join(append(rows, " "+chrome.KeyHints(chrome.Hint{Key: "enter", Does: verb}, chrome.Hint{Key: "esc", Does: "keep"})), "\n") } // accountsKey handles the accounts list's own keys and reports whether it @@ -956,23 +958,23 @@ func (m *LoginModel) firstRunKey(msg tea.KeyPressMsg) tea.Cmd { // the sign-ins, and a note on adding more. func (m LoginModel) firstRunList(width, _ int) []string { width = max(1, width-1) - lines := []string{"", " " + DefaultStyles.Bold.Render("Sign in to start. Your subscription works; no API key needed."), ""} + lines := []string{"", " " + chrome.DefaultStyles.Bold.Render("Sign in to start. Your subscription works; no API key needed."), ""} for i, row := range m.firstRunRows() { detail := row.Blurb if row.Plans != "" { detail = row.Plans + " · " + row.Blurb } - name := svCell(row.Label, 12, false) + name := chrome.Cell(row.Label, 12, false) if i == m.firstCursor { - line := selectBar() + " " + DefaultStyles.Prompt.Render("› ") + DefaultStyles.Bold.Render(name) + DefaultStyles.Muted.Render(ansi.Truncate(detail, max(1, width-17), "…")) - lines = append(lines, selectedLine(line, width)) + line := chrome.SelectBar() + " " + chrome.DefaultStyles.Prompt.Render("› ") + chrome.DefaultStyles.Bold.Render(name) + chrome.DefaultStyles.Muted.Render(ansi.Truncate(detail, max(1, width-17), "…")) + lines = append(lines, chrome.SelectedLine(line, width)) continue } - lines = append(lines, " "+name+DefaultStyles.Muted.Render(ansi.Truncate(detail, max(1, width-17), "…"))) + lines = append(lines, " "+name+chrome.DefaultStyles.Muted.Render(ansi.Truncate(detail, max(1, width-17), "…"))) } lines = append(lines, "", "") for _, l := range svWrap("Add more accounts later; albedo switches between them when one hits a limit.", max(1, width-4), 3) { - lines = append(lines, " "+DefaultStyles.Faint.Render(l)) + lines = append(lines, " "+chrome.DefaultStyles.Faint.Render(l)) } return inset(lines) } diff --git a/cli/internal/tui/agents/canvas.go b/cli/internal/tui/agents/canvas.go new file mode 100644 index 000000000..96e9cd00d --- /dev/null +++ b/cli/internal/tui/agents/canvas.go @@ -0,0 +1,58 @@ +package agents + +import ( + "strings" + + "albedo/cli/internal/tui/chrome" + + "charm.land/lipgloss/v2" + uv "github.com/charmbracelet/ultraviolet" + "github.com/charmbracelet/x/ansi" + "github.com/rivo/uniseg" +) + +// Graph coordinates are absolute. The backing buffer contains just the +// visible interval, even when the selected descendant is far below the root. +type agentCanvas struct { + buffer *uv.Buffer + styles map[chrome.RGB]*uv.Style + top int +} + +func newCanvas(width, height, top int) *agentCanvas { + return &agentCanvas{buffer: uv.NewBuffer(width, height), styles: make(map[chrome.RGB]*uv.Style), top: top} +} + +func (c *agentCanvas) visible(y int) bool { + return y >= c.top && y < c.top+c.buffer.Height() +} + +func (c *agentCanvas) put(x, y int, text string, hue chrome.RGB) { + if !c.visible(y) { + return + } + style := c.styles[hue] + if style == nil { + style = &uv.Style{Fg: lipgloss.Color(hue.Hex())} + c.styles[hue] = style + } + width := c.buffer.Width() + line := c.buffer.Line(y - c.top) + g := uniseg.NewGraphemes(text) + for x < width && g.Next() { + cluster := g.Str() + n := ansi.StringWidth(cluster) + if n == 0 { + continue + } + if x >= 0 && x+n <= width { + line.Set(x, &uv.Cell{Width: n, Content: cluster, Style: style}) + } + x += n + } +} + +func (c *agentCanvas) line(y int) string { + row := c.buffer.Line(y).Render() + return row + strings.Repeat(" ", max(0, c.buffer.Width()-ansi.StringWidth(row))) +} diff --git a/cli/internal/tui/agents_events.go b/cli/internal/tui/agents/events.go similarity index 93% rename from cli/internal/tui/agents_events.go rename to cli/internal/tui/agents/events.go index cf44574c8..b902852de 100644 --- a/cli/internal/tui/agents_events.go +++ b/cli/internal/tui/agents/events.go @@ -1,4 +1,4 @@ -package tui +package agents import ( "hash/fnv" @@ -6,10 +6,11 @@ import ( "time" "albedo/cli/internal/daemon" + "albedo/cli/internal/tui/chrome" ) // node finds or makes the dot for a session. -func (m *AgentsViewModel) node(id, name string) *agentNode { +func (m *Model) node(id, name string) *agentNode { if n, ok := m.nodes[id]; ok { if name != "" { n.name = name @@ -34,13 +35,13 @@ func hashOf(s string) uint32 { return h.Sum32() } -func hueFor(id string) rgb { - hues := agentColors().hues +func hueFor(id string) chrome.RGB { + hues := chrome.AgentColors().Hues return hues[hashOf(id)%uint32(len(hues))] } // apply folds one bus event into the view; true when the tree changed shape. -func (m *AgentsViewModel) apply(event daemon.AgentEvent) (reshaped bool) { +func (m *Model) apply(event daemon.AgentEvent) (reshaped bool) { kind := event.Type id := event.Session if kind == daemon.AgentMail { @@ -155,7 +156,7 @@ func (m *AgentsViewModel) apply(event daemon.AgentEvent) (reshaped bool) { return false } -func (m *AgentsViewModel) rememberProgress(node *agentNode, progress *daemon.ToolProgress) { +func (m *Model) rememberProgress(node *agentNode, progress *daemon.ToolProgress) { if node.progressByCallID == nil { node.progressByCallID = make(map[string]*daemon.ToolProgress) } diff --git a/cli/internal/tui/agents_find.go b/cli/internal/tui/agents/find.go similarity index 71% rename from cli/internal/tui/agents_find.go rename to cli/internal/tui/agents/find.go index 86fd00cbc..f936ad617 100644 --- a/cli/internal/tui/agents_find.go +++ b/cli/internal/tui/agents/find.go @@ -1,8 +1,11 @@ -package tui +package agents import ( "slices" + "albedo/cli/internal/pickersearch" + "albedo/cli/internal/tui/chrome" + "charm.land/bubbles/v2/textinput" tea "charm.land/bubbletea/v2" ) @@ -20,8 +23,8 @@ type agentFind struct { func (f agentFind) active() bool { return f.open } // matches is the agents the query finds, or nil when it finds everything. -func (f agentFind) matches(m *AgentsViewModel) map[string]bool { - words := searchWords(f.input.Value()) +func (f agentFind) matches(m *Model) map[string]bool { + words := pickersearch.Words(f.input.Value()) if !f.open || len(words) == 0 { return nil } @@ -30,7 +33,7 @@ func (f agentFind) matches(m *AgentsViewModel) map[string]bool { if id == agentsYou { continue } - if _, _, ok := matchFields(words, n.name, n.address, n.model); ok { + if _, _, ok := pickersearch.Match(words, n.name, n.address, n.model); ok { found[id] = true } } @@ -38,29 +41,29 @@ func (f agentFind) matches(m *AgentsViewModel) map[string]bool { } // best is the agent the query finds best, the first shown among equals. -func (f agentFind) best(m *AgentsViewModel) string { - words := searchWords(f.input.Value()) - best, bestRank := "", matchRank{} +func (f agentFind) best(m *Model) string { + words := pickersearch.Words(f.input.Value()) + best, bestRank := "", pickersearch.Rank{} for _, id := range m.order { n := m.nodes[id] if n == nil || id == agentsYou { continue } - rank, _, ok := matchFields(words, n.name, n.address, n.model) - if ok && (best == "" || rank.compare(bestRank) > 0) { + rank, _, ok := pickersearch.Match(words, n.name, n.address, n.model) + if ok && (best == "" || rank.Compare(bestRank) > 0) { best, bestRank = id, rank } } return best } -func (m *AgentsViewModel) openFind() tea.Cmd { - m.find = agentFind{input: newField(), was: m.selected, open: true} +func (m *Model) openFind() tea.Cmd { + m.find = agentFind{input: chrome.NewField(), was: m.selected, open: true} m.find.input.Placeholder = "an agent's name or model" return tea.Batch(m.find.input.Focus(), m.hold()) } -func (m *AgentsViewModel) closeFind(keep bool) { +func (m *Model) closeFind(keep bool) { if !keep { m.selected = m.find.was } @@ -69,7 +72,7 @@ func (m *AgentsViewModel) closeFind(keep bool) { } // findKey takes every key while the search is open. -func (m AgentsViewModel) findKey(msg tea.KeyPressMsg) (AgentsViewModel, tea.Cmd) { +func (m Model) findKey(msg tea.KeyPressMsg) (Model, tea.Cmd) { switch s := msg.String(); s { case "esc", "ctrl+c": m.closeFind(false) @@ -98,7 +101,7 @@ func (m AgentsViewModel) findKey(msg tea.KeyPressMsg) (AgentsViewModel, tea.Cmd) } // cycleMatches moves to the next agent the query finds, in the order shown. -func (m *AgentsViewModel) cycleMatches(d int) { +func (m *Model) cycleMatches(d int) { matches := m.find.matches(m) if matches == nil { m.cycle(d) @@ -115,10 +118,10 @@ func (m *AgentsViewModel) cycleMatches(d int) { } // findLine is the prompt row while the search is open. -func (m AgentsViewModel) findLine() string { - line := DefaultStyles.Prompt.Render("find ") + m.find.input.View() +func (m Model) findLine() string { + line := chrome.DefaultStyles.Prompt.Render("find ") + m.find.input.View() if m.find.input.Value() != "" && len(m.find.matches(&m)) == 0 { - line += DefaultStyles.Faint.Render(" no agent matches") + line += chrome.DefaultStyles.Faint.Render(" no agent matches") } return line } diff --git a/cli/internal/tui/agents_graph.go b/cli/internal/tui/agents/graph.go similarity index 87% rename from cli/internal/tui/agents_graph.go rename to cli/internal/tui/agents/graph.go index 08f62aadb..e75a886a7 100644 --- a/cli/internal/tui/agents_graph.go +++ b/cli/internal/tui/agents/graph.go @@ -1,12 +1,15 @@ -package tui +package agents import ( + "albedo/cli/internal/terminalui" "fmt" "math" "slices" "strings" "time" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -15,7 +18,7 @@ type agentPacket struct { to string edge string path [][2]int - hue rgb + hue chrome.RGB pos float64 blocks int bytes int @@ -23,30 +26,25 @@ type agentPacket struct { type agentFloat struct { text string - hue rgb + hue chrome.RGB x, y int t float64 } -func (m *AgentsViewModel) dagWidth() int { - w := m.paneWidth() - if w > 0 { - return m.Width - w - 2 - } - return m.Width - 1 +func (m *Model) dagWidth() int { + width, _ := terminalui.GraphColumns(m.Width) + return width } -func (m *AgentsViewModel) paneWidth() int { - if m.Width < paneMinWidth { - return 0 - } - return min(46, max(36, m.Width/3)) +func (m *Model) paneWidth() int { + _, width := terminalui.GraphColumns(m.Width) + return width } // layout places dots by depth, each depth wrapped into rows that fit the // pane, parents before their children so a family stays together. Siblings // go in agentRank order, and a parent's closed leaves fold into one dot. -func (m *AgentsViewModel) layout() { +func (m *Model) layout() { // The app sizes every screen, including this one before it first opens. if m.nodes == nil { return @@ -157,7 +155,7 @@ func ids(nodes []*agentNode) []string { // ranks is every agent's rank; while the view holds still an agent keeps the // rank it had, and one that joined since takes its own. -func (m *AgentsViewModel) ranks() map[string]agentRank { +func (m *Model) ranks() map[string]agentRank { if !m.holding() { m.held = nil } @@ -172,13 +170,13 @@ func (m *AgentsViewModel) ranks() map[string]agentRank { return ranks } -func (m *AgentsViewModel) holding() bool { +func (m *Model) holding() bool { return m.find.active() || time.Now().Before(m.holdUntil) } // hold keeps the order as it is for agentsHold after the selection moves, // so the next key lands where the reader looked; agentsSettleMsg lets it go. -func (m *AgentsViewModel) hold() tea.Cmd { +func (m *Model) hold() tea.Cmd { if m.held == nil || !m.holding() { m.held = m.ranks() } @@ -188,7 +186,7 @@ func (m *AgentsViewModel) hold() tea.Cmd { } // at is where the dot for id (an agent or a fold) is. -func (m *AgentsViewModel) at(id string) (x, y int, ok bool) { +func (m *Model) at(id string) (x, y int, ok bool) { if f := m.folds[id]; f != nil { return f.x, f.y, true } @@ -230,7 +228,7 @@ func edgeKey(a, b string) string { return a + ">" + b } // send starts a packet from one dot to another. Its weight is the bytes the // letter or message carried, which the daemon counted; nothing here estimates // tokens, because no provider measured them. -func (m *AgentsViewModel) send(from, to string, bytes int) { +func (m *Model) send(from, to string, bytes int) { a, b := m.nodes[from], m.nodes[to] if a == nil || b == nil || from == to { return @@ -251,7 +249,7 @@ func (m *AgentsViewModel) send(from, to string, bytes int) { } // step advances one frame of animation. -func (m *AgentsViewModel) step() { +func (m *Model) step() { now := time.Now() dt := math.Min(0.2, now.Sub(m.last).Seconds()) m.last = now @@ -298,7 +296,7 @@ func (m *AgentsViewModel) step() { // moving is whether the next frame can differ from this one: running agents // pulse, and packets, heat, floats, flashes, and notices play out. -func (m AgentsViewModel) moving() bool { +func (m Model) moving() bool { if len(m.packets) > 0 || len(m.heat) > 0 || len(m.floats) > 0 || m.noticeT > 0 { return true } @@ -331,11 +329,11 @@ func compactBytes(n int) string { var agentGlyphs = map[int]rune{5: '│', 10: '─', 6: '╭', 12: '╮', 3: '╰', 9: '╯', 7: '├', 13: '┤', 14: '┬', 11: '┴', 15: '┼', 1: '│', 4: '│', 2: '─', 8: '─'} -func (m *AgentsViewModel) drawEdges(c *agentCanvas) { +func (m *Model) drawEdges(c *agentCanvas) { type mark struct { mask int heat float64 - hue rgb + hue chrome.RGB dotted bool } marks := map[[2]int]*mark{} @@ -356,6 +354,9 @@ func (m *AgentsViewModel) drawEdges(c *agentCanvas) { cells := append([][2]int{{from.x, from.y}}, route(from, to)...) for i := 1; i < len(cells); i++ { cell, prev := cells[i], cells[i-1] + if !c.visible(cell[1]) { + continue + } mk := marks[cell] if mk == nil { mk = &mark{hue: from.hue} @@ -407,7 +408,7 @@ func (m *AgentsViewModel) drawEdges(c *agentCanvas) { } draw(a, b, heat, true) } - decor := agentColors().decor + decor := chrome.AgentColors().Decor for cell, mk := range marks { g := agentGlyphs[mk.mask] if g == 0 { @@ -421,12 +422,12 @@ func (m *AgentsViewModel) drawEdges(c *agentCanvas) { g = '┄' } } - c.put(cell[0], cell[1], string(g), decor.mix(mk.hue, math.Min(1, mk.heat*1.1))) + c.put(cell[0], cell[1], string(g), decor.Mix(mk.hue, math.Min(1, mk.heat*1.1))) } } -func (m *AgentsViewModel) drawNodes(c *agentCanvas) { - t, colors := m.clock, agentColors() +func (m *Model) drawNodes(c *agentCanvas) { + t, colors := m.clock, chrome.AgentColors() matches := m.find.matches(m) for _, f := range m.folds { glyph := "▸" @@ -434,12 +435,12 @@ func (m *AgentsViewModel) drawNodes(c *agentCanvas) { glyph = "▾" } label := fmt.Sprintf("%d closed", len(f.members)) - hue := colors.faint + hue := colors.Faint c.put(f.x, f.y, glyph, hue) if f.id == m.selected { c.put(f.x-1, f.y, "[", hue) c.put(f.x+2+ansi.StringWidth(label), f.y, "]", hue) - hue = colors.hi + hue = colors.Hi } c.put(f.x+2, f.y, label, hue) } @@ -448,37 +449,37 @@ func (m *AgentsViewModel) drawNodes(c *agentCanvas) { continue } glyph := "●" - var hue rgb + var hue chrome.RGB switch { case id == agentsYou: - glyph, hue = "◆", colors.you + glyph, hue = "◆", colors.You case n.running: p := 0.5 + 0.5*math.Sin(t*5+n.phase) if p > 0.55 { glyph = "◉" } - hue = n.hue.mix(colors.faint, 0.2).mix(n.hue, p) + hue = n.hue.Mix(colors.Faint, 0.2).Mix(n.hue, p) case n.closed: - glyph, hue = "✓", n.hue.mix(colors.faint, 0.5) + glyph, hue = "✓", n.hue.Mix(colors.Faint, 0.5) default: glyph = "○" if n.peer { glyph = "◇" } - hue = n.hue.mix(colors.faint, 0.3) + hue = n.hue.Mix(colors.Faint, 0.3) } if n.flash > 0 { - hue = hue.mix(colors.hi, n.flash*0.7) + hue = hue.Mix(colors.Hi, n.flash*0.7) } - label := n.hue.mix(colors.hi, 0.35) + label := n.hue.Mix(colors.Hi, 0.35) // A search dims the agents it does not find. if matches != nil && !matches[id] && id != agentsYou { - label, hue = colors.faint, colors.faint + label, hue = colors.Faint, colors.Faint } c.put(n.x, n.y, glyph, hue) name := ansi.Truncate(n.name, agentsSlotW-4, "…") if id == m.selected { - label = colors.hi + label = colors.Hi c.put(n.x-1, n.y, "[", n.hue) c.put(n.x+2+ansi.StringWidth(name), n.y, "]", n.hue) } @@ -487,9 +488,9 @@ func (m *AgentsViewModel) drawNodes(c *agentCanvas) { switch { case m.root != "": case m.err != nil: - c.put(n.x, n.y+2, "could not load agents", colors.faint) + c.put(n.x, n.y+2, "could not load agents", colors.Faint) default: - c.put(n.x, n.y+2, "loading agents…", colors.faint) + c.put(n.x, n.y+2, "loading agents…", colors.Faint) } continue } @@ -503,13 +504,13 @@ func (m *AgentsViewModel) drawNodes(c *agentCanvas) { } bars.WriteRune(agentsBars[max(0, min(7, int(math.Round(v*7))))]) } - barHue := colors.decor + barHue := colors.Decor if n.running && (matches == nil || matches[id]) { barHue = n.hue } c.put(n.x+2, n.y+1, bars.String(), barHue) if n.outputBytes > 0 { - c.put(n.x+8, n.y+1, compactBytes(n.outputBytes), colors.faint) + c.put(n.x+8, n.y+1, compactBytes(n.outputBytes), colors.Faint) } } for _, p := range m.packets { @@ -521,13 +522,13 @@ func (m *AgentsViewModel) drawNodes(c *agentCanvas) { } glyph, hue := "▪", p.hue if i == 0 { - glyph, hue = "■", p.hue.mix(colors.hi, 0.35) + glyph, hue = "■", p.hue.Mix(colors.Hi, 0.35) } c.put(p.path[idx][0], p.path[idx][1], glyph, hue) } } for _, f := range m.floats { rise := min(2, int(f.t*2.2)) - c.put(f.x, f.y-rise, f.text, f.hue.mix(colors.decor, math.Min(1, f.t/1.4))) + c.put(f.x, f.y-rise, f.text, f.hue.Mix(colors.Decor, math.Min(1, f.t/1.4))) } } diff --git a/cli/internal/tui/agents_operations.go b/cli/internal/tui/agents/operations.go similarity index 74% rename from cli/internal/tui/agents_operations.go rename to cli/internal/tui/agents/operations.go index a06343cd5..8b65dd071 100644 --- a/cli/internal/tui/agents_operations.go +++ b/cli/internal/tui/agents/operations.go @@ -1,4 +1,4 @@ -package tui +package agents import ( "cmp" @@ -15,7 +15,7 @@ import ( ) // below counts the agents under id. -func (m AgentsViewModel) below(id string) int { +func (m Model) below(id string) int { count := 0 for _, n := range m.nodes { for p := n.parent; p != ""; { @@ -32,7 +32,7 @@ func (m AgentsViewModel) below(id string) int { return count } -func (m AgentsViewModel) deleteCmd(id string) tea.Cmd { +func (m Model) deleteCmd(id string) tea.Cmd { conn, gen, name := m.Conn, m.viewGen, m.label(id, "") condition := daemon.SessionCondition{} if n := m.nodes[id]; n != nil { @@ -41,20 +41,20 @@ func (m AgentsViewModel) deleteCmd(id string) tea.Cmd { return func() tea.Msg { res, err := daemon.DeleteSession(context.Background(), conn, id, true, condition) if err != nil { - return agentsSentMsg{Gen: gen, Action: "delete " + name, Err: err} + return OperationResultMsg{Gen: gen, Action: "delete " + name, Err: err} } - return agentsSentMsg{Gen: gen, Notice: name + ": " + res.Message} + return OperationResultMsg{Gen: gen, Notice: name + ": " + res.Message} } } -func (m *AgentsViewModel) sendCmd(id, text string) tea.Cmd { +func (m *Model) sendCmd(id, text string) tea.Cmd { conn, gen, target := m.Conn, m.viewGen, m.label(id, "agent") handle, err := daemon.NewSubmission(id, daemon.SubmissionRequest{Content: &text}) if err == nil { m.pendingOperations[handle.ID()] = agentPendingOperation{Handle: handle, Action: "send a message to " + target, Draft: text, InFlight: true} } return func() tea.Msg { - result := agentsSentMsg{Gen: gen, Action: "send a message to " + target, Handle: handle, Draft: text, Err: err} + result := OperationResultMsg{Gen: gen, Action: "send a message to " + target, Handle: handle, Draft: text, Err: err} if err == nil { _, result.Err = daemon.SubmitOperation(context.Background(), conn, handle) } @@ -62,12 +62,12 @@ func (m *AgentsViewModel) sendCmd(id, text string) tea.Cmd { } } -func (m *AgentsViewModel) spawnCmd(parent, name, task string) tea.Cmd { +func (m *Model) spawnCmd(parent, name, task string) tea.Cmd { conn, gen := m.Conn, m.viewGen draft := "/spawn " + name + " " + task if name == "" || task == "" { return func() tea.Msg { - return agentsSentMsg{Gen: gen, Action: "start an agent", Draft: draft, Err: errors.New("use /spawn ")} + return OperationResultMsg{Gen: gen, Action: "start an agent", Draft: draft, Err: errors.New("use /spawn ")} } } handle, err := daemon.NewCreation(daemon.CreateSessionRequest{Kind: "child", ParentID: parent, Address: name, Name: name, Task: task}) @@ -75,7 +75,7 @@ func (m *AgentsViewModel) spawnCmd(parent, name, task string) tea.Cmd { m.pendingOperations[handle.ID()] = agentPendingOperation{Handle: handle, Action: "start " + name, Draft: draft, InFlight: true} } return func() tea.Msg { - result := agentsSentMsg{Gen: gen, Action: "start " + name, Notice: "spawned " + name, Handle: handle, Draft: draft, Err: err} + result := OperationResultMsg{Gen: gen, Action: "start " + name, Notice: "spawned " + name, Handle: handle, Draft: draft, Err: err} if err == nil { _, result.Err = daemon.CreateSessionOperation(context.Background(), conn, handle) } @@ -87,10 +87,10 @@ func agentOperationTick(id string, gen int) tea.Cmd { return tea.Tick(300*time.Millisecond, func(time.Time) tea.Msg { return agentsOperationPollMsg{ID: id, Gen: gen} }) } -func (m AgentsViewModel) resolveAgentOperation(pending agentPendingOperation) tea.Cmd { +func (m Model) resolveAgentOperation(pending agentPendingOperation) tea.Cmd { conn, gen := m.Conn, m.viewGen return func() tea.Msg { - result := agentsSentMsg{Gen: gen, Action: pending.Action, Handle: pending.Handle, Draft: pending.Draft, Recovery: true, Notice: "Confirmed: " + pending.Action} + result := OperationResultMsg{Gen: gen, Action: pending.Action, Handle: pending.Handle, Draft: pending.Draft, Recovery: true, Notice: "Confirmed: " + pending.Action} if pending.Handle.IsCreation() { _, result.Err = daemon.ResolveCreation(context.Background(), conn, pending.Handle) } else { @@ -108,7 +108,7 @@ func (m AgentsViewModel) resolveAgentOperation(pending agentPendingOperation) te } // askDelete asks before deleting an agent, and says what goes with it. -func (m *AgentsViewModel) askDelete(id string) { +func (m *Model) askDelete(id string) { what := m.label(id, "") switch below := m.below(id); { case below == 1: @@ -116,22 +116,22 @@ func (m *AgentsViewModel) askDelete(id string) { case below > 1: what += fmt.Sprintf(" and the %d agents below it", below) } - m.confirm.ask("delete", id, "delete", "Their transcripts and work will also be deleted. Delete "+what+"?") + m.confirm.Ask("delete", id, "delete", "Their transcripts and work will also be deleted. Delete "+what+"?") } -func (m AgentsViewModel) key(msg tea.KeyPressMsg) (AgentsViewModel, tea.Cmd) { +func (m Model) key(msg tea.KeyPressMsg) (Model, tea.Cmd) { s, empty := msg.String(), m.input.Value() == "" - if m.rename.active() { - return m, m.rename.key(msg) + if m.rename.Active() { + return m, m.rename.Key(msg) } - if m.confirm.asking() { - id := m.confirm.target - if m.confirm.key(msg) { - m.confirm.dismiss() + if m.confirm.Asking() { + id := m.confirm.Target + if m.confirm.Key(msg) { + m.confirm.Dismiss() m.say("deleting " + m.label(id, "") + "…") return m, m.deleteCmd(id) } - if !m.confirm.asking() { + if !m.confirm.Asking() { m.say("kept") } return m, nil @@ -152,9 +152,9 @@ func (m AgentsViewModel) key(msg tea.KeyPressMsg) (AgentsViewModel, tea.Cmd) { return m, m.restartStream() case s == "ctrl+r": if n := m.nodes[m.selected]; n != nil && n.id != agentsYou { - m.rename.open(n.id, n.name, "name this agent") - if n := m.nodes[m.rename.id]; n != nil { - m.rename.etag = n.session.ETag + m.rename.Open(n.id, n.name, "name this agent") + if n := m.nodes[m.rename.ID]; n != nil { + m.rename.ETag = n.session.ETag } } return m, nil @@ -172,7 +172,7 @@ func (m AgentsViewModel) key(msg tea.KeyPressMsg) (AgentsViewModel, tea.Cmd) { m.input.SetValue("") return m, nil } - return m, func() tea.Msg { return AgentsDoneMsg{} } + return m, func() tea.Msg { return DoneMsg{} } case s == "tab" || (empty && (s == "right" || s == "down")): m.cycle(1) return m, tea.Batch(m.hold(), m.seedCmd()) @@ -193,7 +193,7 @@ func (m AgentsViewModel) key(msg tea.KeyPressMsg) (AgentsViewModel, tea.Cmd) { n.session = daemon.Session{ID: n.id, Title: n.name, Model: n.model} } sess := n.session - return m, func() tea.Msg { return AgentsAttachMsg{Session: sess} } + return m, func() tea.Msg { return AttachMsg{Session: sess} } } m.input.SetValue("") if rest, ok := strings.CutPrefix(text, "/spawn "); ok { @@ -212,12 +212,12 @@ func renameBlank(n *agentNode) string { return cmp.Or(n.address, "its latest message's title") } -func (m *AgentsViewModel) say(text string) { +func (m *Model) say(text string) { m.notice = text m.noticeT = 3 } -func (m *AgentsViewModel) cycle(d int) { +func (m *Model) cycle(d int) { if n := len(m.order); n > 0 { i := max(0, slices.Index(m.order, m.selected)) m.selected = m.order[(i+d+n)%n] diff --git a/cli/internal/tui/agents_order.go b/cli/internal/tui/agents/order.go similarity index 99% rename from cli/internal/tui/agents_order.go rename to cli/internal/tui/agents/order.go index acc2369fa..d26708712 100644 --- a/cli/internal/tui/agents_order.go +++ b/cli/internal/tui/agents/order.go @@ -1,4 +1,4 @@ -package tui +package agents import ( "cmp" diff --git a/cli/internal/tui/agents_order_test.go b/cli/internal/tui/agents/order_test.go similarity index 97% rename from cli/internal/tui/agents_order_test.go rename to cli/internal/tui/agents/order_test.go index 0f50571eb..1ab304db9 100644 --- a/cli/internal/tui/agents_order_test.go +++ b/cli/internal/tui/agents/order_test.go @@ -1,4 +1,4 @@ -package tui +package agents // The agents canvas orders and folds an agent's siblings in the client alone: // a daemon run cannot see which dot comes first, that a closed batch folds, @@ -64,9 +64,9 @@ var orderWorkingOldIdle = func() []orderAgent { return agents }() -func orderModel(t *testing.T, agents ...orderAgent) AgentsViewModel { +func orderModel(t *testing.T, agents ...orderAgent) Model { t.Helper() - m := NewAgentsViewModel(nil, "root") + m := New(nil, "root") m.Gen = 1 m.streamReady = true m.SetSize(200, 60) @@ -76,7 +76,7 @@ func orderModel(t *testing.T, agents ...orderAgent) AgentsViewModel { // shownUnder is the order of the dots under parent, its fold by the fold's // id and without the agents in it. -func shownUnder(m AgentsViewModel, parent string) []string { +func shownUnder(m Model, parent string) []string { fold := m.folds[agentsFoldPrefix+parent] var out []string for _, id := range m.order { diff --git a/cli/internal/tui/agents_preview.go b/cli/internal/tui/agents/preview.go similarity index 93% rename from cli/internal/tui/agents_preview.go rename to cli/internal/tui/agents/preview.go index 31d564716..f114d98c7 100644 --- a/cli/internal/tui/agents_preview.go +++ b/cli/internal/tui/agents/preview.go @@ -1,7 +1,8 @@ -package tui +package agents import ( "albedo/cli/internal/daemon" + "albedo/cli/internal/tui/chrome" "iter" "slices" "strings" @@ -163,7 +164,7 @@ func (tail *agentTail) setCode(code *daemon.ToolCodePreview) { type agentTailCache struct { node *agentNode - ink ink + ink chrome.Ink rows []string revision uint64 width int @@ -172,7 +173,7 @@ type agentTailCache struct { // refreshTail runs after updates, never from View. Only the selected node // needs wrapped rows; animation-only frames reuse the previous result. -func (m *AgentsViewModel) refreshTail() { +func (m *Model) refreshTail() { node := m.nodes[m.selected] width, height := m.paneWidth()-1, max(0, m.Height) cache := &m.tailCache @@ -180,7 +181,7 @@ func (m *AgentsViewModel) refreshTail() { *cache = agentTailCache{} return } - if cache.node == node && cache.revision == node.revision && cache.width == width && cache.height == height && cache.ink == transcriptInk { + if cache.node == node && cache.revision == node.revision && cache.width == width && cache.height == height && cache.ink == chrome.CurrentInk { return } rows := make([]string, 0, height) @@ -207,5 +208,5 @@ func (m *AgentsViewModel) refreshTail() { } } slices.Reverse(rows) - *cache = agentTailCache{node: node, rows: rows, ink: transcriptInk, revision: node.revision, width: width, height: height} + *cache = agentTailCache{node: node, rows: rows, ink: chrome.CurrentInk, revision: node.revision, width: width, height: height} } diff --git a/cli/internal/tui/agents/render.go b/cli/internal/tui/agents/render.go new file mode 100644 index 000000000..720d0e1f2 --- /dev/null +++ b/cli/internal/tui/agents/render.go @@ -0,0 +1,295 @@ +package agents + +import ( + "albedo/cli/internal/daemon" + "albedo/cli/internal/terminalui" + "fmt" + "maps" + "slices" + "strings" + + "albedo/cli/internal/tui/chrome" + + "github.com/charmbracelet/x/ansi" +) + +func (m Model) paneHeader() []string { + // One column goes to the space after the divider. + width := m.paneWidth() - 1 + if width <= 0 { + width = max(1, m.Width-2) + } + rows := make([]string, 0, 12) + if f := m.folds[m.selected]; f != nil { + return m.foldPane(f, width) + } + n := m.nodes[m.selected] + if n == nil || width <= 0 { + return rows + } + colors := chrome.AgentColors() + styled := func(hue chrome.RGB, s string) string { return chrome.Sgr(hue.Hex(), "") + s + chrome.AnsiReset } + state := "idle" + switch { + case n.id == agentsYou: + state = "that's you" + case n.closed: + state = "closed" + case n.session.Status.Phase != nil: + switch *n.session.Status.Phase { + case daemon.PhasePreparing: + state = "preparing" + case daemon.PhaseInterrupted: + state = "interrupting" + case daemon.PhaseIdle, daemon.PhaseResting: + state = "idle" + default: + state = "running" + } + case n.running: + state = "running" + case n.peer: + state = "outside this tree" + } + rows = append(rows, styled(n.hue, "● ")+chrome.DefaultStyles.Bold.Render(n.name)+" "+chrome.DefaultStyles.Faint.Render(state)) + var meta []string + if n.model != "" { + meta = append(meta, n.model) + } + if n.id != agentsYou { + meta = append(meta, fmt.Sprintf("depth %d", n.depth)) + } + if parent := m.nodes[n.parent]; parent != nil { + meta = append(meta, "parent "+parent.name) + } + rows = append(rows, chrome.DefaultStyles.Faint.Render(ansi.Truncate(strings.Join(meta, " · "), width, "…"))) + if usage := providerCall(n.usage); usage != "" { + rows = append(rows, chrome.DefaultStyles.Faint.Render(ansi.Truncate(usage, width, "…"))) + } + rows = append(rows, "") + for _, field := range []struct{ label, text string }{{"request", n.currentRequest}, {"latest", n.latestProgress}} { + if field.text == "" { + continue + } + rows = append(rows, chrome.DefaultStyles.Muted.Render(field.label)) + wrapped := strings.Split(ansi.Wrap(field.text, max(1, width), " "), "\n") + if len(wrapped) > 3 { + wrapped = wrapped[:3] + wrapped[2] = ansi.Truncate(wrapped[2], max(1, width-1), "") + "…" + } + rows = append(rows, wrapped...) + } + if len(n.mail) > 0 { + rows = append(rows, chrome.DefaultStyles.Muted.Render("mail")) + for _, mail := range n.mail[max(0, len(n.mail)-5):] { + var arrow string + if mail.incoming { + arrow = styled(colors.Mail, "← ") + } else { + arrow = chrome.DefaultStyles.Faint.Render("→ ") + } + rows = append(rows, ansi.Truncate(arrow+mail.who+" "+chrome.DefaultStyles.Faint.Render(mail.kind), width, "…")) + } + rows = append(rows, "") + } + live := chrome.DefaultStyles.Muted.Render("tail") + if n.running { + live += " " + styled(n.hue, "●") + chrome.DefaultStyles.Faint.Render(" live") + } + if n.tail.omitted || n.preview.omitted { + live += chrome.DefaultStyles.Faint.Render(" · earlier output omitted") + } + return append(rows, live) +} + +// providerCall words what the provider reported for an agent's latest call, or +// is empty when no call was reported. +func providerCall(usage *daemon.Usage) string { + if usage == nil { + return "" + } + var parts []string + if usage.PromptTokens != nil { + parts = append(parts, compactCount(*usage.PromptTokens)+" in") + } + if usage.CompletionTokens != nil { + parts = append(parts, compactCount(*usage.CompletionTokens)+" out") + } + return "last call " + strings.Join(parts, " · ") + " tok" +} + +// foldPane lists a fold's closed agents, newest turn first, ending in a +// blank row where an agent's pane has its tail heading. +func (m Model) foldPane(f *agentFold, width int) []string { + glyph, verb := "▸ ", "enter or → shows them" + if f.open { + glyph, verb = "▾ ", "enter or ← folds them" + } + rows := []string{ + chrome.DefaultStyles.Faint.Render(glyph) + chrome.DefaultStyles.Bold.Render(fmt.Sprintf("%d closed agents", len(f.members))), + chrome.DefaultStyles.Faint.Render(ansi.Truncate("under "+m.label(f.parent, "")+" · "+verb, width, "…")), + "", + } + for _, id := range f.members { + n := m.nodes[id] + rows = append(rows, ansi.Truncate(chrome.DefaultStyles.Faint.Render("✓ ")+n.name+chrome.DefaultStyles.Faint.Render(" "+n.model), width, "…")) + } + return append(rows, "") +} + +func (m Model) pane(height int) []string { + rows := m.paneHeader() + if m.folds[m.selected] != nil { + return rows + } + room := max(0, height-len(rows)) + if room == 0 || len(rows) == 0 { + return rows + } + wrapped := m.tailCache.rows + if len(wrapped) == 0 { + return append(rows, chrome.DefaultStyles.Faint.Render("nothing yet")) + } + return append(rows, wrapped[max(0, len(wrapped)-room):]...) +} + +// drawTail wraps one tail line to width and styles it by kind. +func drawTail(line tailLine, width, limit int) []string { + gutter, inner := "", width + format := func(s ...string) string { return strings.Join(s, "") } + switch line.kind { + case tailThinking: + format = func(s ...string) string { return chrome.DefaultStyles.Faint.Render(chrome.AnsiItalic + s[0]) } + case tailCode: + gutter, inner, format = chrome.DefaultStyles.Decor.Render("│ "), width-2, chrome.DefaultStyles.Muted.Render + case tailOutput: + gutter, inner, format = chrome.DefaultStyles.Decor.Render("⎿ "), width-2, chrome.DefaultStyles.Faint.Render + case tailMeta: + format = chrome.DefaultStyles.Faint.Render + } + wrapped := ansi.Hardwrap(line.text, max(8, inner), true) + start := len(wrapped) + for range limit { + index := strings.LastIndexByte(wrapped[:start], '\n') + if index < 0 { + start = 0 + break + } + start = index + } + if start > 0 { + start++ + } + var out []string + for part := range strings.SplitSeq(wrapped[start:], "\n") { + // A cached row must not retain the rest of a long wrapped line. + out = append(out, gutter+format(strings.Clone(part))) + } + return out +} + +// graphOffset scrolls a tall swarm so the selected dot and its children's +// dots stay in view, the selected one first when both do not fit. +func (m Model) graphOffset(height int) int { + _, y, ok := m.at(m.selected) + if !ok { + return 0 + } + bottom := y + 3 + for _, child := range m.nodes { + if child.parent == m.selected { + bottom = max(bottom, child.y+2) + } + } + return max(0, min(bottom-height, y-1)) +} + +func (m Model) View() string { + if m.Width <= 0 || m.Height <= 0 { + return "" + } + live, written := 0, 0 + for id, n := range m.nodes { + if id == agentsYou { + continue + } + if n.running { + live++ + } + written += n.outputBytes + } + right := chrome.DefaultStyles.Faint.Render(fmt.Sprintf("%d agents · %d running · ▴%s out", len(m.nodes)-1, live, compactBytes(written))) + page := terminalui.Graph{ + Header: chrome.TitleRule(m.Width-1, chrome.Brand("albedo")+" "+chrome.DefaultStyles.Muted.Render("/agents"), right), + Divider: chrome.DefaultStyles.Decor.Render("│"), + Detail: m.pane, + Canvas: func(w, h int) []string { + if h == 0 { + return nil + } + canvas := newCanvas(w, h, m.graphOffset(h)) + m.drawEdges(canvas) + m.drawNodes(canvas) + lines := make([]string, h) + for i := range lines { + lines[i] = canvas.line(i) + } + return lines + }, + } + if m.paneWidth() == 0 { + // The stacked detail has no live tail. Omit its tail heading. + header := m.paneHeader() + header = header[:max(0, len(header)-1)] + for len(header) > 0 && header[len(header)-1] == "" { + header = header[:len(header)-1] + } + page.Summary = header + page.Rule = chrome.DefaultStyles.Decor.Render(strings.Repeat("─", max(0, m.Width-2))) + } + status := "" + switch { + case m.rename.Active(): + status = chrome.DefaultStyles.Muted.Render("rename ") + chrome.DefaultStyles.Bold.Render(m.label(m.rename.ID, "")) + if n := m.nodes[m.rename.ID]; n != nil && n.address != "" { + status += chrome.DefaultStyles.Faint.Render(" · its family can still mail it at ") + chrome.DefaultStyles.Muted.Render(n.address) + } + case m.err != nil: + status = chrome.DefaultStyles.Error.Render(m.err.Error() + " · ctrl+l retries") + case len(m.pendingOperations) > 0: + ids := slices.Sorted(maps.Keys(m.pendingOperations)) + status = chrome.DefaultStyles.Error.Render("Unresolved request: " + strings.Join(ids, ", ")) + case m.noticeT > 0: + status = chrome.DefaultStyles.Muted.Render(m.notice) + } + if m.confirm.Asking() { + page.Actions = strings.Split(m.confirm.Footer(max(1, m.Width), ""), "\n") + } else { + page.Actions = append(page.Actions, " "+status) + } + target := m.label(m.selected, "agent") + input := m.input.View() + switch { + case m.input.Value() != "": + case m.folds[m.selected] != nil: + input = chrome.DefaultStyles.Faint.Render("closed agents, folded · pick one to message it") + default: + input = chrome.DefaultStyles.Faint.Render("message " + target + "… or /spawn ") + } + hints := []chrome.Hint{{Key: "tab", Does: "next agent"}, {Key: "enter", Does: "open or send"}, {Key: "ctrl+r", Does: "rename"}, {Key: "ctrl+x", Does: "delete"}, {Key: "ctrl+f", Does: "find"}, {Key: "esc", Does: "back"}} + if f := m.folds[m.selected]; f != nil { + hints = []chrome.Hint{{Key: "tab", Does: "next agent"}, {Key: "enter", Does: "show"}, {Key: "ctrl+f", Does: "find"}, {Key: "esc", Does: "back"}} + if f.open { + hints[1].Does = "fold" + } + } + switch n := m.nodes[m.rename.ID]; { + case m.find.active(): + page.Actions = append(page.Actions, " "+m.findLine(), chrome.FooterLine(m.Width, []chrome.Hint{{Key: "↑↓", Does: "next match"}, {Key: "enter", Does: "go there"}, {Key: "esc", Does: "back"}}, "", false)) + case n != nil && m.rename.Active(): + page.Actions = append(page.Actions, " "+chrome.DefaultStyles.Prompt.Render("✎ ")+m.rename.View(m.Width-chrome.PromptMarkWidth-1), " "+chrome.RenameHints("restores "+renameBlank(n))) + default: + page.Actions = append(page.Actions, " "+chrome.PromptLead()+input, chrome.FooterLine(m.Width, hints, "", false)) + } + return page.Render(m.Width, m.Height) +} diff --git a/cli/internal/tui/agents/reopen_test.go b/cli/internal/tui/agents/reopen_test.go new file mode 100644 index 000000000..55432b583 --- /dev/null +++ b/cli/internal/tui/agents/reopen_test.go @@ -0,0 +1,33 @@ +package agents + +import ( + "errors" + "testing" +) + +func TestReopenKeepsDraftAndResolvesOnlyRetainedOperations(t *testing.T) { + m := New(nil, "root") + m.Init() + m.input.SetValue("unfinished draft") + m.sendCmd("child", "sent before leaving") + if len(m.pendingOperations) != 1 { + t.Fatal("missing pending send") + } + streamGen, viewGen := m.Gen, m.viewGen + m.Reopen(nil, "root") + m.Init() + if m.input.Value() != "unfinished draft" || len(m.pendingOperations) != 1 { + t.Fatal("reopening dropped the draft or pending send") + } + m, _ = m.Update(agentsSnapshotMsg{Gen: streamGen, Err: errors.New("obsolete snapshot")}) + m, _ = m.Update(OperationResultMsg{Gen: viewGen, Notice: "obsolete action"}) + if m.err != nil || m.notice != "" { + t.Fatalf("reopened view accepted stale messages: %v, %q", m.err, m.notice) + } + for _, pending := range m.pendingOperations { + m, _ = m.Update(OperationResultMsg{Gen: viewGen, Handle: pending.Handle, Notice: "sent"}) + } + if len(m.pendingOperations) != 0 || m.notice != "sent" || m.input.Value() != "unfinished draft" { + t.Fatal("late send result did not reconcile with the reopened view") + } +} diff --git a/cli/internal/tui/shot_agents_test.go b/cli/internal/tui/agents/shot_agents_test.go similarity index 70% rename from cli/internal/tui/shot_agents_test.go rename to cli/internal/tui/agents/shot_agents_test.go index 524854426..0c7e6d622 100644 --- a/cli/internal/tui/shot_agents_test.go +++ b/cli/internal/tui/agents/shot_agents_test.go @@ -1,4 +1,4 @@ -package tui +package agents import ( "errors" @@ -6,12 +6,14 @@ import ( "albedo/cli/internal/daemon" + "albedo/cli/internal/testutil/tuishots" + tea "charm.land/bubbletea/v2" ) // agentsShotModel is agentsFixture's tree without a *testing.T, for the gallery. -func agentsShotModel(width, height int) AgentsViewModel { - m := NewAgentsViewModel(nil, "lead") +func agentsShotModel(width, height int) Model { + m := New(nil, "lead") m.Gen = 1 m.streamReady = true m.SetSize(width, height) @@ -29,7 +31,7 @@ func agentsShotModel(width, height int) AgentsViewModel { // closed leaves under lead and two under coder fold, then keys are pressed. func agentsFamilyShot(selected string, keys ...tea.KeyPressMsg) func(width, height int) string { return func(width, height int) string { - m := NewAgentsViewModel(nil, "lead") + m := New(nil, "lead") m.Gen = 1 m.streamReady = true m.SetSize(width, height) @@ -94,7 +96,7 @@ func agentsDeleteShot(id string, keys ...tea.KeyPressMsg) func(width, height int } // agentsShot draws the tree after setup. -func agentsShot(setup func(*AgentsViewModel)) func(width, height int) string { +func agentsShot(setup func(*Model)) func(width, height int) string { return func(width, height int) string { m := agentsShotModel(width, height) setup(&m) @@ -105,7 +107,7 @@ func agentsShot(setup func(*AgentsViewModel)) func(width, height int) string { // agentsBare is the view before its first snapshot, after msgs. func agentsBare(msgs ...tea.Msg) func(width, height int) string { return func(width, height int) string { - m := NewAgentsViewModel(nil, "lead") + m := New(nil, "lead") m.Gen = 1 m.streamReady = true m.SetSize(width, height) @@ -118,9 +120,9 @@ func agentsBare(msgs ...tea.Msg) func(width, height int) string { func init() { enter := tea.KeyPressMsg{Code: tea.KeyEnter} - registerShots("agents", - shotState{"graph", agentsShot(func(m *AgentsViewModel) { m.selected = "coder" })}, - shotState{"graph-activity", agentsShot(func(m *AgentsViewModel) { + tuishots.Register("agents", + tuishots.State{Name: "graph", View: agentsShot(func(m *Model) { m.selected = "coder" })}, + tuishots.State{Name: "graph-activity", View: agentsShot(func(m *Model) { m.selected = "coder" m.apply(daemon.AgentEvent{Type: "mail", From: "lead", To: "coder", Kind: "message", Bytes: 3000}) m.apply(daemon.AgentEvent{Type: "mail", From: "coder", To: "lead", Kind: "message", Bytes: 420}) @@ -134,27 +136,27 @@ func init() { m.step() } })}, - shotState{"family-folded", agentsFamilyShot("coder")}, - shotState{"fold-selected", agentsFamilyShot(agentsFoldPrefix + "lead")}, - shotState{"fold-expanded", agentsFamilyShot(agentsFoldPrefix+"lead", tea.KeyPressMsg{Code: tea.KeyRight})}, - shotState{"find-folded", agentsFamilyShot("coder", findKeys("bench")...)}, - shotState{"find-none", agentsFamilyShot("coder", findKeys("zzz")...)}, - shotState{"root-selected", agentsShot(func(m *AgentsViewModel) { m.selected = "lead" })}, - shotState{"no-agents", agentsBare(agentsSnapshotMsg{Gen: 1, Root: "lead", Nodes: []daemon.AgentNode{ + tuishots.State{Name: "family-folded", View: agentsFamilyShot("coder")}, + tuishots.State{Name: "fold-selected", View: agentsFamilyShot(agentsFoldPrefix + "lead")}, + tuishots.State{Name: "fold-expanded", View: agentsFamilyShot(agentsFoldPrefix+"lead", tea.KeyPressMsg{Code: tea.KeyRight})}, + tuishots.State{Name: "find-folded", View: agentsFamilyShot("coder", findKeys("bench")...)}, + tuishots.State{Name: "find-none", View: agentsFamilyShot("coder", findKeys("zzz")...)}, + tuishots.State{Name: "root-selected", View: agentsShot(func(m *Model) { m.selected = "lead" })}, + tuishots.State{Name: "no-agents", View: agentsBare(agentsSnapshotMsg{Gen: 1, Root: "lead", Nodes: []daemon.AgentNode{ {Session: daemon.Session{ID: "lead", Title: "lead", Model: "gpt-6-luna"}, Name: "lead"}, }})}, - shotState{"loading", agentsBare()}, - shotState{"load-failed", agentsBare(agentsSnapshotMsg{Gen: 1, Err: errors.New("daemon connection unavailable")})}, - shotState{"delete-confirm", agentsDeleteShot("coder")}, - shotState{"delete-leaf-confirm", agentsDeleteShot("scout")}, - shotState{"delete-kept", agentsDeleteShot("coder", tea.KeyPressMsg{Code: tea.KeyEscape})}, - shotState{"deleting", agentsDeleteShot("coder", enter)}, - shotState{"delete-failed", func(width, height int) string { + tuishots.State{Name: "loading", View: agentsBare()}, + tuishots.State{Name: "load-failed", View: agentsBare(agentsSnapshotMsg{Gen: 1, Err: errors.New("daemon connection unavailable")})}, + tuishots.State{Name: "delete-confirm", View: agentsDeleteShot("coder")}, + tuishots.State{Name: "delete-leaf-confirm", View: agentsDeleteShot("scout")}, + tuishots.State{Name: "delete-kept", View: agentsDeleteShot("coder", tea.KeyPressMsg{Code: tea.KeyEscape})}, + tuishots.State{Name: "deleting", View: agentsDeleteShot("coder", enter)}, + tuishots.State{Name: "delete-failed", View: func(width, height int) string { m := agentsShotModel(width, height) m.selected = "coder" m, _ = m.key(tea.KeyPressMsg{Code: 'x', Mod: tea.ModCtrl}) m, _ = m.key(enter) - m, _ = m.Update(agentsSentMsg{Gen: m.viewGen, Action: "delete coder", Err: errors.New("coder changed since the view loaded it")}) + m, _ = m.Update(OperationResultMsg{Gen: m.viewGen, Action: "delete coder", Err: errors.New("coder changed since the view loaded it")}) return m.View() }}, ) diff --git a/cli/internal/tui/agents/shot_test.go b/cli/internal/tui/agents/shot_test.go new file mode 100644 index 000000000..69c45f00a --- /dev/null +++ b/cli/internal/tui/agents/shot_test.go @@ -0,0 +1,9 @@ +package agents + +import ( + "albedo/cli/internal/testutil/tuishots" + "testing" +) + +func TestShotGallery(t *testing.T) { tuishots.RenderGallery(t) } +func TestEveryShotStateFitsItsTerminal(t *testing.T) { tuishots.CheckFits(t) } diff --git a/cli/internal/tui/agents_subscription.go b/cli/internal/tui/agents/subscription.go similarity index 90% rename from cli/internal/tui/agents_subscription.go rename to cli/internal/tui/agents/subscription.go index b768a4c66..1a4ae0e35 100644 --- a/cli/internal/tui/agents_subscription.go +++ b/cli/internal/tui/agents/subscription.go @@ -1,4 +1,4 @@ -package tui +package agents import ( "context" @@ -11,12 +11,12 @@ import ( // Close stops the stream and invalidates batches, completions, and timers // already queued for this view. -func (m *AgentsViewModel) Close() { +func (m *Model) Close() { m.viewGen++ m.stopStream() } -func (m *AgentsViewModel) stopStream() { +func (m *Model) stopStream() { if m.cancel != nil { m.cancel() m.cancel = nil @@ -27,7 +27,7 @@ func (m *AgentsViewModel) stopStream() { m.snapshotInFlight, m.snapshotDirty = false, false } -func (m AgentsViewModel) snapshotCmd(gen int) tea.Cmd { +func (m Model) snapshotCmd(gen int) tea.Cmd { conn, id := m.Conn, m.SessionID return func() tea.Msg { if conn == nil { @@ -38,7 +38,7 @@ func (m AgentsViewModel) snapshotCmd(gen int) tea.Cmd { } } -func (m *AgentsViewModel) startStream(gen int) tea.Cmd { +func (m *Model) startStream(gen int) tea.Cmd { if m.Conn == nil { return nil } @@ -73,7 +73,7 @@ func (m *AgentsViewModel) startStream(gen int) tea.Cmd { return waitAgents(events, gen) } -func (m *AgentsViewModel) restartStream() tea.Cmd { +func (m *Model) restartStream() tea.Cmd { m.stopStream() m.snapshotRevision++ for _, n := range m.nodes { @@ -102,7 +102,7 @@ func waitAgents(events <-chan tea.Msg, gen int) tea.Cmd { } // seedCmd loads the selected agent's recent history once; failures retry. -func (m *AgentsViewModel) seedCmd() tea.Cmd { +func (m *Model) seedCmd() tea.Cmd { n := m.nodes[m.selected] if !m.streamReady || m.snapshotInFlight || m.err != nil || n == nil || n.seeded || n.id == agentsYou || m.Conn == nil { return nil diff --git a/cli/internal/tui/agents_view.go b/cli/internal/tui/agents/view.go similarity index 82% rename from cli/internal/tui/agents_view.go rename to cli/internal/tui/agents/view.go index 2a476ec8b..bf744cec8 100644 --- a/cli/internal/tui/agents_view.go +++ b/cli/internal/tui/agents/view.go @@ -1,4 +1,5 @@ -package tui +// Package agents implements the interactive agent tree and its subscriptions. +package agents import ( "cmp" @@ -9,6 +10,8 @@ import ( "albedo/cli/internal/daemon" + "albedo/cli/internal/tui/chrome" + "charm.land/bubbles/v2/textinput" tea "charm.land/bubbletea/v2" ) @@ -19,11 +22,10 @@ import ( // it; the selected agent's tail sits beside it, and what you type goes to // that agent as you. -type ChatOpenAgentsMsg struct{} -type AgentsDoneMsg struct{} +type DoneMsg struct{} -// AgentsAttachMsg opens the agent's session in the chat screen. -type AgentsAttachMsg struct{ Session daemon.Session } +// AttachMsg opens the agent's session in the chat screen. +type AttachMsg struct{ Session daemon.Session } type agentsSnapshotMsg struct { Err error @@ -38,24 +40,24 @@ type agentsEventsMsg struct { } type agentsStreamClosedMsg struct { - Gen int Err error + Gen int } type agentsSnapshotRetryMsg struct{ Gen int } // agentsSeedMsg is an agent's recent history, so its tail starts from where // it is rather than empty. type agentsSeedMsg struct { - Snapshot int + Session *daemon.Session ID string Items []daemon.PreviewItem - Session *daemon.Session + Snapshot int Gen int } type agentsSeedErrMsg struct { - Snapshot int Err error ID string + Snapshot int Gen int } @@ -66,14 +68,14 @@ type agentsSettleMsg struct { Until time.Time Gen int } -type agentsSentMsg struct { +type OperationResultMsg struct { + Err error Handle *daemon.OperationHandle Draft string - Recovery bool - Err error Action string Notice string Gen int + Recovery bool } type agentsOperationPollMsg struct { ID string @@ -121,7 +123,7 @@ type agentNode struct { tail agentTail preview agentTail revision uint64 - hue rgb + hue chrome.RGB rate float64 flash float64 phase float64 @@ -151,46 +153,45 @@ type tailLine struct { kind tailKind } -type AgentsViewModel struct { - seenMail []string - pendingOperations map[string]agentPendingOperation - bufferedActivity map[string]daemon.AgentEvent +type Model struct { last time.Time + holdUntil time.Time err error + streamCtx context.Context + pendingOperations map[string]agentPendingOperation + bufferedActivity map[string]daemon.AgentEvent heat map[string]float64 events chan tea.Msg - streamCtx context.Context - streamReady bool - snapshotInFlight bool - snapshotDirty bool - snapshotRevision int cancel context.CancelFunc Conn *daemon.Connection nodes map[string]*agentNode folds map[string]*agentFold // by fold id, rebuilt by layout expanded map[string]bool // parents whose closed agents are shown held map[string]agentRank // the ranks the order holds to - holdUntil time.Time SessionID string root string selected string - - notice string - confirm confirm // the delete waiting for enter; esc keeps the agent - packets []agentPacket - floats []agentFloat - order []string - input textinput.Model - rename renameField - find agentFind - tailCache agentTailCache - Width int - clock float64 - Height int - Gen int - viewGen int // User operation outcomes survive stream replacement. - noticeT float64 - ticking bool // a frame tick is in flight + notice string + confirm chrome.Confirm // the delete waiting for enter; esc keeps the agent + seenMail []string + packets []agentPacket + floats []agentFloat + order []string + input textinput.Model + rename chrome.RenameField + find agentFind + tailCache agentTailCache + snapshotRevision int + Width int + clock float64 + Height int + Gen int + viewGen int // User operation outcomes survive stream replacement. + noticeT float64 + streamReady bool + snapshotInFlight bool + snapshotDirty bool + ticking bool // a frame tick is in flight } const ( @@ -213,11 +214,11 @@ type agentFold struct { var agentsBars = []rune("▁▂▃▄▅▆▇█") -func NewAgentsViewModel(conn *daemon.Connection, sessionID string) AgentsViewModel { - input := newField() +func New(conn *daemon.Connection, sessionID string) Model { + input := chrome.NewField() input.CharLimit = 4000 input.Focus() - return AgentsViewModel{ + return Model{ Conn: conn, pendingOperations: map[string]agentPendingOperation{}, SessionID: sessionID, @@ -231,14 +232,27 @@ func NewAgentsViewModel(conn *daemon.Connection, sessionID string) AgentsViewMod } } -func (m *AgentsViewModel) SetSize(w, h int) { +// Reopen rebuilds the tree while preserving the draft and outstanding sends. +// Keep both generations monotonic so queued messages from the old tree expire. +func (m *Model) Reopen(conn *daemon.Connection, sessionID string) { + m.Close() + next := New(conn, sessionID) + next.Gen, next.viewGen = m.Gen, m.viewGen + if m.pendingOperations != nil { + next.pendingOperations = m.pendingOperations + } + next.input.SetValue(m.input.Value()) + *m = next +} + +func (m *Model) SetSize(w, h int) { m.Width = w m.Height = h m.layout() m.refreshTail() } -func (m *AgentsViewModel) Init() tea.Cmd { +func (m *Model) Init() tea.Cmd { m.viewGen++ m.Gen++ m.ticking = true @@ -251,13 +265,13 @@ func (m *AgentsViewModel) Init() tea.Cmd { return tea.Batch(cmds...) } -func (m AgentsViewModel) frameCmd(gen int) tea.Cmd { +func (m Model) frameCmd(gen int) tea.Cmd { return tea.Tick(agentsFrame, func(time.Time) tea.Msg { return agentsFrameMsg{Gen: gen} }) } // Update handles msg, then starts the frame tick again if something began to // move while it was stopped. -func (m AgentsViewModel) Update(msg tea.Msg) (AgentsViewModel, tea.Cmd) { +func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { m, cmd := m.update(msg) m.refreshTail() if m.ticking || !m.moving() { @@ -267,7 +281,7 @@ func (m AgentsViewModel) Update(msg tea.Msg) (AgentsViewModel, tea.Cmd) { return m, tea.Batch(cmd, m.frameCmd(m.Gen)) } -func (m AgentsViewModel) update(msg tea.Msg) (AgentsViewModel, tea.Cmd) { +func (m Model) update(msg tea.Msg) (Model, tea.Cmd) { if g, ok := msg.(agentsGenMsg); ok && g.gen() != m.Gen { return m, nil } @@ -316,11 +330,11 @@ func (m AgentsViewModel) update(msg tea.Msg) (AgentsViewModel, tea.Cmd) { if m.nodes[m.selected] == nil { m.selected = m.root } - if m.nodes[m.confirm.target] == nil { - m.confirm.dismiss() + if m.nodes[m.confirm.Target] == nil { + m.confirm.Dismiss() } - if m.nodes[m.rename.id] == nil { - m.rename = renameField{} + if m.nodes[m.rename.ID] == nil { + m.rename = chrome.RenameField{} } for _, event := range m.bufferedActivity { m.apply(event) @@ -345,7 +359,7 @@ func (m AgentsViewModel) update(msg tea.Msg) (AgentsViewModel, tea.Cmd) { if item.Type == "tool" { prefix = "▸ " } - seeded.push(tailLine{kind: tailMeta, text: prefix + firstLine(item.Preview)}) + seeded.push(tailLine{kind: tailMeta, text: prefix + chrome.FirstLine(item.Preview)}) default: for line := range strings.SplitSeq(item.Preview, "\n") { seeded.push(tailLine{kind: tailText, text: line}) @@ -450,7 +464,7 @@ func (m AgentsViewModel) update(msg tea.Msg) (AgentsViewModel, tea.Cmd) { return m, nil } return m, m.resolveAgentOperation(pending) - case agentsSentMsg: + case OperationResultMsg: if msg.Gen != m.viewGen { if msg.Handle == nil { return m, nil @@ -475,7 +489,7 @@ func (m AgentsViewModel) update(msg tea.Msg) (AgentsViewModel, tea.Cmd) { return m, nil } m.pendingOperations[msg.Handle.ID()] = pending - m.say(operationError(msg.Err, "Could not "+msg.Action+": ", "The outcome for "+msg.Handle.ID()+" remains unresolved.")) + m.say(chrome.OperationError(msg.Err, "Could not "+msg.Action+": ", "The outcome for "+msg.Handle.ID()+" remains unresolved.")) if pending.Expired { return m, nil } @@ -487,7 +501,7 @@ func (m AgentsViewModel) update(msg tea.Msg) (AgentsViewModel, tea.Cmd) { if msg.Handle != nil { delete(m.pendingOperations, msg.Handle.ID()) } - m.say(operationError(msg.Err, "Could not "+msg.Action+": ", "The request may have been accepted; refresh before trying again.")) + m.say(chrome.OperationError(msg.Err, "Could not "+msg.Action+": ", "The request may have been accepted; refresh before trying again.")) } else { if msg.Handle != nil { delete(m.pendingOperations, msg.Handle.ID()) @@ -498,10 +512,10 @@ func (m AgentsViewModel) update(msg tea.Msg) (AgentsViewModel, tea.Cmd) { } return m, nil - case sessionRenamedMsg: + case chrome.SessionRenamedMsg: switch { case msg.Err != nil: - m.say(operationError(msg.Err, "Could not rename the session. Try again: ", "Session may have been renamed; refresh before trying again.")) + m.say(chrome.OperationError(msg.Err, "Could not rename the session. Try again: ", "Session may have been renamed; refresh before trying again.")) case msg.Name == "": m.say("name cleared") default: @@ -517,7 +531,7 @@ func (m AgentsViewModel) update(msg tea.Msg) (AgentsViewModel, tea.Cmd) { return m, cmd } -func (m *AgentsViewModel) label(id, fallback string) string { +func (m *Model) label(id, fallback string) string { if id == agentsYou { return agentsYou } @@ -526,7 +540,3 @@ func (m *AgentsViewModel) label(id, fallback string) string { } return cmp.Or(fallback, shortID(id)) } - -// ─── layout ─── - -// ─── drawing ─── diff --git a/cli/internal/tui/agents_weight_test.go b/cli/internal/tui/agents/weight_test.go similarity index 98% rename from cli/internal/tui/agents_weight_test.go rename to cli/internal/tui/agents/weight_test.go index bda5d2d9d..305b5b0d2 100644 --- a/cli/internal/tui/agents_weight_test.go +++ b/cli/internal/tui/agents/weight_test.go @@ -1,10 +1,11 @@ -package tui +package agents import ( "strings" "testing" "albedo/cli/internal/daemon" + "github.com/charmbracelet/x/ansi" ) diff --git a/cli/internal/tui/agents_canvas.go b/cli/internal/tui/agents_canvas.go deleted file mode 100644 index c7d1ea5b0..000000000 --- a/cli/internal/tui/agents_canvas.go +++ /dev/null @@ -1,106 +0,0 @@ -package tui - -import ( - "strings" - - "github.com/rivo/uniseg" - - "github.com/charmbracelet/x/ansi" -) - -type agentCell struct { - hue *rgb - text string - width int - continuation bool -} - -type agentCanvas struct { - cells [][]agentCell - w, h int -} - -func newCanvas(w, h int) *agentCanvas { - c := &agentCanvas{w: w, h: h, cells: make([][]agentCell, h)} - for y := range c.cells { - c.cells[y] = make([]agentCell, w) - for x := range c.cells[y] { - c.cells[y][x] = agentCell{text: " ", width: 1} - } - } - return c -} - -// clearAt removes a whole grapheme when another graph element overwrites it. -func (c *agentCanvas) clearAt(x, y int) { - start := x - for start > 0 && c.cells[y][start].continuation { - start-- - } - width := max(1, c.cells[y][start].width) - for column := start; column < min(c.w, start+width); column++ { - c.cells[y][column] = agentCell{text: " ", width: 1} - } -} - -func (c *agentCanvas) put(x, y int, text string, hue rgb) { - if y < 0 || y >= c.h { - return - } - graphemes := uniseg.NewGraphemes(text) - for graphemes.Next() { - cluster := graphemes.Str() - width := ansi.StringWidth(cluster) - if width == 0 { - continue - } - if x >= 0 && x+width <= c.w { - for column := x; column < x+width; column++ { - c.clearAt(column, y) - } - c.cells[y][x] = agentCell{text: cluster, width: width, hue: &hue} - for column := x + 1; column < x+width; column++ { - c.cells[y][column] = agentCell{continuation: true} - } - } - x += width - } -} - -var sgrCache = map[string]string{} - -// sgrCached memoizes the escape sequence for one hex color. -func sgrCached(hex string) string { - seq, ok := sgrCache[hex] - if !ok { - seq = sgr(hex, "") - sgrCache[hex] = seq - } - return seq -} - -func (c *agentCanvas) line(y int) string { - var b strings.Builder - current := "" - for _, cell := range c.cells[y] { - if cell.continuation { - continue - } - seq := "" - if cell.hue != nil && cell.text != " " { - seq = sgrCached(cell.hue.hex()) - } - if seq != current { - if current != "" { - b.WriteString(ansiReset) - } - b.WriteString(seq) - current = seq - } - b.WriteString(cell.text) - } - if current != "" { - b.WriteString(ansiReset) - } - return b.String() -} diff --git a/cli/internal/tui/agents_render.go b/cli/internal/tui/agents_render.go deleted file mode 100644 index ff72977f2..000000000 --- a/cli/internal/tui/agents_render.go +++ /dev/null @@ -1,311 +0,0 @@ -package tui - -import ( - "albedo/cli/internal/daemon" - "fmt" - "maps" - "slices" - "strings" - - "github.com/charmbracelet/x/ansi" -) - -func (m AgentsViewModel) paneHeader() []string { - // One column goes to the space after the divider. - width := m.paneWidth() - 1 - if width <= 0 { - width = max(1, m.Width-2) - } - rows := make([]string, 0, 12) - if f := m.folds[m.selected]; f != nil { - return m.foldPane(f, width) - } - n := m.nodes[m.selected] - if n == nil || width <= 0 { - return rows - } - colors := agentColors() - styled := func(hue rgb, s string) string { return sgr(hue.hex(), "") + s + ansiReset } - state := "idle" - switch { - case n.id == agentsYou: - state = "that's you" - case n.closed: - state = "closed" - case n.session.Status.Phase != nil: - switch *n.session.Status.Phase { - case daemon.PhasePreparing: - state = "preparing" - case daemon.PhaseInterrupted: - state = "interrupting" - case daemon.PhaseIdle, daemon.PhaseResting: - state = "idle" - default: - state = "running" - } - case n.running: - state = "running" - case n.peer: - state = "outside this tree" - } - rows = append(rows, styled(n.hue, "● ")+DefaultStyles.Bold.Render(n.name)+" "+DefaultStyles.Faint.Render(state)) - var meta []string - if n.model != "" { - meta = append(meta, n.model) - } - if n.id != agentsYou { - meta = append(meta, fmt.Sprintf("depth %d", n.depth)) - } - if parent := m.nodes[n.parent]; parent != nil { - meta = append(meta, "parent "+parent.name) - } - rows = append(rows, DefaultStyles.Faint.Render(ansi.Truncate(strings.Join(meta, " · "), width, "…"))) - if usage := providerCall(n.usage); usage != "" { - rows = append(rows, DefaultStyles.Faint.Render(ansi.Truncate(usage, width, "…"))) - } - rows = append(rows, "") - for _, field := range []struct{ label, text string }{{"request", n.currentRequest}, {"latest", n.latestProgress}} { - if field.text == "" { - continue - } - rows = append(rows, DefaultStyles.Muted.Render(field.label)) - wrapped := strings.Split(ansi.Wrap(field.text, max(1, width), " "), "\n") - if len(wrapped) > 3 { - wrapped = wrapped[:3] - wrapped[2] = ansi.Truncate(wrapped[2], max(1, width-1), "") + "…" - } - rows = append(rows, wrapped...) - } - if len(n.mail) > 0 { - rows = append(rows, DefaultStyles.Muted.Render("mail")) - for _, mail := range n.mail[max(0, len(n.mail)-5):] { - var arrow string - if mail.incoming { - arrow = styled(colors.mail, "← ") - } else { - arrow = DefaultStyles.Faint.Render("→ ") - } - rows = append(rows, ansi.Truncate(arrow+mail.who+" "+DefaultStyles.Faint.Render(mail.kind), width, "…")) - } - rows = append(rows, "") - } - live := DefaultStyles.Muted.Render("tail") - if n.running { - live += " " + styled(n.hue, "●") + DefaultStyles.Faint.Render(" live") - } - if n.tail.omitted || n.preview.omitted { - live += DefaultStyles.Faint.Render(" · earlier output omitted") - } - return append(rows, live) -} - -// providerCall words what the provider reported for an agent's latest call, or -// is empty when no call was reported. -func providerCall(usage *daemon.Usage) string { - if usage == nil { - return "" - } - var parts []string - if usage.PromptTokens != nil { - parts = append(parts, compactCount(*usage.PromptTokens)+" in") - } - if usage.CompletionTokens != nil { - parts = append(parts, compactCount(*usage.CompletionTokens)+" out") - } - return "last call " + strings.Join(parts, " · ") + " tok" -} - -// foldPane lists a fold's closed agents, newest turn first, ending in a -// blank row where an agent's pane has its tail heading. -func (m AgentsViewModel) foldPane(f *agentFold, width int) []string { - glyph, verb := "▸ ", "enter or → shows them" - if f.open { - glyph, verb = "▾ ", "enter or ← folds them" - } - rows := []string{ - DefaultStyles.Faint.Render(glyph) + DefaultStyles.Bold.Render(fmt.Sprintf("%d closed agents", len(f.members))), - DefaultStyles.Faint.Render(ansi.Truncate("under "+m.label(f.parent, "")+" · "+verb, width, "…")), - "", - } - for _, id := range f.members { - n := m.nodes[id] - rows = append(rows, ansi.Truncate(DefaultStyles.Faint.Render("✓ ")+n.name+DefaultStyles.Faint.Render(" "+n.model), width, "…")) - } - return append(rows, "") -} - -func (m AgentsViewModel) pane(height int) []string { - rows := m.paneHeader() - if m.folds[m.selected] != nil { - return rows - } - room := max(0, height-len(rows)) - if room == 0 || len(rows) == 0 { - return rows - } - wrapped := m.tailCache.rows - if len(wrapped) == 0 { - return append(rows, DefaultStyles.Faint.Render("nothing yet")) - } - return append(rows, wrapped[max(0, len(wrapped)-room):]...) -} - -// drawTail wraps one tail line to width and styles it by kind. -func drawTail(line tailLine, width, limit int) []string { - gutter, inner := "", width - format := func(s ...string) string { return strings.Join(s, "") } - switch line.kind { - case tailThinking: - format = func(s ...string) string { return DefaultStyles.Faint.Render(ansiItalic + s[0]) } - case tailCode: - gutter, inner, format = DefaultStyles.Decor.Render("│ "), width-2, DefaultStyles.Muted.Render - case tailOutput: - gutter, inner, format = DefaultStyles.Decor.Render("⎿ "), width-2, DefaultStyles.Faint.Render - case tailMeta: - format = DefaultStyles.Faint.Render - } - wrapped := ansi.Hardwrap(line.text, max(8, inner), true) - start := len(wrapped) - for range limit { - index := strings.LastIndexByte(wrapped[:start], '\n') - if index < 0 { - start = 0 - break - } - start = index - } - if start > 0 { - start++ - } - var out []string - for part := range strings.SplitSeq(wrapped[start:], "\n") { - // A cached row must not retain the rest of a long wrapped line. - out = append(out, gutter+format(strings.Clone(part))) - } - return out -} - -// graphOffset scrolls a tall swarm so the selected dot and its children's -// dots stay in view, the selected one first when both do not fit. -func (m AgentsViewModel) graphOffset(height int) int { - _, y, ok := m.at(m.selected) - if !ok { - return 0 - } - bottom := y + 3 - for _, child := range m.nodes { - if child.parent == m.selected { - bottom = max(bottom, child.y+2) - } - } - return max(0, min(bottom-height, y-1)) -} - -func (m AgentsViewModel) View() string { - if m.Width <= 0 || m.Height <= 0 { - return "" - } - live, written := 0, 0 - for id, n := range m.nodes { - if id == agentsYou { - continue - } - if n.running { - live++ - } - written += n.outputBytes - } - right := DefaultStyles.Faint.Render(fmt.Sprintf("%d agents · %d running · ▴%s out", len(m.nodes)-1, live, compactBytes(written))) - out := []string{" " + titleRule(m.Width-1, brand("albedo")+" "+DefaultStyles.Muted.Render("/agents"), right)} - - var confirmRows []string - if m.confirm.asking() { - confirmRows = strings.Split(m.confirm.footer(max(1, m.Width), ""), "\n") - } - bodyH := max(1, m.Height-3-max(1, len(confirmRows))) - dagW := m.dagWidth() - pw := m.paneWidth() - var stacked []string - if pw == 0 { - // Under the graph no tail follows, so the header ends at its facts. - stacked = m.paneHeader() - stacked = stacked[:max(0, len(stacked)-1)] - for len(stacked) > 0 && stacked[len(stacked)-1] == "" { - stacked = stacked[:len(stacked)-1] - } - stacked = stacked[:min(len(stacked), max(0, bodyH/2-1))] - if len(stacked) > 0 { - bodyH = max(1, bodyH-len(stacked)-1) - } - } - offset := m.graphOffset(bodyH) - canvas := newCanvas(dagW, bodyH+offset) - m.drawEdges(canvas) - m.drawNodes(canvas) - pane := m.pane(bodyH) - divider := DefaultStyles.Decor.Render("│") - for y := range bodyH { - row := canvas.line(y + offset) - if pw > 0 { - side := "" - if y < len(pane) { - side = pane[y] - } - row += divider + " " + ansi.Truncate(side, pw-1, "…") - } - out = append(out, " "+row) - } - - if len(stacked) > 0 { - out = append(out, " "+DefaultStyles.Decor.Render(strings.Repeat("─", max(0, m.Width-2)))) - for _, row := range stacked { - out = append(out, " "+ansi.Truncate(row, max(1, m.Width-1), "…")) - } - } - - status := "" - switch { - case m.rename.active(): - status = DefaultStyles.Muted.Render("rename ") + DefaultStyles.Bold.Render(m.label(m.rename.id, "")) - if n := m.nodes[m.rename.id]; n != nil && n.address != "" { - status += DefaultStyles.Faint.Render(" · its family can still mail it at ") + DefaultStyles.Muted.Render(n.address) - } - case m.err != nil: - status = DefaultStyles.Error.Render(m.err.Error() + " · ctrl+l retries") - case len(m.pendingOperations) > 0: - ids := slices.Sorted(maps.Keys(m.pendingOperations)) - status = DefaultStyles.Error.Render("Unresolved request: " + strings.Join(ids, ", ")) - case m.noticeT > 0: - status = DefaultStyles.Muted.Render(m.notice) - } - if len(confirmRows) > 0 { - out = append(out, confirmRows...) - } else { - out = append(out, " "+status) - } - target := m.label(m.selected, "agent") - input := m.input.View() - switch { - case m.input.Value() != "": - case m.folds[m.selected] != nil: - input = DefaultStyles.Faint.Render("closed agents, folded · pick one to message it") - default: - input = DefaultStyles.Faint.Render("message " + target + "… or /spawn ") - } - hints := []hint{{"tab", "next agent"}, {"enter", "open or send"}, {"ctrl+r", "rename"}, {"ctrl+x", "delete"}, {"ctrl+f", "find"}, {"esc", "back"}} - if f := m.folds[m.selected]; f != nil { - hints = []hint{{"tab", "next agent"}, {"enter", "show"}, {"ctrl+f", "find"}, {"esc", "back"}} - if f.open { - hints[1].does = "fold" - } - } - switch n := m.nodes[m.rename.id]; { - case m.find.active(): - out = append(out, " "+m.findLine(), footerLine(m.Width, []hint{{"↑↓", "next match"}, {"enter", "go there"}, {"esc", "back"}}, "", false)) - case n != nil && m.rename.active(): - out = append(out, " "+DefaultStyles.Prompt.Render("✎ ")+m.rename.view(m.Width-promptMarkWidth-1), " "+renameHints("restores "+renameBlank(n))) - default: - out = append(out, " "+promptLead()+input, footerLine(m.Width, hints, "", false)) - } - return strings.Join(out, "\n") -} diff --git a/cli/internal/tui/app.go b/cli/internal/tui/app.go index 5beb24677..d47b132e5 100644 --- a/cli/internal/tui/app.go +++ b/cli/internal/tui/app.go @@ -5,92 +5,109 @@ import ( "albedo/cli/internal/attach" "albedo/cli/internal/config" "albedo/cli/internal/daemon" + "albedo/cli/internal/terminalclient" "context" "errors" "maps" "slices" + "albedo/cli/internal/tui/agents" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) -type AppState int +type AppState = terminalclient.Route const ( - AppStateChat AppState = iota - AppStateSessionPicker - AppStateModelPicker - AppStateExtensionPicker - AppStateTreePicker - AppStateContextInspector - AppStatePageView - AppStateLogin - AppStateCapabilityPage - AppStateWebhooksPage - AppStateDiscordPage - AppStateConfigPage - AppStateAgents - AppStateFolderPicker - AppStateQuota - AppStateUsage + AppStateChat = terminalclient.Chat + AppStateSessionPicker = terminalclient.Sessions + AppStateModelPicker = terminalclient.Models + AppStateExtensionPicker = terminalclient.Extensions + AppStateTreePicker = terminalclient.Tree + AppStateContextInspector = terminalclient.Context + AppStatePageView = terminalclient.Page + AppStateLogin = terminalclient.Accounts + AppStateCapabilityPage = terminalclient.Capabilities + AppStateWebhooksPage = terminalclient.Webhooks + AppStateDiscordPage = terminalclient.Discord + AppStateConfigPage = terminalclient.Config + AppStateAgents = terminalclient.Agents + AppStateFolderPicker = terminalclient.Folders + AppStateQuota = terminalclient.Quota + AppStateUsage = terminalclient.Usage ) type pendingSessionIntents struct { - users []PendingUserTurn continuations map[string]pendingOperation + users []PendingUserTurn } -type AppModel struct { +type Workspace struct { + UI daemon.UIPreferences + Client *terminalclient.Client + Conn *daemon.Connection + ActiveSession *daemon.Session + SettingsETags map[string]string pendingBySession map[string]pendingSessionIntents - // afterReset is a note for the chat to show once its stream's first reset has - // hydrated it, which clears any notice added sooner. - afterReset string pendingCreations map[string]pendingOperation - ActiveSession *daemon.Session - titleMode titleMode + Tick TickFunc openBrowser func(url string) - Conn *daemon.Connection - Profiles config.Profiles - SettingsETags map[string]string - UI daemon.UIPreferences - Workspace string - Sessions []daemon.Session - Notices Notices - CommandCatalog []daemon.SessionCommand + // cd is the /cd question while it is open or its move goes on. + cd *cdQuestion + // attachedTo is a moved session's new daemon while its view is open; it + // takes every message until it quits. + attachedTo *attachedApp + // openAttachment reaches a daemon on another host; nil uses ssh. + openAttachment func(ctx context.Context, host, home string) (*attach.Attachment, error) + Profiles config.Profiles + Workspace string + // afterReset is a note for the chat to show once its stream's first reset has + // hydrated it, which clears any notice added sooner. + afterReset string + Sessions []daemon.Session + Notices Notices + CommandCatalog []daemon.SessionCommand // signIns are the daemon's sign-ins, read once for their terms warnings. signIns []daemon.SignIn - ExtensionPicker ExtensionPickerModel + Usage UsageModel + Quota QuotaModel + ContextInspector ContextInspectorModel + ConfigPage ConfigPageModel CapabilityPage CapabilityPageModel WebhooksPage WebhooksPageModel - DiscordPage DiscordPageModel - ConfigPage ConfigPageModel + ExtensionPicker ExtensionPickerModel TreePicker TreePickerModel - SessionPicker SessionViewer - PageView PageViewModel - ContextInspector ContextInspectorModel - Login LoginModel + DiscordPage DiscordPageModel ModelPicker ModelPickerModel FolderPicker FolderPicker - Agents AgentsViewModel - Quota QuotaModel - Usage UsageModel - - Chat ChatModel - SettingsGen int - State AppState - Width int - Height int - - // SessionGen invalidates earlier session-list and session-creation replies. - SessionGen int - CatalogGen int - ModelGen int - CommandGen int - ProfileGen int + PageView PageViewModel + Login LoginModel + Agents agents.Model + SessionPicker SessionViewer + Chat ChatModel + Width int + Height int + State AppState // folderReturn is the screen the folder picker goes back to. - folderReturn AppState + folderReturn AppState + titleMode titleMode + SettingsGen int + // SessionGen invalidates earlier session-list and session-creation replies. + SessionGen int + SessionFactsGen int + CatalogGen int + ModelGen int + CommandGen int + ProfileGen int UISaving bool StandaloneLogin bool + // Graphemes says the terminal measures grapheme clusters; see ChatModel. + Graphemes bool + // nested marks the model of an attached view, whose quitting returns to + // the view it is attached under. + nested bool // listingSessions says a session listing is in flight. listingSessions bool // refreshingSession says a session read is in flight, and SessionFactsGen @@ -98,25 +115,9 @@ type AppModel struct { // answer arrives. refreshingSession bool sessionRefreshPending bool - SessionFactsGen int - - // Graphemes says the terminal measures grapheme clusters; see ChatModel. - Graphemes bool - // nested marks the model of an attached view, whose quitting returns to - // the view it is attached under. - nested bool - Tick TickFunc - - // cd is the /cd question while it is open or its move goes on. - cd *cdQuestion - // attachedTo is a moved session's new daemon while its view is open; it - // takes every message until it quits. - attachedTo *attachedApp - // openAttachment reaches a daemon on another host; nil uses ssh. - openAttachment func(ctx context.Context, host, home string) (*attach.Attachment, error) } -func (m *AppModel) newChatModel(session *daemon.Session) ChatModel { +func (m *Workspace) newChatModel(session *daemon.Session) ChatModel { chat := NewChatModel(session, daemon.NewChatClient(m.Conn, session.ID)) chat.artifactConn = m.Conn chat.openBrowser = m.openBrowser @@ -135,12 +136,12 @@ func (m *AppModel) newChatModel(session *daemon.Session) ChatModel { return chat } -// NewAppModel requires an established daemon connection and panics if conn is nil. -func NewAppModel(conn *daemon.Connection, bootstrap Bootstrap, initialSession *daemon.Session, workspace string, needsLogin bool, openBrowser func(string)) *AppModel { +// NewWorkspace requires an established daemon connection and panics if conn is nil. +func NewWorkspace(conn *daemon.Connection, bootstrap Bootstrap, initialSession *daemon.Session, workspace string, needsLogin bool, openBrowser func(string)) *Workspace { if conn == nil { - panic("tui.NewAppModel requires a daemon connection") + panic("tui.NewWorkspace requires a daemon connection") } - m := &AppModel{ + m := &Workspace{ titleMode: windowTitleMode(), Conn: conn, Profiles: bootstrap.Settings.Profiles, @@ -169,23 +170,24 @@ func NewAppModel(conn *daemon.Connection, bootstrap Bootstrap, initialSession *d m.State = AppStateSessionPicker } + m.mount() return m } -// NewLoginAppModel starts the standalone login flow, which exits when finished. -func NewLoginAppModel(conn *daemon.Connection, bootstrap Bootstrap, workspace, nameHint string, openBrowser func(string)) *AppModel { - m := NewAppModel(conn, bootstrap, nil, workspace, false, openBrowser) +// NewLoginWorkspace starts the standalone login flow, which exits when finished. +func NewLoginWorkspace(conn *daemon.Connection, bootstrap Bootstrap, workspace, nameHint string, openBrowser func(string)) *Workspace { + m := NewWorkspace(conn, bootstrap, nil, workspace, false, openBrowser) m.State = AppStateLogin m.StandaloneLogin = true m.Login = NewLoginModel(conn, nameHint, openBrowser) return m } -func (m *AppModel) Init() tea.Cmd { +func (m *Workspace) Start() tea.Cmd { return tea.Batch(m.initScreen(), m.loadTermsCmd()) } -func (m *AppModel) AddNotice(message string) { +func (m *Workspace) AddNotice(message string) { if m.ActiveSession != nil && m.Chat.History != nil { m.Chat.AddNotice(message) return @@ -193,7 +195,7 @@ func (m *AppModel) AddNotice(message string) { m.Notices.AddNotice(message) } -func (m *AppModel) AddError(message string) { +func (m *Workspace) AddError(message string) { if m.ActiveSession != nil && m.Chat.History != nil { m.Chat.AddError(message) return @@ -201,74 +203,51 @@ func (m *AppModel) AddError(message string) { m.Notices.AddError(message) } -func (m *AppModel) ClearNotices() { +func (m *Workspace) ClearNotices() { m.Notices.Clear() if m.ActiveSession != nil && m.Chat.History != nil { m.Chat.ClearNotices() } } -func (m *AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { +func (m *Workspace) Receive(msg tea.Msg) (bool, tea.Cmd) { if cmd, handled := m.updateAttached(msg); handled { - return m, cmd + return true, cmd } if cmd, handled := m.handleCD(msg); handled { - return m, cmd + return true, cmd } if cmd, handled := m.handleCommandInvocation(msg); handled { - return m, cmd + return true, cmd } if handled, cmd := m.handleLoginOutcome(msg); handled { - return m, cmd + return true, cmd } if cmd, handled := m.handleChatLifecycle(msg); handled { - return m, cmd + return true, cmd } if cmd, handled := m.handlePreferences(msg); handled { - return m, cmd + return true, cmd } if cmd, handled := m.handleTerms(msg); handled { - return m, cmd + return true, cmd } if cmd, handled := m.handleSessionResults(msg); handled { - return m, cmd + return true, cmd } if cmd, handled := m.handleCommandResults(msg); handled { - return m, cmd + return true, cmd } switch msg := msg.(type) { - case tea.WindowSizeMsg: - m.Width = msg.Width - m.Height = msg.Height - if m.ActiveSession != nil && m.Chat.History != nil { - m.Chat.SetSize(msg.Width, msg.Height) - } - m.SessionPicker.SetSize(msg.Width, msg.Height) - m.ModelPicker.SetSize(msg.Width, msg.Height) - m.ExtensionPicker.SetSize(msg.Width, msg.Height) - m.TreePicker.SetSize(msg.Width, msg.Height) - m.ContextInspector.SetSize(msg.Width, msg.Height) - m.PageView.SetSize(msg.Width, msg.Height) - m.CapabilityPage.SetSize(msg.Width, msg.Height) - m.WebhooksPage.SetSize(msg.Width, msg.Height) - m.DiscordPage.SetSize(msg.Width, msg.Height) - m.ConfigPage.SetSize(msg.Width, msg.Height) - m.Agents.SetSize(msg.Width, msg.Height) - m.FolderPicker.SetSize(msg.Width, msg.Height) - m.Login.SetSize(msg.Width, msg.Height) - m.Quota.SetSize(msg.Width, msg.Height) - m.Usage.SetSize(msg.Width, msg.Height) - return m, nil - case tea.FocusMsg: // the chat is the one screen that wakes up for input - return m, m.Chat.focus(true) + return true, m.Chat.focus(true) case tea.BlurMsg: - return m, m.Chat.focus(false) + return true, m.Chat.focus(false) case tea.ModeReportMsg: // the reply Bubble Tea switches to grapheme widths on @@ -279,53 +258,53 @@ func (m *AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.Chat.graphemes = true } } - return m, nil + return true, nil case SessionDeleteMsg: if m.State != AppStateSessionPicker || !m.SessionPicker.ArchiveView || m.ActiveSession != nil && m.ActiveSession.ID == msg.ID { - return m, nil + return true, nil } - return m, m.deleteSessionCmd(msg.ID, msg.Condition) + return true, m.deleteSessionCmd(msg.ID, msg.Condition) case commandCatalogLoadedMsg: if msg.Gen != m.CatalogGen { - return m, nil + return true, nil } if msg.Err != nil { if _, ok := errors.AsType[*daemon.UpgradeRequiredError](msg.Err); ok { m.AddError("Could not load commands: " + msg.Err.Error()) } - return m, nil + return true, nil } m.CommandCatalog = msg.Commands m.Chat.CommandMenu.Catalog = msg.Commands if m.ActiveSession != nil { m.Chat.syncLayout() } - return m, nil + return true, nil case ChatQuitMsg: m.Chat.Close() - return m, m.quit() + return true, m.quit() case ChatBackToSessionsMsg: - return m, m.openSessions() + return true, m.openSessions() case ChatNewSessionMsg: - return m, m.newSessionCmd() + return true, m.newSessionCmd() case ChatOpenModelPickerMsg: - return m, m.openModelPicker() + return true, m.openModelPicker() case ModelPickerSelectMsg: m.ModelPicker.Close() m.ModelPicker.Saving = true m.ModelPicker.Error = "" m.ModelGen++ - return m, m.changeModelAccessCmd(msg.Model, msg.Provider, msg.Effort, new(msg.CyberAccess), msg.MakeDefault, m.ModelGen) + return true, m.changeModelAccessCmd(msg.Model, msg.Provider, msg.Effort, new(msg.CyberAccess), msg.MakeDefault, m.ModelGen) case ModelPickerCapsMsg: - return m, m.saveCapsCmd(msg) + return true, m.saveCapsCmd(msg) case modelCapsSavedMsg: if msg.Err == nil { @@ -336,127 +315,122 @@ func (m *AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } var cmd tea.Cmd m.ModelPicker, cmd = m.ModelPicker.Update(msg) - return m, cmd + return true, cmd case ChatOpenExtensionPickerMsg: - return m, m.openExtensionPicker() + return true, m.openExtensionPicker() case ChatOpenWebhooksPageMsg: if m.ActiveSession != nil { m.WebhooksPage = NewWebhooksPageModel(m.Conn, m.ActiveSession.ID) - return m, m.openScreen(AppStateWebhooksPage, &m.WebhooksPage) + return true, m.openScreen(AppStateWebhooksPage, &m.WebhooksPage) } case ChatOpenDiscordPageMsg: if m.ActiveSession != nil { m.DiscordPage = NewDiscordPageModel(m.Conn, m.ActiveSession.ID) - return m, m.openScreen(AppStateDiscordPage, &m.DiscordPage) + return true, m.openScreen(AppStateDiscordPage, &m.DiscordPage) } case ChatOpenConfigPageMsg: - return m, m.openConfigPage() + return true, m.openConfigPage() case ChatOpenAgentsMsg: if m.ActiveSession != nil { - m.Agents.Close() - pending := m.Agents.pendingOperations - draft := m.Agents.input.Value() - m.Agents = NewAgentsViewModel(m.Conn, m.ActiveSession.ID) - m.Agents.pendingOperations = pending - m.Agents.input.SetValue(draft) - return m, m.openScreen(AppStateAgents, &m.Agents) + m.Agents.Reopen(m.Conn, m.ActiveSession.ID) + return true, m.openScreen(AppStateAgents, &m.Agents) } - case agentsSentMsg: + case agents.OperationResultMsg: if m.State != AppStateAgents && msg.Handle != nil { var cmd tea.Cmd m.Agents, cmd = m.Agents.Update(msg) - return m, cmd + return true, cmd } case ChatOpenFolderPickerMsg: - return m, m.openFolderPicker(msg.Retry) + return true, m.openFolderPicker(msg.Retry) case FolderMovedMsg: - return m, m.moved(msg) + return true, m.moved(msg) case FolderPickerCancelMsg: m.FolderPicker.Close() m.State = m.folderReturn - return m, nil + return true, nil case SessionFoldersMsg: - return m, m.openFolderBrowser(msg.Query) + return true, m.openFolderBrowser(msg.Query) case FolderOpenSessionMsg: m.FolderPicker.Close() - return m, m.openSession(msg.Session) + return true, m.openSession(msg.Session) case FolderNewSessionMsg: m.FolderPicker.Close() m.SessionGen++ - return m, m.createSessionCmd(m.SessionGen, msg.Workspace) + return true, m.createSessionCmd(m.SessionGen, msg.Workspace) - case AgentsDoneMsg: + case agents.DoneMsg: m.Agents.Close() m.State = AppStateChat - return m, nil + return true, nil - case AgentsAttachMsg: + case agents.AttachMsg: m.Agents.Close() session := msg.Session if i := slices.IndexFunc(m.Sessions, func(s daemon.Session) bool { return s.ID == session.ID }); i >= 0 { session = m.Sessions[i] } - return m, m.openSession(session) + return true, m.openSession(session) case ModelPickerCancelMsg: m.ModelPicker.Close() m.State = AppStateChat - return m, nil + return true, nil case WebhooksPageDoneMsg, DiscordPageDoneMsg, ExtensionPickerDoneMsg, TreeCancelMsg, ContextDoneMsg, CapabilityPageDoneMsg, PageCancelMsg, QuotaCancelMsg, UsageCancelMsg: m.State = AppStateChat - return m, nil + return true, nil case ConfigPageDoneMsg: m.State = AppStateChat - return m, m.refreshSettingsCmd() + return true, m.refreshSettingsCmd() case ExtensionPickerChangedMsg: m.CatalogGen++ - return m, m.loadCommandCatalogCmd(m.CatalogGen) + return true, m.loadCommandCatalogCmd(m.CatalogGen) case CapabilityPageChangedMsg: m.CatalogGen++ - return m, m.loadCommandCatalogCmd(m.CatalogGen) + return true, m.loadCommandCatalogCmd(m.CatalogGen) case ChatOpenTreePickerMsg: - return m, m.openTreePicker(false) + return true, m.openTreePicker(false) case ChatOpenForkPickerMsg: - return m, m.openTreePicker(true) + return true, m.openTreePicker(true) case ChatOpenQuotaMsg: - return m, m.openQuota() + return true, m.openQuota() case ChatOpenUsageMsg: - return m, m.openUsage() + return true, m.openUsage() case TreeRewindSuccessMsg: if m.State != AppStateTreePicker || msg.Generation != m.TreePicker.Generation || m.ActiveSession == nil { - return m, nil + return true, nil } conn, id, outcome, gen := m.Conn, m.ActiveSession.ID, msg.Outcome, msg.Generation - return m, func() tea.Msg { + return true, func() tea.Msg { s, err := daemon.GetSession(context.Background(), conn, id) return TreeRewindReloadMsg{Session: s, Outcome: outcome, Generation: gen, Err: err} } case TreeRewindReloadMsg: if msg.Err != nil { - m.AddError(operationError(msg.Err, "Could not reload rewound session: ", "Reconnect to refresh this session.")) + m.AddError(chrome.OperationError(msg.Err, "Could not reload rewound session: ", "Reconnect to refresh this session.")) m.State = AppStateChat - return m, nil + return true, nil } note := "Rewound. The earlier conversation is archived as " + msg.Outcome.ArchiveSessionID[:min(8, len(msg.Outcome.ArchiveSessionID))] + "." if msg.Outcome.Summary != "" { @@ -472,42 +446,42 @@ func (m *AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case msg.Outcome.HasInput: m.Chat.TextArea.SetValue(msg.Outcome.Input) } - return m, cmd + return true, cmd case TreeForkSuccessMsg: if m.State != AppStateTreePicker || msg.Generation != m.TreePicker.Generation { - return m, nil + return true, nil } - return m, m.setChatSession(msg.Session, true) + return true, m.setChatSession(msg.Session, true) case ChatSideQuestionOpenMsg: if m.ActiveSession == nil || msg.SessionID != m.ActiveSession.ID || msg.Generation != m.Chat.Generation { - return m, nil + return true, nil } - return m, m.openSession(msg.Session) + return true, m.openSession(msg.Session) case ChatOpenContextInspectorMsg: - return m, m.openContextInspector() + return true, m.openContextInspector() case ChatOpenCapabilityPageMsg: if m.ActiveSession != nil { m.CapabilityPage = NewCapabilityPageModel(m.Conn, m.ActiveSession.ID, msg.Kind) m.CapabilityPage.openBrowser = m.openBrowser - return m, m.openScreen(AppStateCapabilityPage, &m.CapabilityPage) + return true, m.openScreen(AppStateCapabilityPage, &m.CapabilityPage) } case ChatOpenPageMsg: if m.ActiveSession != nil { m.PageView = NewPageViewModel(m.Conn, m.ActiveSession.ID, msg.Command) - return m, m.openScreen(AppStatePageView, &m.PageView) + return true, m.openScreen(AppStatePageView, &m.PageView) } case PageViewChangedMsg: m.Chat.statusRevision++ - return m, m.Chat.statusCmd() + return true, m.Chat.statusCmd() case ChatOpenLoginMsg: - return m, m.openLogin(msg.Name) + return true, m.openLogin(msg.Name) case LoginCancelMsg: cleanup := m.Login.Close() @@ -515,37 +489,37 @@ func (m *AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // /login may have removed providers even when it ends without a choice. if m.StandaloneLogin { - return m, tea.Batch(cleanup, tea.Quit) + return true, tea.Batch(cleanup, tea.Quit) } if m.ActiveSession != nil { - return m, tea.Batch(cleanup, m.returnToChat(), m.loadProfilesCmd("", m.ProfileGen)) + return true, tea.Batch(cleanup, m.returnToChat(), m.loadProfilesCmd("", m.ProfileGen)) } m.State = AppStateSessionPicker m.updateSessionPickerItems() m.SessionGen++ - return m, tea.Batch(cleanup, m.SessionPicker.Init(), m.loadSessionsCmd(m.SessionGen)) + return true, tea.Batch(cleanup, m.SessionPicker.Init(), m.loadSessionsCmd(m.SessionGen)) case LoginDoneMsg: if m.State != AppStateLogin || msg.Gen != m.Login.Generation { - return m, nil + return true, nil } cleanup := m.Login.Close() if len(m.Login.SignIns) > 0 { m.signIns = m.Login.SignIns } m.ProfileGen++ - return m, tea.Batch(cleanup, m.loadProfilesCmd(msg.Name, m.ProfileGen)) + return true, tea.Batch(cleanup, m.loadProfilesCmd(msg.Name, m.ProfileGen)) case PickerSelectMsg: if m.State == AppStateSessionPicker { switch msg.ID { case "new": - return m, m.newSessionCmd() + return true, m.newSessionCmd() case "archive": m.SessionPicker.OpenArchive() - return m, nil + return true, nil case "login": - return m, m.openLogin("") + return true, m.openLogin("") default: // The active session may not yet appear in the daemon's recent list. listed := m.Sessions @@ -553,7 +527,7 @@ func (m *AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { listed = append([]daemon.Session{*m.ActiveSession}, listed...) } if i := slices.IndexFunc(listed, func(s daemon.Session) bool { return s.ID == msg.ID }); i >= 0 { - return m, m.openSession(listed[i]) + return true, m.openSession(listed[i]) } } } @@ -562,73 +536,77 @@ func (m *AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if m.State == AppStateSessionPicker { if m.SessionPicker.ArchiveView { m.SessionPicker.CloseArchive() - return m, nil + return true, nil } if m.ActiveSession != nil { m.State = AppStateChat - return m, nil + return true, nil } - return m, m.quit() + return true, m.quit() } } - // Route to active state model + return false, nil +} + +func (m *Workspace) chatInput(msg tea.Msg) tea.Cmd { var cmd tea.Cmd - switch m.State { - case AppStateChat: - beforePending := len(m.Chat.pendingUsers) - before := m.Chat.Flags - m.Chat, cmd = m.Chat.Update(msg) - if len(m.Chat.pendingUsers) > beforePending { - m.ClearNotices() - } - if m.Chat.Flags.Thinking != before.Thinking || m.Chat.Flags.Tools != before.Tools { - draft := m.Chat.Flags - m.Chat.Flags = before - if !m.UISaving { - m.UISaving = true - m.SettingsGen++ - patch := daemon.UIPreferencesPatch{} - if draft.Thinking != before.Thinking { - patch.Thinking = &draft.Thinking - } - if draft.Tools != before.Tools { - patch.Tools = &draft.Tools - } - cmd = tea.Batch(cmd, m.patchUICmd("", patch, m.SettingsGen)) + beforePending := len(m.Chat.pendingUsers) + before := m.Chat.Flags + m.Chat, cmd = m.Chat.Update(msg) + if len(m.Chat.pendingUsers) > beforePending { + m.ClearNotices() + } + if m.Chat.Flags.Thinking != before.Thinking || m.Chat.Flags.Tools != before.Tools { + draft := m.Chat.Flags + m.Chat.Flags = before + if !m.UISaving { + m.UISaving = true + m.SettingsGen++ + patch := daemon.UIPreferencesPatch{} + if draft.Thinking != before.Thinking { + patch.Thinking = &draft.Thinking } + if draft.Tools != before.Tools { + patch.Tools = &draft.Tools + } + cmd = tea.Batch(cmd, m.patchUICmd("", patch, m.SettingsGen)) } - case AppStateSessionPicker: - m.SessionPicker, cmd = m.SessionPicker.Update(msg) - case AppStateModelPicker: - m.ModelPicker, cmd = m.ModelPicker.Update(msg) - case AppStateExtensionPicker: - m.ExtensionPicker, cmd = m.ExtensionPicker.Update(msg) - case AppStateTreePicker: - m.TreePicker, cmd = m.TreePicker.Update(msg) - case AppStateContextInspector: - m.ContextInspector, cmd = m.ContextInspector.Update(msg) - case AppStatePageView: - m.PageView, cmd = m.PageView.Update(msg) - case AppStateCapabilityPage: - m.CapabilityPage, cmd = m.CapabilityPage.Update(msg) - case AppStateWebhooksPage: - m.WebhooksPage, cmd = m.WebhooksPage.Update(msg) - case AppStateDiscordPage: - m.DiscordPage, cmd = m.DiscordPage.Update(msg) - case AppStateConfigPage: - m.ConfigPage, cmd = m.ConfigPage.Update(msg) - case AppStateAgents: - m.Agents, cmd = m.Agents.Update(msg) - case AppStateFolderPicker: - m.FolderPicker, cmd = m.FolderPicker.Update(msg) - case AppStateLogin: - m.Login, cmd = m.Login.Update(msg) - case AppStateQuota: - m.Quota, cmd = m.Quota.Update(msg) - case AppStateUsage: - m.Usage, cmd = m.Usage.Update(msg) } - - return m, cmd + return cmd +} +func (m *Workspace) mount() { + chat := terminalclient.Screen{Input: m.chatInput, Draw: m.Chat.View, Resize: func(w, h int) { + if m.ActiveSession != nil && m.Chat.History != nil { + m.Chat.SetSize(w, h) + } + }} + sessions := terminalclient.BindPage(&m.SessionPicker) + sessions.Page = m.sessionsPage + m.Client = terminalclient.New(m, [terminalclient.RouteCount]terminalclient.Screen{ + terminalclient.Chat: chat, + terminalclient.Sessions: sessions, + terminalclient.Models: terminalclient.BindPage(&m.ModelPicker), + terminalclient.Extensions: terminalclient.BindPage(&m.ExtensionPicker), + terminalclient.Tree: terminalclient.BindPage(&m.TreePicker), + terminalclient.Context: terminalclient.BindPage(&m.ContextInspector), + terminalclient.Page: terminalclient.BindPage(&m.PageView), + terminalclient.Accounts: terminalclient.BindPage(&m.Login), + terminalclient.Capabilities: terminalclient.BindPage(&m.CapabilityPage), + terminalclient.Webhooks: terminalclient.BindPage(&m.WebhooksPage), + terminalclient.Discord: terminalclient.BindPage(&m.DiscordPage), + terminalclient.Config: terminalclient.BindPage(&m.ConfigPage), + terminalclient.Agents: { + Draw: func() string { return m.Agents.View() }, + Resize: m.Agents.SetSize, + Input: func(msg tea.Msg) tea.Cmd { + next, cmd := m.Agents.Update(msg) + m.Agents = next + return cmd + }, + }, + terminalclient.Folders: terminalclient.BindPage(&m.FolderPicker), + terminalclient.Quota: terminalclient.BindPage(&m.Quota), + terminalclient.Usage: terminalclient.BindPage(&m.Usage), + }, pageTheme) } diff --git a/cli/internal/tui/app_chat.go b/cli/internal/tui/app_chat.go index b52fb2a31..65dcd9619 100644 --- a/cli/internal/tui/app_chat.go +++ b/cli/internal/tui/app_chat.go @@ -2,11 +2,12 @@ package tui import ( "albedo/cli/internal/daemon" + tea "charm.land/bubbletea/v2" uv "github.com/charmbracelet/ultraviolet" ) -func (m *AppModel) handleChatLifecycle(msg tea.Msg) (tea.Cmd, bool) { +func (m *Workspace) handleChatLifecycle(msg tea.Msg) (tea.Cmd, bool) { // First: forward chat lifecycle messages even while a modal is open. var sid string var forward bool diff --git a/cli/internal/tui/app_commands.go b/cli/internal/tui/app_commands.go index 572ec70df..fb42c2796 100644 --- a/cli/internal/tui/app_commands.go +++ b/cli/internal/tui/app_commands.go @@ -10,10 +10,12 @@ import ( "slices" "strings" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" ) -func (m *AppModel) handleCommandResults(msg tea.Msg) (tea.Cmd, bool) { +func (m *Workspace) handleCommandResults(msg tea.Msg) (tea.Cmd, bool) { switch msg := msg.(type) { case modelChangedMsg: if msg.Gen != m.ModelGen || m.ActiveSession == nil || msg.SessionID != m.ActiveSession.ID { @@ -49,7 +51,7 @@ func (m *AppModel) handleCommandResults(msg tea.Msg) (tea.Cmd, bool) { m.ClearNotices() } if msg.Err != nil { - message := operationError(msg.Err, "Model settings error: ", "Model settings may have changed; check them before trying again.") + message := chrome.OperationError(msg.Err, "Model settings error: ", "Model settings may have changed; check them before trying again.") if refusedConfiguration(msg.Err) { message += " Re-read the settings; try again." } @@ -87,7 +89,7 @@ func (m *AppModel) handleCommandResults(msg tea.Msg) (tea.Cmd, bool) { return nil, true } if msg.Err != nil { - m.AddError(operationError(msg.Err, "Command error: ", msg.Name+" may have run; check its result before running it again.")) + m.AddError(chrome.OperationError(msg.Err, "Command error: ", msg.Name+" may have run; check its result before running it again.")) return m.refusedConfigurationCmd(msg.Err), true } if msg.Page != nil && m.State == AppStateChat && m.ActiveSession != nil { @@ -154,7 +156,7 @@ func (m *AppModel) handleCommandResults(msg tea.Msg) (tea.Cmd, bool) { return nil, false } -func (m *AppModel) loadProfilesCmd(provider string, gen int) tea.Cmd { +func (m *Workspace) loadProfilesCmd(provider string, gen int) tea.Cmd { conn := m.Conn return func() tea.Msg { p, err := daemon.ProviderProfiles(context.Background(), conn) @@ -162,7 +164,7 @@ func (m *AppModel) loadProfilesCmd(provider string, gen int) tea.Cmd { } } -func (m *AppModel) loadCommandCatalogCmd(gen int) tea.Cmd { +func (m *Workspace) loadCommandCatalogCmd(gen int) tea.Cmd { conn, hasSession := m.Conn, m.ActiveSession != nil var sessionID string if hasSession { @@ -180,7 +182,7 @@ func (m *AppModel) loadCommandCatalogCmd(gen int) tea.Cmd { // saveCapsCmd saves a model's cap change against the models settings as this // app last read them. -func (m *AppModel) saveCapsCmd(msg ModelPickerCapsMsg) tea.Cmd { +func (m *Workspace) saveCapsCmd(msg ModelPickerCapsMsg) tea.Cmd { conn, caps := m.Conn, msg.Caps caps.ETag = m.SettingsETags["models"] return func() tea.Msg { @@ -189,11 +191,11 @@ func (m *AppModel) saveCapsCmd(msg ModelPickerCapsMsg) tea.Cmd { } } -func (m *AppModel) changeModelCmd(model, provider, effort string, gen int) tea.Cmd { +func (m *Workspace) changeModelCmd(model, provider, effort string, gen int) tea.Cmd { return m.changeModelAccessCmd(model, provider, effort, nil, false, gen) } -func (m *AppModel) changeModelAccessCmd(model, provider, effort string, access *string, makeDefault bool, gen int) tea.Cmd { +func (m *Workspace) changeModelAccessCmd(model, provider, effort string, access *string, makeDefault bool, gen int) tea.Cmd { conn, hasSession := m.Conn, m.ActiveSession != nil var sessionID, currentProvider, etag string if hasSession { @@ -224,7 +226,7 @@ func (m *AppModel) changeModelAccessCmd(model, provider, effort string, access * } } -func (m *AppModel) executeCommandCmd(name, args string, gen int) tea.Cmd { +func (m *Workspace) executeCommandCmd(name, args string, gen int) tea.Cmd { var captured daemon.Session if m.ActiveSession != nil { captured = *m.ActiveSession @@ -378,7 +380,7 @@ func profilesForSession(profiles config.Profiles, session daemon.Session) config return profile } -func (m *AppModel) handleCommandInvocation(msg tea.Msg) (tea.Cmd, bool) { +func (m *Workspace) handleCommandInvocation(msg tea.Msg) (tea.Cmd, bool) { switch msg := msg.(type) { case ChatExecuteCommandMsg: if slices.ContainsFunc(m.CommandCatalog, func(command daemon.SessionCommand) bool { diff --git a/cli/internal/tui/app_login.go b/cli/internal/tui/app_login.go index ea5625c9b..2c3494da6 100644 --- a/cli/internal/tui/app_login.go +++ b/cli/internal/tui/app_login.go @@ -3,12 +3,14 @@ package tui import ( "fmt" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" ) // Sign-in startup can finish after its screen closes. Cleanup must still run; // credential mutation outcomes remain visible without selecting a stale flow. -func (m *AppModel) handleLoginOutcome(msg tea.Msg) (bool, tea.Cmd) { +func (m *Workspace) handleLoginOutcome(msg tea.Msg) (bool, tea.Cmd) { switch result := msg.(type) { case signInStartedMsg, signInStatusMsg, signInPollMsg: var cmd tea.Cmd @@ -19,7 +21,7 @@ func (m *AppModel) handleLoginOutcome(msg tea.Msg) (bool, tea.Cmd) { return false, nil } if result.Err != nil { - message := operationError(result.Err, "Provider update failed: ", "Provider update may have been accepted; check your accounts before trying again.") + message := chrome.OperationError(result.Err, "Provider update failed: ", "Provider update may have been accepted; check your accounts before trying again.") m.AddError(message) if m.State == AppStateLogin { m.Login.Error = message @@ -33,7 +35,7 @@ func (m *AppModel) handleLoginOutcome(msg tea.Msg) (bool, tea.Cmd) { return false, nil } if result.Err != nil { - message := operationError(result.Err, "Account update failed: ", "Account update may have been accepted; check your accounts before trying again.") + message := chrome.OperationError(result.Err, "Account update failed: ", "Account update may have been accepted; check your accounts before trying again.") m.AddError(message) if m.State == AppStateLogin { m.Login.Error = message diff --git a/cli/internal/tui/app_navigation.go b/cli/internal/tui/app_navigation.go index ce6967e6d..ebc52c25c 100644 --- a/cli/internal/tui/app_navigation.go +++ b/cli/internal/tui/app_navigation.go @@ -1,10 +1,12 @@ package tui import ( + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" ) -func (m *AppModel) initScreen() tea.Cmd { +func (m *Workspace) initScreen() tea.Cmd { switch m.State { case AppStateChat: return tea.Batch(m.Chat.Init(), m.loadCommandCatalogCmd(m.CatalogGen), m.recordOpenCmd(m.ActiveSession.ID)) @@ -16,7 +18,7 @@ func (m *AppModel) initScreen() tea.Cmd { return nil } -func (m *AppModel) returnToChat() tea.Cmd { +func (m *Workspace) returnToChat() tea.Cmd { if m.Chat.SessionID != m.ActiveSession.ID { return tea.Batch(m.setChatSession(*m.ActiveSession, false), m.recordOpenCmd(m.ActiveSession.ID)) } @@ -24,7 +26,7 @@ func (m *AppModel) returnToChat() tea.Cmd { return nil } -func (m *AppModel) openLogin(name string) tea.Cmd { +func (m *Workspace) openLogin(name string) tea.Cmd { previous := m.Login.Close() m.Login = NewLoginModel(m.Conn, name, m.openBrowser) m.Login.SetSize(m.Width, m.Height) @@ -32,7 +34,7 @@ func (m *AppModel) openLogin(name string) tea.Cmd { return tea.Batch(previous, m.Login.Init()) } -func (m *AppModel) openSessions() tea.Cmd { +func (m *Workspace) openSessions() tea.Cmd { m.State = AppStateSessionPicker m.updateSessionPickerItems() m.SessionGen++ @@ -44,13 +46,13 @@ type screen interface { Init() tea.Cmd } -func (m *AppModel) openScreen(state AppState, s screen) tea.Cmd { +func (m *Workspace) openScreen(state AppState, s screen) tea.Cmd { s.SetSize(m.Width, m.Height) m.State = state return s.Init() } -func (m *AppModel) openModelPicker() tea.Cmd { +func (m *Workspace) openModelPicker() tea.Cmd { if m.ActiveSession == nil { return nil } @@ -60,7 +62,7 @@ func (m *AppModel) openModelPicker() tea.Cmd { return m.openScreen(AppStateModelPicker, &m.ModelPicker) } -func (m *AppModel) openExtensionPicker() tea.Cmd { +func (m *Workspace) openExtensionPicker() tea.Cmd { if m.ActiveSession == nil { return nil } @@ -70,12 +72,12 @@ func (m *AppModel) openExtensionPicker() tea.Cmd { // openConfigPage opens the extension settings screen, which is not scoped to // a session. -func (m *AppModel) openConfigPage() tea.Cmd { +func (m *Workspace) openConfigPage() tea.Cmd { m.ConfigPage = NewConfigPageModel(m.Conn) return m.openScreen(AppStateConfigPage, &m.ConfigPage) } -func (m *AppModel) openTreePicker(forkOnly bool) tea.Cmd { +func (m *Workspace) openTreePicker(forkOnly bool) tea.Cmd { if m.ActiveSession == nil { return nil } @@ -86,18 +88,18 @@ func (m *AppModel) openTreePicker(forkOnly bool) tea.Cmd { return m.openScreen(AppStateTreePicker, &m.TreePicker) } -func (m *AppModel) openQuota() tea.Cmd { +func (m *Workspace) openQuota() tea.Cmd { m.Quota = NewQuotaModel(m.Conn) return m.openScreen(AppStateQuota, &m.Quota) } // openUsage opens the usage screen, which is not scoped to a session. -func (m *AppModel) openUsage() tea.Cmd { +func (m *Workspace) openUsage() tea.Cmd { m.Usage = NewUsageModel(m.Conn) return m.openScreen(AppStateUsage, &m.Usage) } -func (m *AppModel) openContextInspector() tea.Cmd { +func (m *Workspace) openContextInspector() tea.Cmd { if m.ActiveSession == nil { return nil } @@ -107,7 +109,7 @@ func (m *AppModel) openContextInspector() tea.Cmd { // openFolderPicker offers the session another folder; a retry is the turn // its missing folder refused. -func (m *AppModel) openFolderPicker(retry *WorkspaceRetry) tea.Cmd { +func (m *Workspace) openFolderPicker(retry *WorkspaceRetry) tea.Cmd { if m.ActiveSession == nil { return nil } @@ -119,7 +121,7 @@ func (m *AppModel) openFolderPicker(retry *WorkspaceRetry) tea.Cmd { } // openFolderBrowser lists sessions by folder, from the sessions view. -func (m *AppModel) openFolderBrowser(query string) tea.Cmd { +func (m *Workspace) openFolderBrowser(query string) tea.Cmd { m.FolderPicker.Close() m.FolderPicker = NewFolderBrowser(daemonFolders{conn: m.Conn}, m.Workspace, query) m.FolderPicker.Tick = m.Tick @@ -128,7 +130,7 @@ func (m *AppModel) openFolderBrowser(query string) tea.Cmd { } // moved takes the daemon's answer to moving the session on screen. -func (m *AppModel) moved(msg FolderMovedMsg) tea.Cmd { +func (m *Workspace) moved(msg FolderMovedMsg) tea.Cmd { if m.ActiveSession == nil || msg.SessionID != m.ActiveSession.ID { return nil } @@ -136,7 +138,7 @@ func (m *AppModel) moved(msg FolderMovedMsg) tea.Cmd { if m.State == AppStateFolderPicker { m.FolderPicker.Refused(msg.Err) } else { - m.AddError(operationError(msg.Err, "Could not move this session: ", "Session may have moved; check its folder before trying again.")) + m.AddError(chrome.OperationError(msg.Err, "Could not move this session: ", "Session may have moved; check its folder before trying again.")) } return m.refusedConfigurationCmd(msg.Err) } @@ -152,7 +154,7 @@ func (m *AppModel) moved(msg FolderMovedMsg) tea.Cmd { // Close releases this application's reads and subscriptions. Shared daemon // work and admitted mutations continue independently of the terminal. -func (m *AppModel) Close() tea.Cmd { +func (m *Workspace) Close() tea.Cmd { m.Chat.Close() m.Agents.Close() m.ModelPicker.Close() diff --git a/cli/internal/tui/app_preferences.go b/cli/internal/tui/app_preferences.go index 711addddb..018d10ff3 100644 --- a/cli/internal/tui/app_preferences.go +++ b/cli/internal/tui/app_preferences.go @@ -6,10 +6,12 @@ import ( "errors" "slices" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" ) -func (m *AppModel) handlePreferences(msg tea.Msg) (tea.Cmd, bool) { +func (m *Workspace) handlePreferences(msg tea.Msg) (tea.Cmd, bool) { switch msg := msg.(type) { case settingsLoadedMsg: if msg.Gen != m.SettingsGen { @@ -46,7 +48,7 @@ func (m *AppModel) handlePreferences(msg tea.Msg) (tea.Cmd, bool) { if msg.Err != nil { text := msg.Err.Error() if msg.Action != "" { - text = operationError(msg.Err, "Could not "+msg.Action+" the session: ", text) + text = chrome.OperationError(msg.Err, "Could not "+msg.Action+" the session: ", text) } m.Chat.AddError(text) m.SessionPicker.notice = text @@ -84,7 +86,7 @@ func (m *AppModel) handlePreferences(msg tea.Msg) (tea.Cmd, bool) { } // ApplyUI takes acknowledged shared preferences from the daemon. -func (m *AppModel) ApplyUI(prefs daemon.UIPreferences) { +func (m *Workspace) ApplyUI(prefs daemon.UIPreferences) { if len(prefs.SessionETags) != 0 || len(prefs.Opens) != 0 { m.SessionGen++ // Earlier listings predate these acknowledged session facts. } @@ -125,7 +127,7 @@ func applySessionPreferences(session daemon.Session, prefs daemon.UIPreferences) return session } -func (m *AppModel) refreshSettingsCmd() tea.Cmd { +func (m *Workspace) refreshSettingsCmd() tea.Cmd { if m.UISaving { return nil } @@ -133,7 +135,7 @@ func (m *AppModel) refreshSettingsCmd() tea.Cmd { return m.loadSettingsCmd(m.SettingsGen) } -func (m *AppModel) loadSettingsCmd(gen int) tea.Cmd { +func (m *Workspace) loadSettingsCmd(gen int) tea.Cmd { if m.UISaving { return nil } @@ -159,7 +161,7 @@ func sessionAction(patch daemon.UIPreferencesPatch) string { return "" } -func (m *AppModel) patchUICmd(session string, patch daemon.UIPreferencesPatch, gen int) tea.Cmd { +func (m *Workspace) patchUICmd(session string, patch daemon.UIPreferencesPatch, gen int) tea.Cmd { conn := m.Conn if session == "" { patch.ETag = m.UI.ETag @@ -188,7 +190,7 @@ func (m *AppModel) patchUICmd(session string, patch daemon.UIPreferencesPatch, g } } -func (m *AppModel) recordOpenCmd(session string) tea.Cmd { +func (m *Workspace) recordOpenCmd(session string) tea.Cmd { conn := m.Conn return func() tea.Msg { prefs, err := daemon.RecordOpen(context.Background(), conn, session) diff --git a/cli/internal/tui/app_session_facts.go b/cli/internal/tui/app_session_facts.go index c0f0654f9..919a250ea 100644 --- a/cli/internal/tui/app_session_facts.go +++ b/cli/internal/tui/app_session_facts.go @@ -9,7 +9,7 @@ import ( tea "charm.land/bubbletea/v2" ) -func (m *AppModel) session(id string) (daemon.Session, bool) { +func (m *Workspace) session(id string) (daemon.Session, bool) { if m.ActiveSession != nil && m.ActiveSession.ID == id { return *m.ActiveSession, true } @@ -19,7 +19,7 @@ func (m *AppModel) session(id string) (daemon.Session, bool) { return daemon.Session{}, false } -func (m *AppModel) updateSession(session daemon.Session) { +func (m *Workspace) updateSession(session daemon.Session) { if i := slices.IndexFunc(m.Sessions, func(s daemon.Session) bool { return s.ID == session.ID }); i >= 0 { m.Sessions[i] = session } @@ -30,7 +30,7 @@ func (m *AppModel) updateSession(session daemon.Session) { m.updateSessionPickerItems() } -func (m *AppModel) applySessionList(sessions []daemon.Session) { +func (m *Workspace) applySessionList(sessions []daemon.Session) { // The reply is the client's listing: the sessions screen shares it rather // than keeping a copy of it. m.Sessions = sessions @@ -51,9 +51,9 @@ func (m *AppModel) applySessionList(sessions []daemon.Session) { // sessionFactsMsg is the session representation a refresh read. type sessionFactsMsg struct { - SessionID string Session daemon.Session Err error + SessionID string Gen int } @@ -62,7 +62,7 @@ type sessionFactsMsg struct { // can save its configuration, and a child spawns or closes beside it, so a copy // observed before any of them is refused when it is used. One read in flight at // a time answers all of them, and one that arrives meanwhile is read once more. -func (m *AppModel) refreshSessionFactsCmd() tea.Cmd { +func (m *Workspace) refreshSessionFactsCmd() tea.Cmd { if m.Conn == nil || m.ActiveSession == nil { return nil } @@ -81,7 +81,7 @@ func (m *AppModel) refreshSessionFactsCmd() tea.Cmd { // applySessionFacts takes what the daemon reported for the active session: the // validators its next change has to match, and the values it shows. -func (m *AppModel) applySessionFacts(msg sessionFactsMsg) { +func (m *Workspace) applySessionFacts(msg sessionFactsMsg) { if msg.Err != nil || m.ActiveSession == nil || m.ActiveSession.ID != msg.SessionID { return } @@ -111,7 +111,7 @@ func (m *AppModel) applySessionFacts(msg sessionFactsMsg) { // based on. The copy on screen is no longer the daemon's, so the same change // would keep being refused until the session was closed and opened again, or // the client restarted. -func (m *AppModel) refusedConfigurationCmd(err error) tea.Cmd { +func (m *Workspace) refusedConfigurationCmd(err error) tea.Cmd { // A model change saves the provider default it switches to as well. if apiErr, known := errors.AsType[*daemon.APIError](err); known && apiErr.Code == "settings_changed" { return m.refreshSettingsCmd() @@ -131,7 +131,7 @@ func windowTokens(value *int64) int64 { } // sessionCondition is the observed state a workspace move is conditional on. -func (m *AppModel) sessionCondition() daemon.SessionCondition { +func (m *Workspace) sessionCondition() daemon.SessionCondition { if m.ActiveSession == nil { return daemon.SessionCondition{} } diff --git a/cli/internal/tui/app_sessions.go b/cli/internal/tui/app_sessions.go index 537fa0fb8..30df42236 100644 --- a/cli/internal/tui/app_sessions.go +++ b/cli/internal/tui/app_sessions.go @@ -8,10 +8,12 @@ import ( "slices" "time" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" ) -func (m *AppModel) handleSessionResults(msg tea.Msg) (tea.Cmd, bool) { +func (m *Workspace) handleSessionResults(msg tea.Msg) (tea.Cmd, bool) { switch msg := msg.(type) { case sessionFactsMsg: if msg.Gen != m.SessionFactsGen { @@ -49,7 +51,7 @@ func (m *AppModel) handleSessionResults(msg tea.Msg) (tea.Cmd, bool) { case sessionDeletedMsg: if msg.Err != nil { - m.AddError(operationError(msg.Err, "Could not delete the session: ", "Session may have been deleted; refresh the session list before trying again.")) + m.AddError(chrome.OperationError(msg.Err, "Could not delete the session: ", "Session may have been deleted; refresh the session list before trying again.")) return nil, true } m.ClearNotices() @@ -73,16 +75,16 @@ func (m *AppModel) handleSessionResults(msg tea.Msg) (tea.Cmd, bool) { return m.loadSessionsCmd(m.SessionGen, msg.Result.Message), true } return nil, true - case SessionRenameMsg: + case chrome.SessionRenameMsg: m.SessionGen++ return m.renameSessionCmd(msg), true - case sessionRenamedMsg: + case chrome.SessionRenamedMsg: var cmd tea.Cmd if m.State == AppStateAgents { m.Agents, cmd = m.Agents.Update(msg) } if msg.Err != nil { - m.SessionPicker.notice = operationError(msg.Err, "Could not rename the session: ", "Session may have been renamed; refresh the session list before trying again.") + m.SessionPicker.notice = chrome.OperationError(msg.Err, "Could not rename the session: ", "Session may have been renamed; refresh the session list before trying again.") return tea.Batch(cmd, m.refusedConfigurationCmd(msg.Err)), true } if current, ok := m.session(msg.Configuration.Value.ID); ok { @@ -160,11 +162,11 @@ func (m *AppModel) handleSessionResults(msg tea.Msg) (tea.Cmd, bool) { return nil, true } if msg.Err != nil && m.State == AppStateFolderPicker { - m.FolderPicker.Refused(errors.New(operationError(msg.Err, "", "Session may have been created; check the session list before creating another."))) + m.FolderPicker.Refused(errors.New(chrome.OperationError(msg.Err, "", "Session may have been created; check the session list before creating another."))) return nil, true } if msg.Err != nil { - m.AddError(operationError(msg.Err, "Could not create a session: ", "Session may have been created; check the session list before creating another.")) + m.AddError(chrome.OperationError(msg.Err, "Could not create a session: ", "Session may have been created; check the session list before creating another.")) return nil, true } return m.setChatSession(msg.Session, true), true @@ -172,7 +174,7 @@ func (m *AppModel) handleSessionResults(msg tea.Msg) (tea.Cmd, bool) { return nil, false } -func (m *AppModel) loadSessionsCmd(gen int, notices ...string) tea.Cmd { +func (m *Workspace) loadSessionsCmd(gen int, notices ...string) tea.Cmd { m.listingSessions = true conn := m.Conn notice := "" @@ -188,26 +190,26 @@ func (m *AppModel) loadSessionsCmd(gen int, notices ...string) tea.Cmd { } } -func (m *AppModel) renameSessionCmd(rename SessionRenameMsg) tea.Cmd { +func (m *Workspace) renameSessionCmd(rename chrome.SessionRenameMsg) tea.Cmd { conn := m.Conn return func() tea.Msg { if conn == nil { - return sessionRenamedMsg{SessionRenameMsg: rename, Err: errors.New("daemon connection unavailable")} + return chrome.SessionRenamedMsg{SessionRenameMsg: rename, Err: errors.New("daemon connection unavailable")} } etag := rename.ETag if etag == "" { current, err := currentCondition(conn, rename.ID) if err != nil { - return sessionRenamedMsg{SessionRenameMsg: rename, Err: err} + return chrome.SessionRenamedMsg{SessionRenameMsg: rename, Err: err} } etag = current.ETag } s, err := daemon.RenameSession(context.Background(), conn, rename.ID, rename.Name, etag) - return sessionRenamedMsg{SessionRenameMsg: rename, Configuration: s, Err: err} + return chrome.SessionRenamedMsg{SessionRenameMsg: rename, Configuration: s, Err: err} } } -func (m *AppModel) deleteSessionCmd(id string, condition daemon.SessionCondition) tea.Cmd { +func (m *Workspace) deleteSessionCmd(id string, condition daemon.SessionCondition) tea.Cmd { m.SessionGen++ conn := m.Conn return func() tea.Msg { @@ -239,7 +241,7 @@ func sessionPreviewCmd(conn *daemon.Connection, id, etag string) tea.Cmd { } } -func (m *AppModel) createSessionCmd(gen int, workspace string) tea.Cmd { +func (m *Workspace) createSessionCmd(gen int, workspace string) tea.Cmd { conn := m.Conn handle, preparationErr := daemon.NewCreation(daemon.CreateSessionRequest{Workspace: workspace}) if preparationErr == nil { @@ -267,11 +269,11 @@ func creationRecoveryCmd(tick TickFunc, handle *daemon.OperationHandle, gen int) // updateSessionPickerItems hands the sessions screen the listing it draws. The // screen keeps the listing rather than a copy and builds its rows when it is // drawn, so a refresh in the chat costs one slice header. -func (m *AppModel) updateSessionPickerItems() { +func (m *Workspace) updateSessionPickerItems() { m.SessionPicker.SetSessions(m.Sessions, m.ActiveSession) } -func (m *AppModel) setChatSession(s daemon.Session, prepend bool) tea.Cmd { +func (m *Workspace) setChatSession(s daemon.Session, prepend bool) tea.Cmd { m.SessionGen++ m.afterReset = "" if m.pendingBySession == nil { @@ -303,12 +305,12 @@ func (m *AppModel) setChatSession(s daemon.Session, prepend bool) tea.Cmd { } // openSession makes session the chat on screen. -func (m *AppModel) openSession(s daemon.Session) tea.Cmd { +func (m *Workspace) openSession(s daemon.Session) tea.Cmd { m.ClearNotices() return tea.Batch(m.setChatSession(s, false), m.recordOpenCmd(s.ID)) } -func (m *AppModel) newSessionCmd() tea.Cmd { +func (m *Workspace) newSessionCmd() tea.Cmd { m.SessionGen++ return m.createSessionCmd(m.SessionGen, m.Workspace) } diff --git a/cli/internal/tui/app_terms.go b/cli/internal/tui/app_terms.go index 3642d24af..8a92715c2 100644 --- a/cli/internal/tui/app_terms.go +++ b/cli/internal/tui/app_terms.go @@ -12,8 +12,8 @@ import ( // termsLoadedMsg carries the daemon's sign-ins, for their terms warnings. type termsLoadedMsg struct { - signIns []daemon.SignIn err error + signIns []daemon.SignIn } // termsSeenMsg says the terms warning id was answered with a message sent. @@ -25,7 +25,7 @@ type termsSavedMsg struct { err error } -func (m *AppModel) loadTermsCmd() tea.Cmd { +func (m *Workspace) loadTermsCmd() tea.Cmd { conn := m.Conn if conn == nil { return nil @@ -36,7 +36,7 @@ func (m *AppModel) loadTermsCmd() tea.Cmd { } } -func (m *AppModel) handleTerms(msg tea.Msg) (tea.Cmd, bool) { +func (m *Workspace) handleTerms(msg tea.Msg) (tea.Cmd, bool) { switch msg := msg.(type) { case termsLoadedMsg: // Without the list no warning shows until a login screen reads it. @@ -67,7 +67,7 @@ func (m *AppModel) handleTerms(msg tea.Msg) (tea.Cmd, bool) { // termsFor is the terms warning a message on profile still owes: the one its // sign-in carries, while the profile has no API key of its own and the // warning was never dismissed. -func (m *AppModel) termsFor(profile string) *daemon.Terms { +func (m *Workspace) termsFor(profile string) *daemon.Terms { settings, known := m.Profiles.Providers[cmp.Or(profile, m.Profiles.Active)] if !known || settings.HasKey { return nil diff --git a/cli/internal/tui/app_view.go b/cli/internal/tui/app_view.go index 364e0067f..f3d0d2f63 100644 --- a/cli/internal/tui/app_view.go +++ b/cli/internal/tui/app_view.go @@ -3,7 +3,9 @@ package tui import ( "strings" - tea "charm.land/bubbletea/v2" + "albedo/cli/internal/terminalclient" + "albedo/cli/internal/terminalui" + "albedo/cli/internal/tui/chrome" ) // markPrefix opens a private APC mark, which describes a row for selection and @@ -44,74 +46,35 @@ func stripPrivateMarks(s string) string { return b.String() } -// View draws the active screen. The chat strips its own row marks as it builds -// a frame (and caches the result), so only other screens need the scan here. -func (m *AppModel) View() tea.View { - if m.attachedTo != nil { - return m.attachedTo.app.View() +func (m *Workspace) Route() terminalclient.Route { return m.State } +func (m *Workspace) Attached() *terminalclient.Client { + if m.attachedTo == nil { + return nil } - content := m.content() + return m.attachedTo.app.Client +} +func (m *Workspace) Size(width, height int) { m.Width, m.Height = width, height } +func (m *Workspace) WindowTitle() string { return windowTitle(m.titleMode, m.ActiveSession) } +func (m *Workspace) Overlay(content string) string { if m.State != AppStateChat { content = stripPrivateMarks(content) } - if m.cd != nil && !m.cd.hidden { - content = overlay(content, m.cd.view(m.Width, m.Height), m.Width, m.Height) + if m.State == AppStateLogin { + content = m.Login.overlay(content) } - v := tea.NewView(content) - v.WindowTitle = windowTitle(m.titleMode, m.ActiveSession) - v.MouseMode = tea.MouseModeNone - // ReportFocus lets a client animate only while its terminal is focused. - v.ReportFocus = true - if m.State == AppStateChat { - v.MouseMode = tea.MouseModeCellMotion + if m.cd != nil && !m.cd.hidden { + return overlay(content, m.cd.view(m.Width, m.Height), m.Width, m.Height) } - return v + return content } - -func (m *AppModel) content() string { - switch m.State { - case AppStateChat: - return m.Chat.View() - case AppStateSessionPicker: - var b strings.Builder - for _, n := range m.Notices { - style := DefaultStyles.Faint - if n.Error { - style = DefaultStyles.Error - } - b.WriteString(style.Render(n.Message)) - b.WriteByte('\n') +func (m *Workspace) sessionsPage() terminalui.Page { + page := m.SessionPicker.Page() + for _, n := range m.Notices { + style := chrome.DefaultStyles.Faint + if n.Error { + style = chrome.DefaultStyles.Error } - return b.String() + m.SessionPicker.View() - case AppStateModelPicker: - return m.ModelPicker.View() - case AppStateExtensionPicker: - return m.ExtensionPicker.View() - case AppStateTreePicker: - return m.TreePicker.View() - case AppStateContextInspector: - return m.ContextInspector.View() - case AppStatePageView: - return m.PageView.View() - case AppStateCapabilityPage: - return m.CapabilityPage.View() - case AppStateWebhooksPage: - return m.WebhooksPage.View() - case AppStateDiscordPage: - return m.DiscordPage.View() - case AppStateConfigPage: - return m.ConfigPage.View() - case AppStateAgents: - return m.Agents.View() - case AppStateFolderPicker: - return m.FolderPicker.View() - case AppStateLogin: - return m.Login.View() - case AppStateQuota: - return m.Quota.View() - case AppStateUsage: - return m.Usage.View() - default: - return "" + page.Notices = append(page.Notices, style.Render(n.Message)) } + return page } diff --git a/cli/internal/tui/artifact.go b/cli/internal/tui/artifact.go index 7b58ca9e4..22cdfcd00 100644 --- a/cli/internal/tui/artifact.go +++ b/cli/internal/tui/artifact.go @@ -10,19 +10,21 @@ import ( "path/filepath" "strconv" "strings" - "syscall" + "time" "albedo/cli/internal/component" "albedo/cli/internal/daemon" + "albedo/cli/internal/tui/chrome" "albedo/cli/internal/webui" + tea "charm.land/bubbletea/v2" ) type artifactOpenResult struct { + Err error Notice string Copied string - Err error } // artifactRow renders one selectable artifact activity consistently in transcript and cards. @@ -35,8 +37,8 @@ func artifactRow(activity daemon.ToolActivity, width int) string { label = fmt.Sprintf("↗ open artifact albedo updated: %s · v%d", activity.Target, activity.Artifact.Version) } key := activity.Artifact.ID + "." + strconv.FormatInt(activity.Artifact.Version, 10) - tail := DefaultStyles.Faint.Render(" · ") + DefaultStyles.Muted.Render("⧉") - return fit(rowAction{verb: verbArtifact, key: key}.mark()+DefaultStyles.Busy.Render(label), tail, width) + tail := chrome.DefaultStyles.Faint.Render(" · ") + chrome.DefaultStyles.Muted.Render("⧉") + return fit(rowAction{verb: verbArtifact, key: key}.mark()+chrome.DefaultStyles.Busy.Render(label), tail, width) } // openArtifactAction opens or copies the version a row names. The first @@ -117,7 +119,7 @@ func launchWeb(ctx context.Context, executable, path string, extra ...string) (s } command := exec.Command(executable, append([]string{"--no-open"}, extra...)...) command.Stdout, command.Stderr, command.Env = log, log, os.Environ() - command.SysProcAttr = &syscall.SysProcAttr{Setsid: true} + component.Detach(command) if err := command.Start(); err != nil { log.Close() return "", fmt.Errorf("cannot start albedo web: %w", err) diff --git a/cli/internal/tui/bounded_history.go b/cli/internal/tui/bounded_history.go index 938e5e61f..bb7700e73 100644 --- a/cli/internal/tui/bounded_history.go +++ b/cli/internal/tui/bounded_history.go @@ -23,26 +23,25 @@ const ( ) type HistoryEntry struct { - MessageID string - ID string - Source daemon.InputSource - MailKind string - SenderSessionID string - ToolArgs map[string]any + ToolArgs map[string]any // facts is what this entry contributes to a grouped row, computed once // when the entry settles. Targets stay as recorded; naming is at render. - facts *entryFacts - ToolTrace *daemon.ToolTrace - ShellCommand *daemon.ShellCommand - ShellOutputLoaded bool - ShellExpandedOutput string + facts *entryFacts + ToolTrace *daemon.ToolTrace + ShellCommand *daemon.ShellCommand // Skill is the skill a user's slash activation loaded. - Skill *daemon.SkillLoad - Speaker string - Mood mood - Text string - ToolName string - ToolResult string + Skill *daemon.SkillLoad + MessageID string + ID string + Source daemon.InputSource + MailKind string + SenderSessionID string + ShellExpandedOutput string + Speaker string + Mood mood + Text string + ToolName string + ToolResult string // ToolStatus is the daemon's outcome of the call: "completed" or "failed". ToolStatus string ToolTitle string @@ -67,7 +66,8 @@ type HistoryEntry struct { CacheDriftTokens int // Seq is the newest transcript row this entry came from; 0 until a // `committed` event says which rows cover it. - Seq int64 + Seq int64 + ShellOutputLoaded bool // Live is a reply still streaming in. It renders on every token, so it // skips the second rendering that marks wraps for a copy until it settles. Live bool @@ -189,6 +189,12 @@ func (h *BoundedHistory) Replace(entry HistoryEntry) bool { return true } +// insert adds a reconstructed boundary while an older page is being joined. +func (h *BoundedHistory) insert(at int, entry HistoryEntry) { + h.totalBytes += entry.ComputeSize() + h.entries = slices.Insert(h.entries, at, entry) +} + // Prepend puts older entries before the retained ones. It does not evict: // they were asked for, and Trim or the next Append restores the bounds. func (h *BoundedHistory) Prepend(older []HistoryEntry) { diff --git a/cli/internal/tui/burst.go b/cli/internal/tui/burst.go index 236103fd8..3c35cb29a 100644 --- a/cli/internal/tui/burst.go +++ b/cli/internal/tui/burst.go @@ -9,6 +9,8 @@ import ( "strings" "albedo/cli/internal/daemon" + "albedo/cli/internal/tui/chrome" + "github.com/charmbracelet/x/ansi" ) @@ -259,7 +261,7 @@ func collect(entries []HistoryEntry) burst { func pyLabel(title, code string) string { line := title if line == "" { - line = firstLine(code) + line = chrome.FirstLine(code) } return ansi.Truncate(oneLine(line), 48, "…") } @@ -332,7 +334,7 @@ func (r TranscriptRenderer) summary(b burst, width int, n namer) string { } tail := "" if n := len(b.failed); n > 0 { - tail += DefaultStyles.Error.Render(fmt.Sprintf(" · %d failed", n)) + tail += chrome.DefaultStyles.Error.Render(fmt.Sprintf(" · %d failed", n)) } if b.added+b.removed > 0 { tail += " " + r.diffCounts(daemon.FileChange{Added: b.added, Removed: b.removed}) @@ -342,7 +344,7 @@ func (r TranscriptRenderer) summary(b burst, width int, n namer) string { room := width - ansi.StringWidth(tail) for ansi.StringWidth(line()) > room && shorten(clauses) { } - return fit(DefaultStyles.Faint.Render(line()), tail, width) + return fit(chrome.DefaultStyles.Faint.Render(line()), tail, width) } // queries names each search by its query, quoted, on one line. @@ -487,7 +489,7 @@ func (r TranscriptRenderer) RenderBurst(entries []HistoryEntry, flags DisplayFla if open { toggle = toggleOpen } - head += rowAction{verbOpen, key}.mark() + DefaultStyles.Faint.Render(toggle) + head += rowAction{verbOpen, key}.mark() + chrome.DefaultStyles.Faint.Render(toggle) room -= ansi.StringWidth(toggle) } rows := []string{head + r.summary(b, room, n)} @@ -498,7 +500,7 @@ func (r TranscriptRenderer) RenderBurst(entries []HistoryEntry, flags DisplayFla } } else { for _, entry := range b.failed { - rows = append(rows, markChrome+DefaultStyles.Error.Render(toolRow(entry, true, "", width))) + rows = append(rows, markChrome+chrome.DefaultStyles.Error.Render(toolRow(entry, true, "", width))) } } for _, look := range b.looked { @@ -516,7 +518,7 @@ func (r TranscriptRenderer) RenderBurst(entries []HistoryEntry, flags DisplayFla if change.Kind == "diff" { rows = append(rows, r.renderDiffPath(change.Diff, change.Path, width)) } else { - rows = append(rows, DefaultStyles.Faint.Render(n.name(prepareTarget(change.Path))+": "+change.Reason)) + rows = append(rows, chrome.DefaultStyles.Faint.Render(n.name(prepareTarget(change.Path))+": "+change.Reason)) } } } @@ -549,15 +551,15 @@ func (r TranscriptRenderer) steps(entries []HistoryEntry, width int) []string { } trace := entry.ToolTrace if trace == nil || len(trace.Activities)+len(trace.Changes) == 0 { - failed, style := toolFailed(entry), DefaultStyles.Faint + failed, style := toolFailed(entry), chrome.DefaultStyles.Faint if failed { - style = DefaultStyles.Error + style = chrome.DefaultStyles.Error } rows = append(rows, style.Render(toolRow(entry, failed, "", width))) continue } for _, act := range trace.Activities { - style := DefaultStyles.Faint + style := chrome.DefaultStyles.Faint rows = append(rows, style.Render(r.traceLine(stepLabel(act.Kind), act.Target, isPath(act), width))) } for _, change := range trace.Changes { @@ -566,7 +568,7 @@ func (r TranscriptRenderer) steps(entries []HistoryEntry, width int) []string { counts = " " + r.diffCounts(change) } line := r.traceLine(stepLabel("edit"), change.Path, true, width-ansi.StringWidth(counts)) - rows = append(rows, fit(DefaultStyles.Faint.Render(line), counts, width)) + rows = append(rows, fit(chrome.DefaultStyles.Faint.Render(line), counts, width)) } } return rows diff --git a/cli/internal/tui/capability_pages.go b/cli/internal/tui/capability_pages.go index aceefc17f..b520c9805 100644 --- a/cli/internal/tui/capability_pages.go +++ b/cli/internal/tui/capability_pages.go @@ -3,6 +3,7 @@ package tui import ( "albedo/cli/internal/config" "albedo/cli/internal/daemon" + "albedo/cli/internal/terminalui" "cmp" "context" "errors" @@ -11,6 +12,8 @@ import ( "slices" "strings" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -20,22 +23,25 @@ import ( // changes this session only. MCP servers are added and edited through one // form (mcp_form.go) that opens over the list. type CapabilityPageModel struct { - Prefs config.CapabilityPrefs - Conn *daemon.Connection - Form *mcpForm - SignIn *mcpSignIn - openBrowser func(string) - SessionID, Kind string - Items []capabilityItem - Revision string - SessionETag, GlobalETag, MCPETag string - Diagnostics []string - ExtensionEnabled bool + Prefs config.CapabilityPrefs + Conn *daemon.Connection + Form *mcpForm + SignIn *mcpSignIn + openBrowser func(string) + Revision string + Kind string + SessionID string + SessionETag string + GlobalETag string + MCPETag string + confirm chrome.Confirm + Items []capabilityItem + Diagnostics []string + listView + pageStatus + ExtensionEnabled bool // noticeWarns says the notice is a warning rather than a save that went through. noticeWarns bool - pageStatus - listView - confirm } type capabilityItem struct { @@ -90,11 +96,11 @@ func NewCapabilityPageModel(conn *daemon.Connection, sessionID, kind string) Cap func (m *CapabilityPageModel) SetSize(width, height int) { m.pageStatus.SetSize(width, height) - m.listView.setSize(width, height) + m.setSize(width, height) } // Confirming reports a question waiting for enter or esc. -func (m CapabilityPageModel) Confirming() bool { return m.confirm.asking() } +func (m CapabilityPageModel) Confirming() bool { return m.confirm.Asking() } func (m CapabilityPageModel) Init() tea.Cmd { return m.loadCmd(m.Generation) } @@ -252,18 +258,18 @@ func (m CapabilityPageModel) Update(msg tea.Msg) (CapabilityPageModel, tea.Cmd) if msg.Gen == m.Generation { if apiErr, ok := errors.AsType[*daemon.APIError](msg.Err); ok && apiErr.Code == "catalog_changed" { m.Saving, m.Loading, m.Error = false, true, "" - m.confirm.dismiss() + m.confirm.Dismiss() m.Notice, m.noticeWarns = "The list changed. Review it before trying again.", true m.Generation = nextPageGeneration() return m, m.loadCmd(m.Generation) } } if !m.settle(msg.Gen, msg.Err, &m.Saving) { - m.confirm.failed = msg.Gen == m.Generation + m.confirm.Failed = msg.Gen == m.Generation return m, nil } m.Form = nil - m.confirm.dismiss() + m.confirm.Dismiss() m.Notice = cmp.Or(msg.Notice, "Saved. Reload the session to apply the selection.") m.noticeWarns = msg.Warns m.Loading, m.Generation = true, nextPageGeneration() @@ -284,11 +290,11 @@ func (m CapabilityPageModel) Update(msg tea.Msg) (CapabilityPageModel, tea.Cmd) case tea.KeyPressMsg: switch { - case m.confirm.asking() && !m.Saving: - if m.confirm.key(msg) { + case m.confirm.Asking() && !m.Saving: + if m.confirm.Key(msg) { return m.confirmed() } - if !m.confirm.asking() { + if !m.confirm.Asking() { m.Error = "" } return m, nil @@ -303,7 +309,7 @@ func (m CapabilityPageModel) Update(msg tea.Msg) (CapabilityPageModel, tea.Cmd) } return m.listKey(msg) } - cmd := m.listView.update(msg) + cmd := m.update(msg) return m, cmd } @@ -367,18 +373,18 @@ func (m CapabilityPageModel) listKey(msg tea.KeyPressMsg) (CapabilityPageModel, } case "ctrl+u": if mcp && ok && item.Secrets.Auth.State == "signed_in" { - m.confirm.ask(actionSignOut, item.ID, "sign out", fmt.Sprintf("Its tools stop working until you sign in again. Sign out of %s?", item.Title)) + m.confirm.Ask(actionSignOut, item.ID, "sign out", fmt.Sprintf("Its tools stop working until you sign in again. Sign out of %s?", item.Title)) } case "ctrl+t": if !m.ExtensionEnabled { - m.confirm.ask(actionEnableExtension, m.Kind, "enable", fmt.Sprintf("Enable the %s extension? This reloads this session to apply it.", m.Kind)) + m.confirm.Ask(actionEnableExtension, m.Kind, "enable", fmt.Sprintf("Enable the %s extension? This reloads this session to apply it.", m.Kind)) } case "ctrl+r": m.Loading, m.Error, m.Notice = true, "", "" m.Generation = nextPageGeneration() return m, m.loadCmd(m.Generation) default: - cmd := m.listView.update(msg) + cmd := m.update(msg) return m, cmd } return m, nil @@ -396,7 +402,7 @@ func (m CapabilityPageModel) enableServer(item capabilityItem) (CapabilityPageMo // askDeleteServer asks before removing an MCP server and its credentials. func (m *CapabilityPageModel) askDeleteServer(item capabilityItem) { - m.confirm.ask(actionDeleteServer, item.ID, "delete", fmt.Sprintf("Its stored credentials will also be removed. Delete MCP server %s?", item.Title)) + m.confirm.Ask(actionDeleteServer, item.ID, "delete", fmt.Sprintf("Its stored credentials will also be removed. Delete MCP server %s?", item.Title)) } // askToggle asks before changing a row in one scope, or before dropping @@ -408,7 +414,7 @@ func (m *CapabilityPageModel) askToggle(scope string) { } m.Error = "" if scope == scopeInherit { - m.confirm.ask(scope, item.ID, "follow global", fmt.Sprintf("This session will follow the global default for %s. Remove its own choice?", item.Title)) + m.confirm.Ask(scope, item.ID, "follow global", fmt.Sprintf("This session will follow the global default for %s. Remove its own choice?", item.Title)) return } verb := "enable" @@ -420,13 +426,13 @@ func (m *CapabilityPageModel) askToggle(scope string) { if scope == scopeSession { prompt = fmt.Sprintf("%s %s for this session only? Reload this session to apply it.", sentence, item.Title) } - m.confirm.ask(scope, item.ID, verb, prompt) + m.confirm.Ask(scope, item.ID, verb, prompt) } // confirmed runs the change the question asked about. The question stays up // while the change is in flight, so a failure can be retried with enter. func (m CapabilityPageModel) confirmed() (CapabilityPageModel, tea.Cmd) { - target, what := m.confirm.target, m.confirm.what + target, what := m.confirm.Target, m.confirm.What switch what { case actionEnableExtension: return m.save(m.enableExtensionCmd) @@ -437,7 +443,7 @@ func (m CapabilityPageModel) confirmed() (CapabilityPageModel, tea.Cmd) { } item, ok := m.itemNamed(target) if !ok { - m.confirm.dismiss() + m.confirm.Dismiss() return m, nil } if what == scopeInherit { @@ -538,9 +544,9 @@ func (m CapabilityPageModel) entry(item capabilityItem) listEntry { entry.search = []string{candidate.ID, candidate.Source} switch { case !candidate.Valid: - entry.lead = DefaultStyles.Warning.Render("invalid") + entry.lead = chrome.DefaultStyles.Warning.Render("invalid") case candidate.ShadowedBy != nil: - entry.lead = DefaultStyles.Faint.Render("shadowed") + entry.lead = chrome.DefaultStyles.Faint.Render("shadowed") } } entry.lead = daggered(entry.lead, m.hasSessionChoice(item)) @@ -667,34 +673,34 @@ func storedLabel(names daemon.MCPSecretNames) string { // hints are the keys this page answers now; the ones that do not apply to // the highlighted row or this extension state are left out. -func (m CapabilityPageModel) hints(item capabilityItem, ok bool) []hint { +func (m CapabilityPageModel) hints(item capabilityItem, ok bool) []chrome.Hint { mcp := m.Kind == "mcp" - hints := []hint{{"↑↓", "move"}} + hints := []chrome.Hint{{Key: "↑↓", Does: "move"}} if m.extensionOff() { - hints = append(hints, hint{"ctrl+t", "enable extension"}) + hints = append(hints, chrome.Hint{Key: "ctrl+t", Does: "enable extension"}) } if ok && m.canToggle(item, scopeGlobal) { - hints = append(hints, hint{"enter", "global"}) + hints = append(hints, chrome.Hint{Key: "enter", Does: "global"}) } if mcp { - hints = append(hints, hint{"ctrl+o", "add server"}) + hints = append(hints, chrome.Hint{Key: "ctrl+o", Does: "add server"}) if ok { hints = append(hints, m.signInHints(item)...) - hints = append(hints, hint{"ctrl+e", "edit"}, hint{"ctrl+x", "delete"}) + hints = append(hints, chrome.Hint{Key: "ctrl+e", Does: "edit"}, chrome.Hint{Key: "ctrl+x", Does: "delete"}) } } if ok { if m.canToggle(item, scopeSession) { - hints = append(hints, hint{"shift+enter", "this session"}) + hints = append(hints, chrome.Hint{Key: "shift+enter", Does: "this session"}) } if !mcp && m.canClear(item) { - hints = append(hints, hint{"ctrl+x", "follow global"}) + hints = append(hints, chrome.Hint{Key: "ctrl+x", Does: "follow global"}) } if serverDisabled(item) { - hints = append(hints, hint{"ctrl+g", "enable server"}) + hints = append(hints, chrome.Hint{Key: "ctrl+g", Does: "enable server"}) } } - return append(hints, hint{"ctrl+r", "refresh"}, hint{"esc", "back"}) + return append(hints, chrome.Hint{Key: "ctrl+r", Does: "refresh"}, chrome.Hint{Key: "esc", Does: "back"}) } // extensionOff is whether a loaded page found its extension switched off. @@ -710,19 +716,19 @@ func (m CapabilityPageModel) status() (string, bool) { } switch { case m.Saving: - return DefaultStyles.Busy.Render("saving and reloading…"), true + return chrome.DefaultStyles.Busy.Render("saving and reloading…"), true case m.Loading: - return DefaultStyles.Faint.Render("loading…"), false + return chrome.DefaultStyles.Faint.Render("loading…"), false case m.Error != "": - return DefaultStyles.Error.Render(m.Error), true + return chrome.DefaultStyles.Error.Render(m.Error), true case m.Notice != "": return notice(m.Notice, m.noticeWarns), true case m.extensionOff(): - return DefaultStyles.Warning.Render("extension is off"), true + return chrome.DefaultStyles.Warning.Render("extension is off"), true case len(m.Diagnostics) > 0: - return DefaultStyles.Warning.Render(m.diagnosticLine()), true + return chrome.DefaultStyles.Warning.Render(m.diagnosticLine()), true } - return DefaultStyles.Faint.Render(counted(len(m.Items), capabilityNouns[m.Kind])), false + return chrome.DefaultStyles.Faint.Render(counted(len(m.Items), capabilityNouns[m.Kind])), false } func (m CapabilityPageModel) diagnosticLine() string { @@ -733,8 +739,8 @@ func (m CapabilityPageModel) diagnosticLine() string { } func (m CapabilityPageModel) footer(width int) string { - if m.confirm.asking() && !m.Saving { - return m.confirm.footer(width, m.Error) + if m.confirm.Asking() && !m.Saving { + return m.confirm.Footer(width, m.Error) } status, urgent := m.status() if m.Form != nil { @@ -745,7 +751,7 @@ func (m CapabilityPageModel) footer(width int) string { return " " + ansi.Truncate(status, max(1, width-2), "…") + "\n" + keys } item, ok := m.current() - return footerLine(width, m.hints(item, ok), status, urgent) + return chrome.FooterLine(width, m.hints(item, ok), status, urgent) } // summary is the highlighted row's source or address, for a width too @@ -767,7 +773,7 @@ func (m CapabilityPageModel) formList(width, height int) []string { return rows[:min(len(rows), height)] } -func (m CapabilityPageModel) View() string { +func (m CapabilityPageModel) Page() terminalui.Page { width := max(1, m.Width) lv := m.listView noun := capabilityNouns[m.Kind] @@ -778,16 +784,16 @@ func (m CapabilityPageModel) View() string { case m.Error != "" && len(m.Items) == 0: lv.Empty = "Could not load " + noun + "s; the reason is in the footer." } - frame := lv.frame(brand("albedo")+" "+DefaultStyles.Muted.Render("/"+m.Kind), daggerLegend(slices.ContainsFunc(m.Items, m.hasSessionChoice)), m.footer(width)) + frame := lv.frame(chrome.Brand("albedo")+" "+chrome.DefaultStyles.Muted.Render("/"+m.Kind), daggerLegend(slices.ContainsFunc(m.Items, m.hasSessionChoice)), m.footer(width)) if m.Form != nil { - frame.filter, frame.pane, frame.list = "", nil, m.formList + frame.Filter, frame.Detail, frame.List = "", nil, m.formList } else { - frame.summary = m.summary() + frame.Summary = m.summary() } - if item, ok := m.current(); ok && m.confirm.asking() && slices.Contains([]string{scopeGlobal, scopeSession, scopeInherit}, m.confirm.what) { - frame.pane = detailPane(func(width int) []string { return m.details(item, m.confirm.what, width) }) + if item, ok := m.current(); ok && m.confirm.Asking() && slices.Contains([]string{scopeGlobal, scopeSession, scopeInherit}, m.confirm.What) { + frame.Detail = detailPane(func(width int) []string { return m.details(item, m.confirm.What, width) }) } - return frame.view(m.Width, m.Height) + return frame } func capabilityChoiceID(item capabilityItem, scope string) string { diff --git a/cli/internal/tui/cards.go b/cli/internal/tui/cards.go index dafa3ef18..27a77bd48 100644 --- a/cli/internal/tui/cards.go +++ b/cli/internal/tui/cards.go @@ -10,6 +10,8 @@ import ( "albedo/cli/internal/daemon" + "albedo/cli/internal/tui/chrome" + "github.com/charmbracelet/x/ansi" ) @@ -33,9 +35,9 @@ func (r TranscriptRenderer) shellCard(entry HistoryEntry, width int) []string { inner := max(1, width-2) panel := func(text string) string { text = ansi.Truncate(text, inner, "…") - return diffPanel() + " " + keepBackground(text) + strings.Repeat(" ", max(0, inner-ansi.StringWidth(text))) + " " + ansiReset + return chrome.DiffPanel() + " " + chrome.KeepBackground(text) + strings.Repeat(" ", max(0, inner-ansi.StringWidth(text))) + " " + chrome.AnsiReset } - head := DefaultStyles.Busy.Render("! " + oneLine(command.Command)) + head := chrome.DefaultStyles.Busy.Render("! " + oneLine(command.Command)) state := command.Status if command.ExitCode != nil { state += fmt.Sprintf(" · exit %d", *command.ExitCode) @@ -49,13 +51,13 @@ func (r TranscriptRenderer) shellCard(entry HistoryEntry, width int) []string { delivery = "sent to agent" } } - status := DefaultStyles.Faint.Render(" " + state) + status := chrome.DefaultStyles.Faint.Render(" " + state) if delivery != "" { - status += DefaultStyles.Faint.Render(" · " + delivery) + status += chrome.DefaultStyles.Faint.Render(" · " + delivery) } rows := []string{markChrome + panel(fit(head, status, inner))} if command.Status == "running" { - rows = append(rows, markChrome+rowAction{"cancel", command.ID}.mark()+panel(DefaultStyles.Faint.Render("running · click to cancel · ctrl+shift+x cancels latest"))) + rows = append(rows, markChrome+rowAction{"cancel", command.ID}.mark()+panel(chrome.DefaultStyles.Faint.Render("running · click to cancel · ctrl+shift+x cancels latest"))) } output := command.Output if open && entry.ShellOutputLoaded { @@ -71,7 +73,7 @@ func (r TranscriptRenderer) shellCard(entry HistoryEntry, width int) []string { } var body []string for _, line := range wrapped(lines, inner) { - body = append(body, panel(DefaultStyles.Faint.Render(line))) + body = append(body, panel(chrome.DefaultStyles.Faint.Render(line))) } if open && entry.ShellOutputLoaded { rows = append(rows, body...) @@ -79,20 +81,20 @@ func (r TranscriptRenderer) shellCard(entry HistoryEntry, width int) []string { shown := min(cardOutputRows, len(body)) rows = append(rows, body[:shown]...) if open && !entry.ShellOutputLoaded && command.OutputBytes > int64(len(command.Output)) { - rows = append(rows, panel(DefaultStyles.Faint.Render("loading full retained output…"))) + rows = append(rows, panel(chrome.DefaultStyles.Faint.Render("loading full retained output…"))) } else if len(body) > shown || command.OutputBytes > int64(len(command.Output)) || command.Truncated { label := fmt.Sprintf("%s%d more lines · click to expand", toggleClosed, max(0, len(body)-shown)) - rows = append(rows, markChrome+rowAction{verbMore, key}.mark()+panel(DefaultStyles.Faint.Render(label))) + rows = append(rows, markChrome+rowAction{verbMore, key}.mark()+panel(chrome.DefaultStyles.Faint.Render(label))) } } if command.Truncated { - rows = append(rows, panel(DefaultStyles.Error.Render("capture capped at 16 MiB; later output is unavailable"))) + rows = append(rows, panel(chrome.DefaultStyles.Error.Render("capture capped at 16 MiB; later output is unavailable"))) } if message := daemon.ShellCommandErrorText(*command); message != "" { - rows = append(rows, panel(DefaultStyles.Error.Render(oneLine(message)))) + rows = append(rows, panel(chrome.DefaultStyles.Error.Render(oneLine(message)))) } if open && entry.ShellOutputLoaded { - rows = append(rows, markChrome+rowAction{verbMore, key}.mark()+panel(DefaultStyles.Faint.Render(toggleOpen+"show less"))) + rows = append(rows, markChrome+rowAction{verbMore, key}.mark()+panel(chrome.DefaultStyles.Faint.Render(toggleOpen+"show less"))) } return rows } @@ -104,10 +106,10 @@ func (r TranscriptRenderer) toolCard(entry HistoryEntry, flags DisplayFlags, wid inner := max(1, width-2) panel := func(row string) string { row = ansi.Truncate(row, inner, "…") - return diffPanel() + " " + keepBackground(row) + strings.Repeat(" ", max(0, inner-ansi.StringWidth(row))) + " " + ansiReset + return chrome.DiffPanel() + " " + chrome.KeepBackground(row) + strings.Repeat(" ", max(0, inner-ansi.StringWidth(row))) + " " + chrome.AnsiReset } fold := func(hidden int, noun string) string { - return markChrome + rowAction{verbMore, key}.mark() + panel(DefaultStyles.Faint.Render(fmt.Sprintf("%s%d more %s · click to expand", toggleClosed, hidden, noun))) + return markChrome + rowAction{verbMore, key}.mark() + panel(chrome.DefaultStyles.Faint.Render(fmt.Sprintf("%s%d more %s · click to expand", toggleClosed, hidden, noun))) } folded := false var rows []string @@ -135,9 +137,9 @@ func (r TranscriptRenderer) toolCard(entry HistoryEntry, flags DisplayFlags, wid rows = append(append(rows, body[:limit]...), fold(hidden, noun)) } - name, glyph := cardName(entry), DefaultStyles.Busy + name, glyph := cardName(entry), chrome.DefaultStyles.Busy if failed { - name, glyph = "✗ "+name, DefaultStyles.Error + name, glyph = "✗ "+name, chrome.DefaultStyles.Error } var facts []string if took := cellDuration(entry); took != "" { @@ -147,7 +149,7 @@ func (r TranscriptRenderer) toolCard(entry HistoryEntry, flags DisplayFlags, wid facts = append(facts, "failed") } facts = append(facts, formatClock(entry.Timestamp)) - rows = append(rows, markChrome+panel(fit(glyph.Bold(true).Render(name), DefaultStyles.Faint.Render(" "+strings.Join(facts, " · ")), inner))) + rows = append(rows, markChrome+panel(fit(glyph.Bold(true).Render(name), chrome.DefaultStyles.Faint.Render(" "+strings.Join(facts, " · ")), inner))) if code, lang := cardInput(entry); strings.TrimSpace(code) != "" { var body []string @@ -159,9 +161,9 @@ func (r TranscriptRenderer) toolCard(entry HistoryEntry, flags DisplayFlags, wid section(r.cardCalls(entry.ToolTrace, flags, inner, panel), cardCallRows, true, "calls") var body []string for _, part := range cardOutput(entry) { - ink := DefaultStyles.Faint + ink := chrome.DefaultStyles.Faint if part.failed { - ink = DefaultStyles.Error + ink = chrome.DefaultStyles.Error } for _, line := range wrapped(plainLines(part.text), inner) { body = append(body, panel(ink.Render(line))) @@ -169,7 +171,7 @@ func (r TranscriptRenderer) toolCard(entry HistoryEntry, flags DisplayFlags, wid } section(body, cardOutputRows, false, "lines") if open && folded { - rows = append(rows, markChrome+rowAction{verbMore, key}.mark()+panel(DefaultStyles.Faint.Render(toggleOpen+"show less"))) + rows = append(rows, markChrome+rowAction{verbMore, key}.mark()+panel(chrome.DefaultStyles.Faint.Render(toggleOpen+"show less"))) } return rows } @@ -197,12 +199,12 @@ func (r TranscriptRenderer) cardCalls(trace *daemon.ToolTrace, flags DisplayFlag rows = append(rows, markChrome+panel(artifactRow(act, width))) continue } - head := callGlyph(act) + " " + DefaultStyles.Busy.Render(act.Kind) + " " + head := callGlyph(act) + " " + chrome.DefaultStyles.Busy.Render(act.Kind) + " " took := "" if act.MS != nil { - took = " " + DefaultStyles.Decor.Render(formatMillis(*act.MS)) + took = " " + chrome.DefaultStyles.Decor.Render(formatMillis(*act.MS)) } - target := DefaultStyles.Faint.Render(r.shortTarget(act.Target, isPath(act), width-ansi.StringWidth(head)-ansi.StringWidth(took))) + target := chrome.DefaultStyles.Faint.Render(r.shortTarget(act.Target, isPath(act), width-ansi.StringWidth(head)-ansi.StringWidth(took))) if act.Kind == "run" { command := HighlightLines(plainLines(r.named(act.Target)), lexerFor("command.sh"), r.highlights) target = ansi.Truncate(strings.Join(command, " "), max(1, width-ansi.StringWidth(head)-ansi.StringWidth(took)), "…") @@ -219,13 +221,13 @@ func (r TranscriptRenderer) cardCalls(trace *daemon.ToolTrace, flags DisplayFlag if change.Kind == "diff" { counts = " " + r.diffCounts(change) } - line := r.traceLine(DefaultStyles.Success.Render("✓")+" "+DefaultStyles.Busy.Render("edited"), change.Path, true, width-ansi.StringWidth(counts)) + line := r.traceLine(chrome.DefaultStyles.Success.Render("✓")+" "+chrome.DefaultStyles.Busy.Render("edited"), change.Path, true, width-ansi.StringWidth(counts)) rows = append(rows, markChrome+panel(fit(line, counts, width))) if !flags.Diffs { continue } if change.Kind != "diff" { - rows = append(rows, markChrome+panel(DefaultStyles.Faint.Render(change.Reason))) + rows = append(rows, markChrome+panel(chrome.DefaultStyles.Faint.Render(change.Reason))) continue } // the edited row above already names the file @@ -235,7 +237,7 @@ func (r TranscriptRenderer) cardCalls(trace *daemon.ToolTrace, flags DisplayFlag } } if trace.Truncated { - rows = append(rows, markChrome+panel(DefaultStyles.Faint.Render("some activity was not captured; this list is incomplete"))) + rows = append(rows, markChrome+panel(chrome.DefaultStyles.Faint.Render("some activity was not captured; this list is incomplete"))) } return rows } @@ -323,11 +325,11 @@ func formatMillis(ms int64) string { func callGlyph(act daemon.ToolActivity) string { switch { case act.OK == nil: - return DefaultStyles.Faint.Render("·") + return chrome.DefaultStyles.Faint.Render("·") case *act.OK: - return DefaultStyles.Success.Render("✓") + return chrome.DefaultStyles.Success.Render("✓") default: - return DefaultStyles.Error.Render("✗") + return chrome.DefaultStyles.Error.Render("✗") } } diff --git a/cli/internal/tui/cd_checklist.go b/cli/internal/tui/cd_checklist.go index 8e865c06b..659972a0e 100644 --- a/cli/internal/tui/cd_checklist.go +++ b/cli/internal/tui/cd_checklist.go @@ -8,6 +8,8 @@ import ( "albedo/cli/internal/daemon" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -52,7 +54,7 @@ func (q *cdQuestion) checklistView(width, height int) []string { } inner := outer - 6 host := q.host() - face := DefaultStyles.Agent.Render(connectingFace(host, q.frame)) + face := chrome.DefaultStyles.Agent.Render(connectingFace(host, q.frame)) var head, tail []string wrap := func(rows *[]string, style func(...string) string, text string) { for line := range strings.SplitSeq(ansi.Wrap(text, inner, " "), "\n") { @@ -61,17 +63,17 @@ func (q *cdQuestion) checklistView(width, height int) []string { } head = append(head, "") if _, path := daemon.SplitLocation(q.target); path != "" { - wrap(&head, DefaultStyles.Muted.Render, q.target) + wrap(&head, chrome.DefaultStyles.Muted.Render, q.target) } - var keys []hint + var keys []chrome.Hint var bindings, compact [][]string switch q.phase { case cdMoving: - head = append(head, DefaultStyles.Muted.Render("reading the move to "+host)+" "+face) - keys = []hint{{"esc", "hide"}} + head = append(head, chrome.DefaultStyles.Muted.Render("reading the move to "+host)+" "+face) + keys = []chrome.Hint{{Key: "esc", Does: "hide"}} case cdFailed: - wrap(&head, DefaultStyles.Error.Render, q.failure) - keys = []hint{{"esc", "close"}, {"enter", "retry"}} + wrap(&head, chrome.DefaultStyles.Error.Render, q.failure) + keys = []chrome.Hint{{Key: "esc", Does: "close"}, {Key: "enter", Does: "retry"}} default: intro := "Live on " + host + " now; this copy still runs until the move finishes." if len(q.move.Bindings) == 0 { @@ -89,7 +91,7 @@ func (q *cdQuestion) checklistView(width, height int) []string { tail = append(tail, "") } if failure := q.finishFailure(); failure != "" { - wrap(&tail, DefaultStyles.Error.Render, failure) + wrap(&tail, chrome.DefaultStyles.Error.Render, failure) tail = append(tail, "") } tail, keys = q.checklistChoices(tail, face) @@ -101,7 +103,7 @@ func (q *cdQuestion) checklistView(width, height int) []string { if len(slices.Concat(bindings...)) > room { bindings = compact } - return cdFrame("/cd", append(append(head, fitBindings(bindings, room)...), tail...), outer) + return fitCDFrame(head, append(fitBindings(bindings, room), tail...), outer, height) } // listedBindings are the move's bindings in the order the checklist lists @@ -133,12 +135,12 @@ func (q *cdQuestion) finishFailure() string { return cmp.Or(q.failure, q.move.Er // checklistChoices adds the two lines, or what replaced them, to rows and // returns them with the keys under the box. -func (q *cdQuestion) checklistChoices(rows []string, face string) ([]string, []hint) { +func (q *cdQuestion) checklistChoices(rows []string, face string) ([]string, []chrome.Hint) { switch q.phase { case cdFinishing: - return append(rows, DefaultStyles.Muted.Render("disarming and finishing")+" "+face), []hint{{"esc", "hide"}} + return append(rows, chrome.DefaultStyles.Muted.Render("disarming and finishing")+" "+face), []chrome.Hint{{Key: "esc", Does: "hide"}} case cdAttaching: - return append(rows, DefaultStyles.Success.Render("moved")+DefaultStyles.Muted.Render(" · opening it on "+q.host())+" "+face), []hint{{"esc", "hide"}} + return append(rows, chrome.DefaultStyles.Success.Render("moved")+chrome.DefaultStyles.Muted.Render(" · opening it on "+q.host())+" "+face), []chrome.Hint{{Key: "esc", Does: "hide"}} } finish, verb := "disarm all and finish the move", "finish" switch { @@ -149,28 +151,28 @@ func (q *cdQuestion) checklistChoices(rows []string, face string) ([]string, []h } line := func(selected bool, label string) string { if selected { - return DefaultStyles.Prompt.Render("› " + label) + return chrome.DefaultStyles.Prompt.Render("› " + label) } - return DefaultStyles.Muted.Render(" " + label) + return chrome.DefaultStyles.Muted.Render(" " + label) } rows = append(rows, line(!q.later, finish), line(q.later, "later")) if q.later { verb = "later" } - return rows, []hint{{"esc", "later"}, {"enter", verb}} + return rows, []chrome.Hint{{Key: "esc", Does: "later"}, {Key: "enter", Does: verb}} } // bindingRows is one binding as the checklist lists it: its kind and label, // what it does, a webhook's old and new address, and once a finish was // tried, whether it was disarmed. compact leaves only the kind and label. func (q *cdQuestion) bindingRows(b daemon.MoveBinding, inner int, compact bool) []string { - mark := DefaultStyles.Faint.Render("· ") + mark := chrome.DefaultStyles.Faint.Render("· ") if q.tried() { switch b.Status { case "disarmed": - mark = DefaultStyles.Success.Render("✓ ") + mark = chrome.DefaultStyles.Success.Render("✓ ") case "failed": - mark = DefaultStyles.Error.Render("✗ ") + mark = chrome.DefaultStyles.Error.Render("✗ ") } } const indent = 12 // the mark, the kind and a gap @@ -185,25 +187,25 @@ func (q *cdQuestion) bindingRows(b daemon.MoveBinding, inner int, compact bool) rows = append(rows, lead+style(line)) } } - hang(mark+DefaultStyles.Muted.Render(fmt.Sprintf("%-10s", b.Kind)), unstyled, b.Label) + hang(mark+chrome.DefaultStyles.Muted.Render(fmt.Sprintf("%-10s", b.Kind)), unstyled, b.Label) if compact { return rows } if b.Detail != "" && b.Detail != b.Label { - hang(pad, DefaultStyles.Faint.Render, b.Detail) + hang(pad, chrome.DefaultStyles.Faint.Render, b.Detail) } switch { case b.NewURL != "": - hang(pad, DefaultStyles.Faint.Render, "re-point its sender") + hang(pad, chrome.DefaultStyles.Faint.Render, "re-point its sender") if b.OldURL != "" { - hang(pad, DefaultStyles.Faint.Render, "from "+b.OldURL) + hang(pad, chrome.DefaultStyles.Faint.Render, "from "+b.OldURL) } hang(pad, unstyled, "to "+b.NewURL) case b.OldURL != "": - hang(pad, DefaultStyles.Faint.Render, "senders post to "+b.OldURL) + hang(pad, chrome.DefaultStyles.Faint.Render, "senders post to "+b.OldURL) } if b.Status == "failed" && b.Error != "" { - hang(pad, DefaultStyles.Error.Render, b.Error) + hang(pad, chrome.DefaultStyles.Error.Render, b.Error) } return rows } @@ -222,7 +224,7 @@ func fitBindings(bindings [][]string, room int) []string { need++ // the line saying how many more } if len(rows)+need > room { - return append(rows, DefaultStyles.Faint.Render(fmt.Sprintf(" … and %d more", len(bindings)-i))) + return append(rows, chrome.DefaultStyles.Faint.Render(fmt.Sprintf(" … and %d more", len(bindings)-i))) } rows = append(rows, b...) } diff --git a/cli/internal/tui/cd_checklist_test.go b/cli/internal/tui/cd_checklist_test.go index c9aefdc09..a679f43d6 100644 --- a/cli/internal/tui/cd_checklist_test.go +++ b/cli/internal/tui/cd_checklist_test.go @@ -102,12 +102,12 @@ func (d *checklistDaemon) serve(t *testing.T) *daemon.Connection { // pendingApp is a chat on session a, its move to vassago waiting in its // checklist. -func pendingApp(t *testing.T, conn *daemon.Connection) *AppModel { +func pendingApp(t *testing.T, conn *daemon.Connection) *Workspace { session := cdShotSession() session.MovePending = &daemon.SessionMovePending{TransferID: "t1", Host: "vassago"} - app := NewAppModel(conn, Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) + app := NewWorkspace(conn, Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) t.Cleanup(func() { app.Chat.Close() }) - app.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) + app.Client.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) return app } @@ -117,7 +117,7 @@ func TestCDChecklistLaterLeavesTheMoveToResumeFromTheChatAndCD(t *testing.T) { if !strings.Contains(strings.Join(app.Chat.movedRows(120), "\n"), "moving to vassago · checklist pending") { t.Fatal("the chat does not say its move waits") } - _, cmd := app.Update(keyEnter) + _, cmd := app.Client.Update(keyEnter) settleCD(t, app, cmd) if app.cd == nil || app.cd.phase != cdChecklist || fake.reads != 1 { t.Fatal("enter on an empty composer must reopen the checklist, read afresh") @@ -125,11 +125,11 @@ func TestCDChecklistLaterLeavesTheMoveToResumeFromTheChatAndCD(t *testing.T) { if app.cd.target != cdShotTarget { t.Fatalf("the reopened box names %q", app.cd.target) } - app.Update(keyEsc) + app.Client.Update(keyEsc) if app.cd != nil || app.ActiveSession.MovePending == nil || app.Chat.movePending == nil { t.Fatal("later must close the box and leave the move pending") } - _, cmd = app.Update(ChatExecuteCommandMsg{Name: "/cd", Args: "elsewhere"}) + _, cmd = app.Client.Update(ChatExecuteCommandMsg{Name: "/cd", Args: "elsewhere"}) settleCD(t, app, cmd) if app.cd == nil || app.cd.phase != cdChecklist || fake.reads != 2 { t.Fatal("/cd on a session whose move waits must reopen its checklist") @@ -147,9 +147,9 @@ func TestCDChecklistRetriesAPartialFinishThenOpensTheSessionThere(t *testing.T) opened = append(opened, host+" "+home) return nil, errors.New("connection refused") } - _, cmd := app.Update(keyEnter) + _, cmd := app.Client.Update(keyEnter) settleCD(t, app, cmd) - _, cmd = app.Update(keyEnter) + _, cmd = app.Client.Update(keyEnter) settleCD(t, app, cmd) if app.cd == nil || app.cd.phase != cdChecklist { t.Fatal("a partial finish must keep the checklist") @@ -160,7 +160,7 @@ func TestCDChecklistRetriesAPartialFinishThenOpensTheSessionThere(t *testing.T) t.Fatalf("box lacks %q:\n%s", want, box) } } - _, cmd = app.Update(keyEnter) + _, cmd = app.Client.Update(keyEnter) settleCD(t, app, cmd) if len(fake.finishes) != 0 || len(opened) != 1 || opened[0] != "vassago /home/ana/.albedo" { t.Fatalf("finishes left %d, attached to %q", len(fake.finishes), opened) diff --git a/cli/internal/tui/cd_move.go b/cli/internal/tui/cd_move.go index 56e2213bc..8ecf79b24 100644 --- a/cli/internal/tui/cd_move.go +++ b/cli/internal/tui/cd_move.go @@ -64,7 +64,7 @@ type detachMsg struct{} // attachedApp is a session's new daemon, shown in place of this one's // screens until it quits. type attachedApp struct { - app *AppModel + app *Workspace attachment *attach.Attachment } @@ -86,7 +86,7 @@ func cdTarget(workspace, input string) (string, bool) { // askCD opens the /cd question for target and asks the daemon whether the // session can move there, naming the folder first when it was typed under // the host's home. -func (m *AppModel) askCD(target string, retry *WorkspaceRetry) tea.Cmd { +func (m *Workspace) askCD(target string, retry *WorkspaceRetry) tea.Cmd { if m.ActiveSession == nil { return nil } @@ -113,12 +113,12 @@ func (m *AppModel) askCD(target string, retry *WorkspaceRetry) tea.Cmd { }, m.cdTick(gen)) } -func (m *AppModel) cdTick(gen int64) tea.Cmd { +func (m *Workspace) cdTick(gen int64) tea.Cmd { return tea.Tick(faceInterval, func(time.Time) tea.Msg { return cdTickMsg{Gen: gen} }) } // handleCD takes the /cd question's messages and its keys while it shows. -func (m *AppModel) handleCD(msg tea.Msg) (tea.Cmd, bool) { +func (m *Workspace) handleCD(msg tea.Msg) (tea.Cmd, bool) { switch msg := msg.(type) { case cdAskMsg: return m.askCD(msg.Target, msg.Retry), true @@ -176,7 +176,7 @@ func (m *AppModel) handleCD(msg tea.Msg) (tea.Cmd, bool) { } // cdKey does what a key on the question chose. -func (m *AppModel) cdKey(choice cdChoice) tea.Cmd { +func (m *Workspace) cdKey(choice cdChoice) tea.Cmd { q := m.cd switch choice { case cdClose, cdLater: @@ -206,7 +206,7 @@ func (m *AppModel) cdKey(choice cdChoice) tea.Cmd { // after a move that failed takes a new transfer id; after a request that // failed it asks again under the same one, which joins the move if it went // on. -func (m *AppModel) startMove() tea.Cmd { +func (m *Workspace) startMove() tea.Cmd { q := m.cd if q.listed && q.move.State != "failed" { q.phase, q.failure = cdMoving, "" @@ -230,7 +230,7 @@ func (m *AppModel) startMove() tea.Cmd { // moveProgressed takes the move's latest state: a settled move fails in the // box or opens the session where it went; otherwise it is read again. -func (m *AppModel) moveProgressed(msg cdMoveMsg) tea.Cmd { +func (m *Workspace) moveProgressed(msg cdMoveMsg) tea.Cmd { q := m.cd defer m.syncMoveStatus() if msg.Err != nil { @@ -260,7 +260,7 @@ func (m *AppModel) moveProgressed(msg cdMoveMsg) tea.Cmd { // movedAway marks the session moved here and opens it on the daemon it // went to, with what was typed or waiting to be sent. -func (m *AppModel) movedAway(move daemon.Move) tea.Cmd { +func (m *Workspace) movedAway(move daemon.Move) tea.Cmd { q := m.cd host, _ := daemon.SplitLocation(q.target) m.markMove(q.sessionID, &daemon.SessionMoved{Host: q.host(), Workspace: q.target, TransferID: q.transferID, At: time.Now()}, nil) @@ -276,7 +276,7 @@ func (m *AppModel) movedAway(move daemon.Move) tea.Cmd { } // attachMoved opens the chat's moved session where it went. -func (m *AppModel) attachMoved(msg ChatAttachMsg) tea.Cmd { +func (m *Workspace) attachMoved(msg ChatAttachMsg) tea.Cmd { moved := m.Chat.moved if moved == nil || msg.SessionID != m.Chat.SessionID { return nil @@ -289,7 +289,7 @@ func (m *AppModel) attachMoved(msg ChatAttachMsg) tea.Cmd { // attachCmd forwards a port to host's daemon and reads what the attached // view opens with. home is that daemon's albedo home there, read from the // transfer when it is not known. -func (m *AppModel) attachCmd(host, home, sessionID, transferID, draft string) tea.Cmd { +func (m *Workspace) attachCmd(host, home, sessionID, transferID, draft string) tea.Cmd { conn, open := m.Conn, m.openAttachment if open == nil { open = func(ctx context.Context, host, home string) (*attach.Attachment, error) { @@ -329,7 +329,7 @@ func (m *AppModel) attachCmd(host, home, sessionID, transferID, draft string) te // attached shows the session on its new daemon, or why it could not be // reached in the moved session's banner. -func (m *AppModel) attached(msg attachedMsg) tea.Cmd { +func (m *Workspace) attached(msg attachedMsg) tea.Cmd { var lost []string if m.cd != nil { lost = m.cd.move.Lost @@ -360,7 +360,7 @@ func (m *AppModel) attached(msg attachedMsg) tea.Cmd { m.Chat.Close() m.State = AppStateSessionPicker session := msg.Session - child := NewAppModel(msg.Attachment.Conn, Bootstrap{Sessions: msg.Sessions, Settings: msg.Settings}, &session, session.Workspace, false, m.openBrowser) + child := NewWorkspace(msg.Attachment.Conn, Bootstrap{Sessions: msg.Sessions, Settings: msg.Settings}, &session, session.Workspace, false, m.openBrowser) child.nested, child.Tick, child.Graphemes = true, m.Tick, m.Graphemes if msg.Draft != "" { child.Chat.TextArea.SetValue(msg.Draft) @@ -370,12 +370,12 @@ func (m *AppModel) attached(msg attachedMsg) tea.Cmd { } m.attachedTo = &attachedApp{app: child, attachment: msg.Attachment} w, h := m.Width, m.Height - return tea.Batch(child.Init(), func() tea.Msg { return tea.WindowSizeMsg{Width: w, Height: h} }) + return tea.Batch(child.Client.Init(), func() tea.Msg { return tea.WindowSizeMsg{Width: w, Height: h} }) } // updateAttached hands msg to the attached view; it returns false while // nothing is attached. -func (m *AppModel) updateAttached(msg tea.Msg) (tea.Cmd, bool) { +func (m *Workspace) updateAttached(msg tea.Msg) (tea.Cmd, bool) { if m.attachedTo == nil { return nil, false } @@ -385,14 +385,12 @@ func (m *AppModel) updateAttached(msg tea.Msg) (tea.Cmd, bool) { case tea.WindowSizeMsg: m.Width, m.Height = msg.Width, msg.Height } - model, cmd := m.attachedTo.app.Update(msg) - m.attachedTo.app = model.(*AppModel) - return cmd, true + return m.attachedTo.app.Client.Dispatch(msg), true } // detach closes the attached view and its forward, and shows this daemon's // session list. -func (m *AppModel) detach() tea.Cmd { +func (m *Workspace) detach() tea.Cmd { attached := m.attachedTo m.attachedTo = nil cleanup := attached.app.Close() @@ -404,7 +402,7 @@ func (m *AppModel) detach() tea.Cmd { } // quit ends the program, or, attached under another view, returns to it. -func (m *AppModel) quit() tea.Cmd { +func (m *Workspace) quit() tea.Cmd { if m.nested { return func() tea.Msg { return detachMsg{} } } @@ -412,7 +410,7 @@ func (m *AppModel) quit() tea.Cmd { } // syncMoveStatus puts a hidden box's move in the chat's status line. -func (m *AppModel) syncMoveStatus() { +func (m *Workspace) syncMoveStatus() { m.Chat.moveStatus = "" if m.cd != nil && m.cd.hidden { m.Chat.moveStatus = m.cd.statusText() @@ -420,7 +418,7 @@ func (m *AppModel) syncMoveStatus() { } // readMove reads the box's move again. -func (m *AppModel) readMove() tea.Cmd { +func (m *Workspace) readMove() tea.Cmd { conn, id, gen := m.Conn, m.cd.transferID, m.cd.gen return func() tea.Msg { move, err := daemon.GetTransfer(context.Background(), conn, id) @@ -430,7 +428,7 @@ func (m *AppModel) readMove() tea.Cmd { // reopenChecklist opens the box on the session's move waiting in its // checklist, read afresh from the daemon. -func (m *AppModel) reopenChecklist(sessionID string) tea.Cmd { +func (m *Workspace) reopenChecklist(sessionID string) tea.Cmd { s, ok := m.session(sessionID) if !ok || s.MovePending == nil { return nil @@ -444,7 +442,7 @@ func (m *AppModel) reopenChecklist(sessionID string) tea.Cmd { } // finishMove asks the daemon to disarm the checklist and finish the move. -func (m *AppModel) finishMove() tea.Cmd { +func (m *Workspace) finishMove() tea.Cmd { q := m.cd q.phase, q.failure = cdFinishing, "" conn, id, gen := m.Conn, q.transferID, q.gen @@ -456,7 +454,7 @@ func (m *AppModel) finishMove() tea.Cmd { // finished takes a finish's outcome: a finished move opens the session where // it went; one still in checklist shows each binding's status, to retry. -func (m *AppModel) finished(msg cdFinishedMsg) tea.Cmd { +func (m *Workspace) finished(msg cdFinishedMsg) tea.Cmd { q := m.cd defer m.syncMoveStatus() if msg.Err != nil { @@ -468,7 +466,7 @@ func (m *AppModel) finished(msg cdFinishedMsg) tea.Cmd { } // markMove records where session id stands in its move, here and in its chat. -func (m *AppModel) markMove(id string, moved *daemon.SessionMoved, pending *daemon.SessionMovePending) { +func (m *Workspace) markMove(id string, moved *daemon.SessionMoved, pending *daemon.SessionMovePending) { if s, ok := m.session(id); ok { s.Moved, s.MovePending = moved, pending m.updateSession(s) diff --git a/cli/internal/tui/cd_question.go b/cli/internal/tui/cd_question.go index f0f8ce81a..b0f0e122f 100644 --- a/cli/internal/tui/cd_question.go +++ b/cli/internal/tui/cd_question.go @@ -2,9 +2,13 @@ package tui import ( "fmt" + "slices" "strings" "albedo/cli/internal/daemon" + "albedo/cli/internal/terminalui" + + "albedo/cli/internal/tui/chrome" tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" @@ -273,14 +277,14 @@ func (q *cdQuestion) view(width, height int) []string { return q.checklistView(width, height) } for tight := 0; ; tight++ { - if box := q.draw(width, tight); len(box) <= height || tight == cdTightest { + if box := q.draw(width, height, tight); len(box) <= height || tight == cdTightest { return box } } } // draw is the box with tight steps of view's dropped. -func (q *cdQuestion) draw(width, tight int) []string { +func (q *cdQuestion) draw(width, height, tight int) []string { outer := cdBoxWidth(width) inner := outer - 6 // a border and two spaces each side var body []string @@ -290,20 +294,21 @@ func (q *cdQuestion) draw(width, tight int) []string { } } plain := func(s string) string { return s } - faint := func(s string) string { return DefaultStyles.Faint.Render(s) } + faint := func(s string) string { return chrome.DefaultStyles.Faint.Render(s) } host := q.host() face := connectingFace(host, q.frame) if tight < cdTightest { body = append(body, "") } - wrap(func(s string) string { return DefaultStyles.Muted.Render(s) }, q.target) + wrap(func(s string) string { return chrome.DefaultStyles.Muted.Render(s) }, q.target) wrap(plain, cdQuestionText) if tight < 1 { wrap(faint, cdQuestionNote) } body = append(body, "") - var keys []hint + head := len(body) + var keys []chrome.Hint switch q.phase { case cdAsking: body = append(body, q.choices(inner, tight)...) @@ -314,23 +319,23 @@ func (q *cdQuestion) draw(width, tight int) []string { case q.yes: verb = "move" } - keys = []hint{{"esc", "cancel"}, {"enter", verb}} + keys = []chrome.Hint{{Key: "esc", Does: "cancel"}, {Key: "enter", Does: verb}} case cdMoving: - body = append(body, DefaultStyles.Muted.Render("moving to "+host)+" "+DefaultStyles.Agent.Render(face)) + body = append(body, chrome.DefaultStyles.Muted.Render("moving to "+host)+" "+chrome.DefaultStyles.Agent.Render(face)) wrap(faint, q.progress()) - keys = []hint{{"esc", "hide · the move goes on"}} + keys = []chrome.Hint{{Key: "esc", Does: "hide · the move goes on"}} case cdAttaching: - body = append(body, DefaultStyles.Success.Render("moved")+DefaultStyles.Muted.Render(" · opening it on "+host)+" "+DefaultStyles.Agent.Render(face)) - keys = []hint{{"esc", "hide"}} + body = append(body, chrome.DefaultStyles.Success.Render("moved")+chrome.DefaultStyles.Muted.Render(" · opening it on "+host)+" "+chrome.DefaultStyles.Agent.Render(face)) + keys = []chrome.Hint{{Key: "esc", Does: "hide"}} case cdFailed: why, words := q.failed() - wrap(func(s string) string { return DefaultStyles.Error.Render(s) }, why) + wrap(func(s string) string { return chrome.DefaultStyles.Error.Render(s) }, why) wrap(faint, "the session stays here, as it was.") if words != "" { body = append(body, "") wrap(faint, words) } - keys = []hint{{"esc", "close"}, {"enter", "retry"}} + keys = []chrome.Hint{{Key: "esc", Does: "close"}, {Key: "enter", Does: "retry"}} } body = append(body, "") hints := cdKeys(keys) @@ -338,6 +343,9 @@ func (q *cdQuestion) draw(width, tight int) []string { if tight < cdTightest { body = append(body, "") } + if tight == cdTightest { + return fitCDFrame(body[:head], body[head:], outer, height) + } return cdFrame("/cd", body, outer) } @@ -349,29 +357,29 @@ func (q *cdQuestion) choices(inner, tight int) []string { line := func(selected bool, label, aside string) string { switch { case selected: - return DefaultStyles.Prompt.Render("› " + label) + return chrome.DefaultStyles.Prompt.Render("› " + label) case aside != "": - return DefaultStyles.Faint.Render(" "+label) + " " + aside + return chrome.DefaultStyles.Faint.Render(" "+label) + " " + aside } - return DefaultStyles.Muted.Render(" " + label) + return chrome.DefaultStyles.Muted.Render(" " + label) } detail := func(text string) { for l := range strings.SplitSeq(ansi.Wrap(text, inner-4, " "), "\n") { - rows = append(rows, " "+DefaultStyles.Faint.Render(l)) + rows = append(rows, " "+chrome.DefaultStyles.Faint.Render(l)) } } switch { case q.checking(): - rows = append(rows, line(false, "yes", DefaultStyles.Faint.Render("checking "+host+" ")+DefaultStyles.Agent.Render(connectingFace(host, q.frame)))) + rows = append(rows, line(false, "yes", chrome.DefaultStyles.Faint.Render("checking "+host+" ")+chrome.DefaultStyles.Agent.Render(connectingFace(host, q.frame)))) case !q.canMove(): - rows = append(rows, line(false, "yes", DefaultStyles.Muted.Render("unavailable"))) + rows = append(rows, line(false, "yes", chrome.DefaultStyles.Muted.Render("unavailable"))) why, words := q.unavailable() if words == "" { detail(why) break } for l := range strings.SplitSeq(ansi.Wrap(why, inner-4, " "), "\n") { - rows = append(rows, " "+DefaultStyles.Muted.Render(l)) + rows = append(rows, " "+chrome.DefaultStyles.Muted.Render(l)) } detail(words) default: @@ -379,7 +387,7 @@ func (q *cdQuestion) choices(inner, tight int) []string { if tight < cdTightest { detail(q.facts()) } else { - rows = append(rows, " "+DefaultStyles.Faint.Render(ansi.Truncate(q.facts(), inner-4, "…"))) + rows = append(rows, " "+chrome.DefaultStyles.Faint.Render(ansi.Truncate(q.facts(), inner-4, "…"))) } rows = append(rows, q.pickRows(inner, tight >= 2)...) } @@ -397,9 +405,9 @@ func (q *cdQuestion) pickRows(inner int, gapless bool) []string { if !gapless { rows = append(rows, "") } - rows = append(rows, " "+DefaultStyles.Muted.Render(r.Name+" · "+r.Model)) + rows = append(rows, " "+chrome.DefaultStyles.Muted.Render(r.Name+" · "+r.Model)) for l := range strings.SplitSeq(ansi.Wrap(r.Reason+"; run it there on", inner-4, " "), "\n") { - rows = append(rows, " "+DefaultStyles.Faint.Render(l)) + rows = append(rows, " "+chrome.DefaultStyles.Faint.Render(l)) } for _, profile := range r.Alternatives { n++ @@ -409,11 +417,11 @@ func (q *cdQuestion) pickRows(inner int, gapless bool) []string { } switch { case q.option == n: - rows = append(rows, " "+DefaultStyles.Prompt.Render("› "+mark+profile)) + rows = append(rows, " "+chrome.DefaultStyles.Prompt.Render("› "+mark+profile)) case mark == "● ": - rows = append(rows, " "+DefaultStyles.Muted.Render(" "+mark+profile)) + rows = append(rows, " "+chrome.DefaultStyles.Muted.Render(" "+mark+profile)) default: - rows = append(rows, " "+DefaultStyles.Faint.Render(" "+mark+profile)) + rows = append(rows, " "+chrome.DefaultStyles.Faint.Render(" "+mark+profile)) } } } @@ -468,21 +476,43 @@ func (q *cdQuestion) statusText() string { return "" } -func cdKeys(keys []hint) string { +func cdKeys(keys []chrome.Hint) string { parts := make([]string, len(keys)) for i, k := range keys { - parts[i] = DefaultStyles.Muted.Render(k.key) + " " + DefaultStyles.Faint.Render(k.does) + parts[i] = chrome.DefaultStyles.Muted.Render(k.Key) + " " + chrome.DefaultStyles.Faint.Render(k.Does) } return strings.Join(parts, " ") } +// Keep the destination and question fixed. When choices overflow, move +// their window with the keyboard focus and keep the action hints below it. +func fitCDFrame(head, body []string, width, height int) []string { + if len(head)+len(body)+2 <= height { + return cdFrame("/cd", append(head, body...), width) + } + compact := func(rows []string) []string { + return slices.DeleteFunc(rows, func(s string) bool { return strings.TrimSpace(s) == "" }) + } + head, body = compact(head), compact(body) + room := height - 2 - len(head) + if len(body) > room && room >= 2 { + choices, keys := body[:len(body)-1], body[len(body)-1] + selected := slices.IndexFunc(choices, func(s string) bool { + return strings.HasPrefix(strings.TrimSpace(ansi.Strip(s)), "›") + }) + start := windowStart(len(choices), selected, room-1) + body = append(choices[start:start+room-1:start+room-1], keys) + } + return cdFrame("/cd", append(head, body...), width) +} + // cdFrame draws body in a rounded box outer columns wide, title in its top // edge. func cdFrame(title string, body []string, outer int) []string { inner := outer - 2 - decor := DefaultStyles.Decor.Render + decor := chrome.DefaultStyles.Decor.Render head := "─ " + title + " " - top := decor("╭─ ") + DefaultStyles.Bold.Render(title) + decor(" "+strings.Repeat("─", max(0, inner-ansi.StringWidth(head)))+"╮") + top := decor("╭─ ") + chrome.DefaultStyles.Bold.Render(title) + decor(" "+strings.Repeat("─", max(0, inner-ansi.StringWidth(head)))+"╮") rows := []string{top} for _, line := range body { line = ansi.Truncate(line, inner-4, "…") @@ -494,28 +524,7 @@ func cdFrame(title string, body []string, outer int) []string { // overlay lays box centred over the screen, which steps back to the faint // ink under it. func overlay(screen string, box []string, width, height int) string { - lines := strings.Split(screen, "\n") - for len(lines) < height { - lines = append(lines, "") - } - boxWidth := 0 - for _, b := range box { - boxWidth = max(boxWidth, ansi.StringWidth(b)) - } - left := max(0, (width-boxWidth)/2) - top := max(0, (height-len(box))/2) - for i, line := range lines { - plain := ansi.Strip(line) - if i < top || i >= top+len(box) { - lines[i] = DefaultStyles.Decor.Render(plain) - continue - } - before := ansi.Truncate(plain, left, "") - before += strings.Repeat(" ", left-ansi.StringWidth(before)) - after := ansi.TruncateLeft(plain, left+boxWidth, "") - lines[i] = DefaultStyles.Decor.Render(before) + box[i-top] + DefaultStyles.Decor.Render(after) - } - return strings.Join(lines, "\n") + return terminalui.Dialog(screen, box, width, height, chrome.DefaultStyles.Decor) } // sizeText is a byte count as a person reads it. diff --git a/cli/internal/tui/cd_question_test.go b/cli/internal/tui/cd_question_test.go index 5792ea8e3..b93b7a55f 100644 --- a/cli/internal/tui/cd_question_test.go +++ b/cli/internal/tui/cd_question_test.go @@ -137,6 +137,14 @@ func TestCDQuestionWithPicksFitsAShortScreen(t *testing.T) { if len(box) > 20 { t.Fatalf("the box is %d rows on a 20-row screen:\n%s", len(box), text) } + q.key(keyUp) + q.key(keyUp) + box = q.view(90, 16) + text = ansi.Strip(strings.Join(box, "\n")) + if len(box) > 16 || !strings.Contains(text, cdShotTarget) || !strings.Contains(text, "› ● opencode-zen") || !strings.Contains(text, "enter pick") { + t.Fatalf("the move destination, current profile and keys must fit in 16 rows:\n%s", text) + } + } func TestCDQuestionWithoutAnAlternativeShowsWhyAndOffersOnlyNo(t *testing.T) { @@ -199,7 +207,7 @@ func (d *moveDaemon) serve(t *testing.T) *daemon.Connection { // settleCD runs cmd and feeds what it returns back into app until nothing is // left but ticks, which it drops. -func settleCD(t *testing.T, app *AppModel, cmd tea.Cmd) { +func settleCD(t *testing.T, app *Workspace, cmd tea.Cmd) { t.Helper() queue := []tea.Cmd{cmd} for len(queue) > 0 { @@ -223,7 +231,7 @@ func settleCD(t *testing.T, app *AppModel, cmd tea.Cmd) { case cdTickMsg, nil: continue } - _, more := app.Update(msg) + _, more := app.Client.Update(msg) queue = append(queue, more) } } @@ -231,20 +239,20 @@ func settleCD(t *testing.T, app *AppModel, cmd tea.Cmd) { func TestCDYesMovesThenShowsAnUnreachableTargetInTheBanner(t *testing.T) { fake := &moveDaemon{} session := cdShotSession() - app := NewAppModel(fake.serve(t), Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) + app := NewWorkspace(fake.serve(t), Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) defer app.Chat.Close() var opened []string app.openAttachment = func(_ context.Context, host, home string) (*attach.Attachment, error) { opened = append(opened, host+" "+home) return nil, errors.New("connection refused") } - app.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) - _, cmd := app.Update(ChatExecuteCommandMsg{Name: "/cd", Args: cdShotTarget}) + app.Client.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) + _, cmd := app.Client.Update(ChatExecuteCommandMsg{Name: "/cd", Args: cdShotTarget}) settleCD(t, app, cmd) if app.cd == nil || !app.cd.yes { t.Fatal("the question did not open on yes for an available target") } - _, cmd = app.Update(keyEnter) + _, cmd = app.Client.Update(keyEnter) settleCD(t, app, cmd) if len(fake.moves) != 1 || fake.moves[0].Target != cdShotTarget || fake.moves[0].TransferID == "" || fake.moves[0].Profiles != nil { t.Fatalf("moves = %v", fake.moves) @@ -268,18 +276,18 @@ func TestCDYesSendsTheProfilesPicked(t *testing.T) { `{"session_id":"a","name":"fleet rollout","ok":false,"profile":"claude","model":"claude-opus-5-5","reason":"vassago has no claude profile: sign in there first","alternatives":["bedrock","vertex"]},` + `{"session_id":"b","name":"scout","ok":true,"profile":"codex","model":"gpt-5.6-luna","reason":null,"alternatives":[]}]}`} session := cdShotSession() - app := NewAppModel(fake.serve(t), Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) + app := NewWorkspace(fake.serve(t), Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) defer app.Chat.Close() app.openAttachment = func(context.Context, string, string) (*attach.Attachment, error) { return nil, errors.New("connection refused") } - app.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) - _, cmd := app.Update(ChatExecuteCommandMsg{Name: "/cd", Args: cdShotTarget}) + app.Client.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) + _, cmd := app.Client.Update(ChatExecuteCommandMsg{Name: "/cd", Args: cdShotTarget}) settleCD(t, app, cmd) for _, key := range []tea.KeyPressMsg{keyDown, keyDown, keyEnter, keyUp, keyUp} { - app.Update(key) + app.Client.Update(key) } - _, cmd = app.Update(keyEnter) + _, cmd = app.Client.Update(keyEnter) settleCD(t, app, cmd) if len(fake.moves) != 1 || len(fake.moves[0].Profiles) != 1 || fake.moves[0].Profiles["a"] != "vertex" { t.Fatalf("moves = %+v", fake.moves) @@ -291,16 +299,16 @@ func TestCDYesSendsTheProfilesPicked(t *testing.T) { // the target's words, which name what it lacks, beneath. func TestCDAnOlderTargetSaysToUpdateItAndKeepsItsWords(t *testing.T) { const lacks = "core/sessions here lacks pending_switch_caller, pending_switch_model" - boxed := func(app *AppModel) string { + boxed := func(app *Workspace) string { box := strings.ReplaceAll(ansi.Strip(strings.Join(app.cd.view(120, 40), "\n")), "│", "") return strings.Join(strings.Fields(box), " ") } - open := func(fake *moveDaemon) *AppModel { + open := func(fake *moveDaemon) *Workspace { session := cdShotSession() - app := NewAppModel(fake.serve(t), Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) + app := NewWorkspace(fake.serve(t), Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) t.Cleanup(app.Chat.Close) - app.Update(tea.WindowSizeMsg{Width: 120, Height: 40}) - _, cmd := app.Update(ChatExecuteCommandMsg{Name: "/cd", Args: cdShotTarget}) + app.Client.Update(tea.WindowSizeMsg{Width: 120, Height: 40}) + _, cmd := app.Client.Update(ChatExecuteCommandMsg{Name: "/cd", Args: cdShotTarget}) settleCD(t, app, cmd) return app } @@ -321,7 +329,7 @@ func TestCDAnOlderTargetSaysToUpdateItAndKeepsItsWords(t *testing.T) { fake := &moveDaemon{polled: `{"id":"x","session_id":"a","target":"` + cdShotTarget + `","state":"failed","progress":{"bytes_done":0,"bytes_total":0},"error":{"code":"transfer_target_older","detail":"` + lacks + `"},"reason":null,"target_session_id":null,"target_home":null,"lost":[],"bindings":[]}`} during := open(fake) - _, cmd := during.Update(keyEnter) + _, cmd := during.Client.Update(keyEnter) settleCD(t, during, cmd) if during.cd == nil || during.cd.phase != cdFailed { t.Fatal("a move refused at staging must fail in the box") @@ -361,12 +369,12 @@ func TestCDAMissingExtensionDoesNotAlwaysMeanUpdate(t *testing.T) { func TestCDNoMovesOnlyTheKernel(t *testing.T) { fake := &moveDaemon{} session := cdShotSession() - app := NewAppModel(fake.serve(t), Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) + app := NewWorkspace(fake.serve(t), Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) defer app.Chat.Close() app.cd = newCDQuestion("a", cdShotTarget, nil) app.cd.checked(daemon.TransferPreflight{Available: true}, nil) - app.Update(keyDown) - _, cmd := app.Update(keyEnter) + app.Client.Update(keyDown) + _, cmd := app.Client.Update(keyEnter) if app.cd != nil || cmd == nil { t.Fatal("no must close the box and move the session's folder") } @@ -381,16 +389,16 @@ func TestCDNoMovesOnlyTheKernel(t *testing.T) { func TestQuittingTheAttachedViewReturnsToTheSessionList(t *testing.T) { conn := daemon.NewConnection(daemon.ConnectionSnapshot{Port: 1}, nil) session := cdShotSession() - app := NewAppModel(conn, Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) - child := NewAppModel(conn, Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) + app := NewWorkspace(conn, Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) + child := NewWorkspace(conn, Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) child.nested = true app.attachedTo = &attachedApp{app: child, attachment: &attach.Attachment{}} - _, cmd := app.Update(ChatQuitMsg{}) + _, cmd := app.Client.Update(ChatQuitMsg{}) msg := cmd() if _, ok := msg.(detachMsg); !ok { t.Fatalf("the attached view quit the program: %T", msg) } - app.Update(msg) + app.Client.Update(msg) if app.attachedTo != nil || app.State != AppStateSessionPicker { t.Fatal("detaching must return to this daemon's session list") } diff --git a/cli/internal/tui/chat.go b/cli/internal/tui/chat.go index 6fd2ca366..6f97e711d 100644 --- a/cli/internal/tui/chat.go +++ b/cli/internal/tui/chat.go @@ -9,6 +9,8 @@ import ( "strings" "time" + "albedo/cli/internal/tui/chrome" + "charm.land/bubbles/v2/textarea" tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" @@ -28,14 +30,14 @@ type pendingOperation struct { } type PendingUserTurn struct { - Expired bool Handle *daemon.OperationHandle OperationID string BlockingReason string + Text string Images []daemon.ImageAttachment Pastes []string - Text string At int64 + Expired bool Queued bool } @@ -85,50 +87,66 @@ type burstRowsKey struct { // liveRowsKey is what the cached rows of the reply streaming in were // rendered for: the same transcript end as a burst, and the reply itself. type liveRowsKey struct { - burstRowsKey text string kind EntryKind + burstRowsKey } // liveFrame is the shortest wait between two renderings of a growing reply. const liveFrame = 120 * time.Millisecond type ChatModel struct { + transcript transcriptState + Renderer TranscriptRenderer + liveDrawn time.Time streamCtx context.Context Usage *daemon.Usage progressByCallID map[string]*daemon.ToolProgress - progressOrder []string eventChan chan streamDelivery - streamStopped bool - // Images and Pastes are what was pasted into the composer as markers. - Images promptImages - Pastes promptPastes // window is the context window of windowModel, read once per model so // the footer can say how full the context is. window *int client *daemon.ChatClient shellIDsByCommand map[string]string shellOutputLoading map[string]bool - shellSubmitting bool - btw btwState artifactConn *daemon.Connection openBrowser func(string) // termsFor is the terms warning a message on a profile still owes, if // any; terms holds termsHeld back until it is answered. - termsFor func(profile string) *daemon.Terms - terms *termsBox - termsHeld string - History *BoundedHistory - + termsFor func(profile string) *daemon.Terms + terms *termsBox + History *BoundedHistory // Selection coordinates use frameLines, the whole transcript as last // drawn, so a selection can extend beyond the viewport. dragAnchor *Point streamCancel context.CancelFunc windowModel *string + // moved is where the session went when it moved to another daemon; the + // banner above the composer offers to open it there. movedNote is the + // attach in flight or, with movedFailed, why the last one failed. + moved *daemon.SessionMoved + // movePending is the session's move waiting in its checklist; the + // banner's enter reopens it. + movePending *daemon.SessionMovePending + // liveRows is the reply streaming in: its finished blocks are framed + // once and only the block still growing is rendered again, so a draw + // costs what arrived rather than the length of the reply. While only + // its text grows it redraws at most once per liveInterval, a few times + // what the last rendering took; liveDue is a later redraw on its way. + // settled is each named entry's rows from the last rebuild while reading + // older history; see rebuildSettledLines. + settled map[settledKey]settledBlock + // editing is the queued message the composer is editing, held meanwhile. + editing *queuedEdit + pendingContinuations map[string]pendingOperation + // frame caches the pieces of the last frame; see frameCache in chat_view.go. + frame *frameCache + hostAuth *hostSignIn + liveRowsKey liveRowsKey // stretch is the phase run the status face animates. stretch stretch + termsHeld string SessionID string - Status daemon.AgentStatus AgentName string Workspace string Host string // the label of a remote workspace's host; "" when local @@ -138,21 +156,13 @@ type ChatModel struct { modelNameProfile string CyberAccess string Effort string - Fast bool Provider string CopyStatus string settledToolLabel string ThoughtProgressText string - Renderer TranscriptRenderer - // hostHome is the remote home ~ names in the header, once the host's // probe reported it for hostAsked, the workspace it was asked for. hostHome, hostAsked string - - // userRows are the settled rows where user messages start. - userRows []int - effortOptions []string - effortLevels []string effortDefault string effortDefaultSource string effortDefaultChoice string @@ -160,64 +170,46 @@ type ChatModel struct { // direnvAsk is the blocked .envrc the question above the composer offers // to allow; empty when nothing asks. direnvAsk string - // moved is where the session went when it moved to another daemon; the - // banner above the composer offers to open it there. movedNote is the - // attach in flight or, with movedFailed, why the last one failed. - moved *daemon.SessionMoved movedNote string - // movePending is the session's move waiting in its checklist; the - // banner's enter reopens it. - movePending *daemon.SessionMovePending // moveStatus is a move to another daemon whose box was put away. - moveStatus string - + moveStatus string + progressOrder []string + // Images and Pastes are what was pasted into the composer as markers. + Images promptImages + Pastes promptPastes + // userRows are the settled rows where user messages start. + userRows []int + effortOptions []string + effortLevels []string // burstRows is the rendered frame of the trailing run of compact entries. // Its key names every input the rows depend on, so a refresh that changes // nothing redraws nothing, and nothing can ask for a stale frame. - burstRows []string - // liveRows is the reply streaming in: its finished blocks are framed - // once and only the block still growing is rendered again, so a draw - // costs what arrived rather than the length of the reply. While only - // its text grows it redraws at most once per liveInterval, a few times - // what the last rendering took; liveDue is a later redraw on its way. - // settled is each named entry's rows from the last rebuild while reading - // older history; see rebuildSettledLines. - settled map[settledKey]settledBlock - liveRows []string - liveRowsKey liveRowsKey - liveDrawn time.Time - liveInterval time.Duration - liveDue bool - Notices Notices - settledLines []string - settledSpans []settledSpan - - pendingUsers []PendingUserTurn - // editing is the queued message the composer is editing, held meanwhile. - editing *queuedEdit - // queueHold is set while a hold on a queued message is in flight, so a - // second Up does not hold the same message twice. - queueHold bool - pendingContinuations map[string]pendingOperation - Glances []PageGlance + burstRows []string + liveRows []string + Notices Notices + settledLines []string + settledSpans []settledSpan + pendingUsers []PendingUserTurn + Glances []PageGlance + frameLines []string + Flags DisplayFlags + CommandMenu CommandMenuModel + Status daemon.AgentStatus + btw btwState + terminalClipboard terminalClipboardRead + Viewport pane + TextArea textarea.Model + burstRowsKey burstRowsKey + dragHead Point + liveInterval time.Duration // layoutSidebar is the sidebar width the last layout reserved. - layoutSidebar int - frameLines []string - // frame caches the pieces of the last frame; see frameCache in chat_view.go. - frame *frameCache - CommandMenu CommandMenuModel - Viewport pane - - transcript transcriptState - TextArea textarea.Model - burstRowsKey burstRowsKey - dragHead Point + layoutSidebar int effortSelected int Generation int64 - terminalClipboard terminalClipboardRead copyStatusRevision uint64 burstEpoch int ProgressFrame int + progressAt int64 // Unix milliseconds at the most recent animation tick. Width int // moodSeed selects the status-face animation for the current stretch. moodSeed int64 @@ -227,16 +219,21 @@ type ChatModel struct { statusRevision uint64 statusPoll uint64 scrollOffset int - - scrollLimit int - dragDir int - dragCtrl bool - dragGen int + scrollLimit int + dragDir int + dragGen int // olderBefore is the first transcript row carried by the reset or last older page. olderBefore int64 // settledOffset counts notice rows above the settled transcript. settledOffset int - Flags DisplayFlags + streamStopped bool + shellSubmitting bool + Fast bool + liveDue bool + // queueHold is set while a hold on a queued message is in flight, so a + // second Up does not hold the same message twice. + queueHold bool + dragCtrl bool Follow bool TurnFailed bool Stopping bool @@ -247,14 +244,12 @@ type ChatModel struct { blurred bool // rebuilding defers trimming until a re-render has placed the reading position. rebuilding bool - // olderMore reports whether transcript rows precede olderBefore. olderMore bool // loadingOlder prevents overlapping history fetches. loadingOlder bool isSending bool interruptDeferred bool - hostAuth *hostSignIn sentHere bool movedFailed bool // graphemes says the terminal measures grapheme clusters (mode 2027), @@ -269,23 +264,23 @@ func NewChatModel(session *daemon.Session, client *daemon.ChatClient) ChatModel } ta := textarea.New() ta.Placeholder = "" - ta.Prompt = promptMark + ta.Prompt = chrome.PromptMark ta.CharLimit = 0 ta.ShowLineNumbers = false - ta.SetPromptFunc(promptMarkWidth, func(info textarea.PromptInfo) string { + ta.SetPromptFunc(chrome.PromptMarkWidth, func(info textarea.PromptInfo) string { if info.LineNumber == 0 { - return promptMark + return chrome.PromptMark } - return strings.Repeat(" ", promptMarkWidth) + return strings.Repeat(" ", chrome.PromptMarkWidth) }) ta.KeyMap.InsertNewline.SetKeys("enter", "ctrl+m", "alt+enter", "shift+enter") ta.KeyMap.WordBackward.SetKeys("alt+left", "alt+b", "ctrl+left") ta.KeyMap.WordForward.SetKeys("alt+right", "alt+f", "ctrl+right") ta.SetHeight(6) st := ta.Styles() - st.Focused.Prompt, st.Blurred.Prompt = DefaultStyles.Prompt, DefaultStyles.Prompt + st.Focused.Prompt, st.Blurred.Prompt = chrome.DefaultStyles.Prompt, chrome.DefaultStyles.Prompt st.Focused.CursorLine, st.Blurred.CursorLine = lipgloss.NewStyle(), lipgloss.NewStyle() - st.Focused.Placeholder, st.Blurred.Placeholder = DefaultStyles.Faint, DefaultStyles.Faint + st.Focused.Placeholder, st.Blurred.Placeholder = chrome.DefaultStyles.Faint, chrome.DefaultStyles.Faint st.Cursor.Blink, st.Cursor.Color = false, nil ta.SetStyles(st) ta.Focus() @@ -552,6 +547,7 @@ func (m ChatModel) update(msg tea.Msg) (ChatModel, tea.Cmd) { } // the face lives in the status line, so the transcript stays as it is m.ProgressFrame++ + m.progressAt = msg.At.UnixMilli() return m, m.progressTickCmd() case ChatStreamResultMsg: diff --git a/cli/internal/tui/chat_btw.go b/cli/internal/tui/chat_btw.go index 85509f405..a8c279a8d 100644 --- a/cli/internal/tui/chat_btw.go +++ b/cli/internal/tui/chat_btw.go @@ -7,6 +7,8 @@ import ( "strings" "albedo/cli/internal/daemon" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -333,9 +335,9 @@ func (m *ChatModel) btwPanelView(width, height int) []string { head = append(head, line) } if status != "" && (m.btw.exchange == nil || m.btw.exchange.Status != "answered") { - style := DefaultStyles.Faint.Render + style := chrome.DefaultStyles.Faint.Render if m.btw.exchange != nil && m.btw.exchange.Status == "failed" { - style = DefaultStyles.Error.Render + style = chrome.DefaultStyles.Error.Render } for line := range strings.SplitSeq(ansi.Wrap(status, inner, " "), "\n") { head = append(head, style(line)) @@ -343,7 +345,7 @@ func (m *ChatModel) btwPanelView(width, height int) []string { } if m.btw.continueErr != "" { for line := range strings.SplitSeq(ansi.Wrap(m.btw.continueErr, inner, " "), "\n") { - head = append(head, DefaultStyles.Error.Render(line)) + head = append(head, chrome.DefaultStyles.Error.Render(line)) } } @@ -359,7 +361,7 @@ func (m *ChatModel) btwPanelView(width, height int) []string { body = append(body, answer[m.btw.scroll:min(len(answer), m.btw.scroll+visible)]...) } body = append(body, "") - body = append(body, strings.Repeat(" ", max(0, inner-ansi.StringWidth(hint)))+DefaultStyles.Faint.Render(hint)) + body = append(body, strings.Repeat(" ", max(0, inner-ansi.StringWidth(hint)))+chrome.DefaultStyles.Faint.Render(hint)) return cdFrame("/btw", body, outer) } diff --git a/cli/internal/tui/chat_direnv.go b/cli/internal/tui/chat_direnv.go index eccef1f00..a356c898d 100644 --- a/cli/internal/tui/chat_direnv.go +++ b/cli/internal/tui/chat_direnv.go @@ -10,6 +10,8 @@ import ( "albedo/cli/internal/daemon" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -131,12 +133,12 @@ func (m ChatModel) direnvRows(width int) []string { return nil } question := "this folder's .envrc is blocked · direnv allow it for run() jobs?" - keys := keyHints(hint{"y", "allow"}, hint{"n", "not now"}) + keys := chrome.KeyHints(chrome.Hint{Key: "y", Does: "allow"}, chrome.Hint{Key: "n", Does: "not now"}) if ansi.StringWidth(question)+3+ansi.StringWidth(keys) <= width { - return []string{DefaultStyles.Warning.Render(question) + " " + keys} + return []string{chrome.DefaultStyles.Warning.Render(question) + " " + keys} } return []string{ - DefaultStyles.Warning.Render(ansi.Truncate(question, width, "…")), + chrome.DefaultStyles.Warning.Render(ansi.Truncate(question, width, "…")), ansi.Truncate(keys, width, "…"), } } diff --git a/cli/internal/tui/chat_footer.go b/cli/internal/tui/chat_footer.go index aae7746d2..1255f24fb 100644 --- a/cli/internal/tui/chat_footer.go +++ b/cli/internal/tui/chat_footer.go @@ -10,6 +10,8 @@ import ( "strings" "time" + "albedo/cli/internal/tui/chrome" + "charm.land/lipgloss/v2" "github.com/charmbracelet/x/ansi" ) @@ -157,14 +159,14 @@ func (m ChatModel) glanceRows(g PageGlance, limit int) []string { if len(g.Rows) > shown { shown = limit - 2 } - rows := []string{DefaultStyles.Faint.Render(fmt.Sprintf("%s · %d", g.Title, len(g.Rows)))} + rows := []string{chrome.DefaultStyles.Faint.Render(fmt.Sprintf("%s · %d", g.Title, len(g.Rows)))} for _, item := range g.Rows[:shown] { - mark, style := "○", DefaultStyles.Faint + mark, style := "○", chrome.DefaultStyles.Faint switch item.Tone { case ToneActive: - mark, style = "●", DefaultStyles.Success + mark, style = "●", chrome.DefaultStyles.Success case ToneWarning: - mark, style = "!", DefaultStyles.Warning + mark, style = "!", chrome.DefaultStyles.Warning case ToneMuted: mark = "✓" } @@ -176,7 +178,7 @@ func (m ChatModel) glanceRows(g PageGlance, limit int) []string { rows = append(rows, style.Render(mark)+" "+ansi.Truncate(label, max(1, m.sidebarWidth()-2), "…")) } if shown < len(g.Rows) { - rows = append(rows, DefaultStyles.Faint.Render(fmt.Sprintf("+%d more", len(g.Rows)-shown))) + rows = append(rows, chrome.DefaultStyles.Faint.Render(fmt.Sprintf("+%d more", len(g.Rows)-shown))) } return rows } @@ -184,45 +186,45 @@ func (m ChatModel) glanceRows(g PageGlance, limit int) []string { func (m ChatModel) renderFooter() string { width := m.chatWidth() right, compact := m.contextStat() - commands := hint{"/", "commands"} - sessions := hint{"←", "sessions"} + commands := chrome.Hint{Key: "/", Does: "commands"} + sessions := chrome.Hint{Key: "←", Does: "sessions"} candidates := []struct { right string - left []hint + left []chrome.Hint }{ - {left: []hint{sessions, commands, {"shift+↑↓", "your messages"}, {"ctrl+j", "diffs"}, {"ctrl+o", "agents"}}, right: right}, - {left: []hint{sessions, commands, {"ctrl+j", "diffs"}, {"ctrl+o", "agents"}}, right: right}, - {left: []hint{sessions, commands, {"ctrl+o", "agents"}}, right: compact}, - {left: []hint{sessions, commands}, right: compact}, - {left: []hint{commands, {"ctrl+j", "diffs"}}, right: compact}, - {left: []hint{commands}, right: compact}, - {left: []hint{{"/", ""}}, right: compact}, + {left: []chrome.Hint{sessions, commands, {Key: "shift+↑↓", Does: "your messages"}, {Key: "ctrl+j", Does: "diffs"}, {Key: "ctrl+o", Does: "agents"}}, right: right}, + {left: []chrome.Hint{sessions, commands, {Key: "ctrl+j", Does: "diffs"}, {Key: "ctrl+o", Does: "agents"}}, right: right}, + {left: []chrome.Hint{sessions, commands, {Key: "ctrl+o", Does: "agents"}}, right: compact}, + {left: []chrome.Hint{sessions, commands}, right: compact}, + {left: []chrome.Hint{commands, {Key: "ctrl+j", Does: "diffs"}}, right: compact}, + {left: []chrome.Hint{commands}, right: compact}, + {left: []chrome.Hint{{Key: "/", Does: ""}}, right: compact}, } if slices.ContainsFunc(m.History.Entries(), func(e HistoryEntry) bool { return e.Kind == EntryShell }) { candidates = append([]struct { right string - left []hint + left []chrome.Hint }{ - {left: []hint{sessions, commands, {"ctrl+shift+o", "shell output"}, {"ctrl+shift+x", "stop shell"}}, right: right}, - {left: []hint{commands, {"ctrl+shift+o", "output"}, {"ctrl+shift+x", "stop"}}, right: compact}, - {left: []hint{commands, {"ctrl+shift+o", "output"}}, right: compact}, + {left: []chrome.Hint{sessions, commands, {Key: "ctrl+shift+o", Does: "shell output"}, {Key: "ctrl+shift+x", Does: "stop shell"}}, right: right}, + {left: []chrome.Hint{commands, {Key: "ctrl+shift+o", Does: "output"}, {Key: "ctrl+shift+x", Does: "stop"}}, right: compact}, + {left: []chrome.Hint{commands, {Key: "ctrl+shift+o", Does: "output"}}, right: compact}, }, candidates...) } if m.editing != nil { candidates = append([]struct { right string - left []hint + left []chrome.Hint }{ - {left: []hint{{"enter", "save edit"}, {"esc", "cancel edit"}}, right: compact}, + {left: []chrome.Hint{{Key: "enter", Does: "save edit"}, {Key: "esc", Does: "cancel edit"}}, right: compact}, }, candidates...) } for _, c := range candidates { - left := keyHints(c.left...) + left := chrome.KeyHints(c.left...) if gap := width - lipgloss.Width(left) - lipgloss.Width(c.right); gap > 0 { return left + strings.Repeat(" ", gap) + c.right } } - return ansi.Truncate(keyHints(commands), width, "…") + return ansi.Truncate(chrome.KeyHints(commands), width, "…") } // contextStat is how much of the prompt was read from cache, fading as the @@ -237,10 +239,10 @@ func (m ChatModel) contextStat() (full, short string) { // total answers what the work has cost. charge := "" if usage != nil && usage.Spent != nil { - charge = DefaultStyles.Faint.Render(" · " + daemon.FormatCharge(usage.Spent.Usd)) + charge = chrome.DefaultStyles.Faint.Render(" · " + daemon.FormatCharge(usage.Spent.Usd)) } if usage == nil || usage.Model != "" && m.Model != "" && usage.Model != m.Model { - return DefaultStyles.Faint.Render("—/— cached") + charge, DefaultStyles.Faint.Render("—/—") + charge + return chrome.DefaultStyles.Faint.Render("—/— cached") + charge, chrome.DefaultStyles.Faint.Render("—/—") + charge } count := func(n *int) string { if n == nil || *n < 0 { @@ -248,20 +250,20 @@ func (m ChatModel) contextStat() (full, short string) { } return shortCount(*n) } - ratio := DefaultStyles.Muted.Render(count(cachedNow(usage, time.Now())) + "/" + count(usage.PromptTokens)) - fullRatio, shortRatio := ratio+DefaultStyles.Faint.Render(" cached"), ratio + ratio := chrome.DefaultStyles.Muted.Render(count(cachedNow(usage, time.Now())) + "/" + count(usage.PromptTokens)) + fullRatio, shortRatio := ratio+chrome.DefaultStyles.Faint.Render(" cached"), ratio if usage.Size != nil { // No call measured this request, so there is no cache to show: show // what the size is made of instead. sizeFull, sizeShort := sizeStat(*usage.Size) - fullRatio, shortRatio = DefaultStyles.Muted.Render(sizeFull), DefaultStyles.Muted.Render(sizeShort) + fullRatio, shortRatio = chrome.DefaultStyles.Muted.Render(sizeFull), chrome.DefaultStyles.Muted.Render(sizeShort) } share := "" if total := contextTokens(usage); total != nil && m.window != nil && m.windowModel != nil && *m.windowModel == usage.Model { pct := int(math.Round(100 * float64(*total) / float64(*m.window))) - style := DefaultStyles.Faint + style := chrome.DefaultStyles.Faint if pct >= 90 { - style = DefaultStyles.Warning + style = chrome.DefaultStyles.Warning } share = " " + style.Render(fmt.Sprintf("(%d%%)", pct)) } diff --git a/cli/internal/tui/chat_history.go b/cli/internal/tui/chat_history.go index b6813585e..665550f81 100644 --- a/cli/internal/tui/chat_history.go +++ b/cli/internal/tui/chat_history.go @@ -10,6 +10,8 @@ import ( "strings" "time" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -237,11 +239,11 @@ func (m ChatModel) headerLines() []string { var line string switch { case m.loadingOlder: - line = DefaultStyles.Faint.Render("↑ loading earlier messages…") + line = chrome.DefaultStyles.Faint.Render("↑ loading earlier messages…") case m.hasOlder(): - line = DefaultStyles.Faint.Render("↑ earlier messages load as you scroll up") + line = chrome.DefaultStyles.Faint.Render("↑ earlier messages load as you scroll up") case m.History.TruncationNotice() != "": - line = DefaultStyles.Warning.Render(m.History.TruncationNotice()) + line = chrome.DefaultStyles.Warning.Render(m.History.TruncationNotice()) default: return nil } @@ -280,12 +282,12 @@ type settledKey struct { burstFirst string burstLast string prior prior + flags DisplayFlags burst int epoch int width int follows lane burstFollows lane - flags DisplayFlags separated bool burstSeparated bool } @@ -517,7 +519,7 @@ func (m *ChatModel) refreshViewportContent() int { action = m.renderProgress() case m.ThoughtProgressText != "" && !m.Flags.Thinking: width := max(1, m.Renderer.BodyWidth-railWidth) - action = markChrome + DefaultStyles.Faint.Render(ansi.Truncate(m.ThoughtProgressText, width, "…")) + action = markChrome + chrome.DefaultStyles.Faint.Render(ansi.Truncate(m.ThoughtProgressText, width, "…")) } if action != "" { if len(allLines) > 0 && !stacks { @@ -567,7 +569,7 @@ func (m *ChatModel) liveBlock(entry HistoryEntry) []string { start := time.Now() switch { case !grows || previous.burstRowsKey != key.burstRowsKey || previous.kind != key.kind || - live.ink != transcriptInk || !strings.HasPrefix(key.text, previous.text): + live.ink != chrome.CurrentInk || !strings.HasPrefix(key.text, previous.text): // a new reply, one whose transcript end or palette changed under it, or // text that is not this reply growing live.reset(m.Renderer, m.History.Entries(), entry, m.Flags) @@ -596,14 +598,14 @@ type liveRender struct { rows []string shown []string line string - ink ink + ink chrome.Ink blocks growingMarkdown } // reset renders the entry whole, which is what a new reply and one whose // rendering changed under it need. func (l *liveRender) reset(r TranscriptRenderer, before []HistoryEntry, entry HistoryEntry, flags DisplayFlags) { - l.ink, l.blocks = transcriptInk, growingMarkdown{} + l.ink, l.blocks = chrome.CurrentInk, growingMarkdown{} l.rows, l.line = r.LiveHead(before, entry, flags), "" l.shown = l.rows if !l.grow(r, entry, flags) { @@ -793,7 +795,7 @@ func (m *ChatModel) showOlder(msg ChatOlderLoadedMsg) ChatModel { events = append(events, event) } } - older := replayTranscript(events, m.AgentName) + older, tail := replayTranscript(events, m.AgentName) for i := range older { if Compact(older[i], m.Flags) { facts := factsOf(older[i]) @@ -801,6 +803,16 @@ func (m *ChatModel) showOlder(msg ChatOlderLoadedMsg) ChatModel { } } anchor := m.captureAnchor() + if tail != nil { + if inserted := m.joinOlderTurn(tail); inserted >= 0 { + if anchor.entry >= inserted { + anchor.entry++ + } + if anchor.burst >= inserted { + anchor.burst++ + } + } + } beforeLen := m.History.Len() m.History.Prepend(older) prepended := m.History.Len() - beforeLen @@ -811,3 +823,44 @@ func (m *ChatModel) showOlder(msg ChatOlderLoadedMsg) ChatModel { m.refreshViewportContent() return *m } + +// The fetched page and the retained history can meet anywhere in a turn. +// Merge only that turn, leaving all later live timings and copy targets intact. +func (m *ChatModel) joinOlderTurn(older *openTurn) int { + retained := m.History.Entries() + tools := older.tools + for i := range retained { + e := &retained[i] + switch { + case e.Kind == EntryTool: + tools++ + case e.Kind == EntryTurnEnd: + e.ElapsedMs = max(e.ElapsedMs, e.Timestamp-older.start) + e.Mood = outcome(e.Mood == moodFailed, e.Mood == moodStopped, e.ElapsedMs) + e.Tools = max(e.Tools, tools) + return -1 + case e.Kind == EntryUser && e.Source.FromPerson(): + return m.insertOlderSignoff(i, older) + } + } + if current := m.transcript.turn; current != nil { + current.start = min(older.start, current.start) + current.last = max(older.last, current.last) + current.answered = current.answered || older.answered + current.tools = max(current.tools, tools) + } else if m.Status.Idle { + return m.insertOlderSignoff(m.History.Len(), older) + } else { + m.transcript.turn = older + } + return -1 +} + +func (m *ChatModel) insertOlderSignoff(at int, turn *openTurn) int { + state := transcriptState{turn: turn} + for _, end := range state.closeTurn(false) { + m.History.insert(at, end) + return at + } + return -1 +} diff --git a/cli/internal/tui/chat_messages.go b/cli/internal/tui/chat_messages.go index d75a2ec59..ddd0ef3cd 100644 --- a/cli/internal/tui/chat_messages.go +++ b/cli/internal/tui/chat_messages.go @@ -2,6 +2,7 @@ package tui import ( "albedo/cli/internal/daemon" + "time" ) type ChatBackToSessionsMsg struct{} @@ -19,9 +20,9 @@ type ChatEditorFinishedMsg struct { // FileOpenResultMsg is sent after attempting to open a file in an external editor. type FileOpenResultMsg struct { + Err error SessionID string Target FileTarget - Err error } // ChatOlderLoadedMsg carries a page of history from before what is shown. @@ -62,8 +63,8 @@ type ChatExecuteCommandMsg struct { type ChatShellSubmitMsg struct { Err error - Command daemon.ShellCommand SessionID, OriginalInput string + Command daemon.ShellCommand Generation int64 } @@ -76,8 +77,8 @@ type ChatShellOutputMsg struct { type ChatShellCancelMsg struct { Err error - Command daemon.ShellCommand SessionID string + Command daemon.ShellCommand Generation int64 } @@ -94,6 +95,7 @@ type ChatLiveDrawMsg struct { } type ChatProgressTickMsg struct { + At time.Time SessionID string Generation int64 } @@ -107,8 +109,8 @@ type ChatClearCopyStatusMsg struct { type ChatStatusMsg struct { Err error Status *daemon.AgentStatus - Glances []PageGlance SessionID string + Glances []PageGlance Generation int64 Revision uint64 } @@ -153,9 +155,9 @@ type ChatStatusPollMsg struct { // ChatStreamResultMsg follows all accepted events from the same subscription. type ChatStreamResultMsg struct { + Err error SessionID string Generation int64 - Err error Recovering bool } @@ -171,34 +173,34 @@ type ChatStreamClosedMsg struct { } type ChatOperationResolvedMsg struct { - SessionID string - Generation int64 - Handle *daemon.OperationHandle Receipt daemon.InputReceipt Err error + Handle *daemon.OperationHandle + SessionID string + Generation int64 } type ChatTurnSentMsg struct { + Err error Handle *daemon.OperationHandle OperationID string - Err error - Images []daemon.ImageAttachment - Pastes []string SessionID string Prompt string + Images []daemon.ImageAttachment + Pastes []string Generation int64 + AcceptanceOrder int64 Continue bool OK bool Queued bool - AcceptanceOrder int64 } type ChatInterruptMsg struct { Err error SessionID string + Cancelled []string // queued inputs the daemon cancelled with the run Generation int64 Interrupted bool - Cancelled []string // queued inputs the daemon cancelled with the run } // ChatOpenFolderPickerMsg asks for the folder picker; Retry is the turn a @@ -206,7 +208,9 @@ type ChatInterruptMsg struct { type ChatOpenFolderPickerMsg struct{ Retry *WorkspaceRetry } type ChatOperationPollMsg struct { + Handle *daemon.OperationHandle SessionID string Generation int64 - Handle *daemon.OperationHandle } + +type ChatOpenAgentsMsg struct{} diff --git a/cli/internal/tui/chat_moved.go b/cli/internal/tui/chat_moved.go index 95d5926aa..4c2905bce 100644 --- a/cli/internal/tui/chat_moved.go +++ b/cli/internal/tui/chat_moved.go @@ -3,6 +3,8 @@ package tui import ( "strings" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -49,25 +51,25 @@ func (m ChatModel) movedRows(width int) []string { if m.moved.Workspace != "" { where += " · " + m.moved.Workspace } - keys = keyHints(hint{"enter", "open it there"}) + keys = chrome.KeyHints(chrome.Hint{Key: "enter", Does: "open it there"}) if m.movedNote != "" && !m.movedFailed { - keys = DefaultStyles.Faint.Render(m.movedNote) + keys = chrome.DefaultStyles.Faint.Render(m.movedNote) } case m.movePending != nil: where = "moving to " + m.movePending.Host + " · checklist pending" - keys = keyHints(hint{"enter", "open the checklist"}) + keys = chrome.KeyHints(chrome.Hint{Key: "enter", Does: "open the checklist"}) default: return nil } var rows []string if ansi.StringWidth(where)+3+ansi.StringWidth(keys) <= width { - rows = []string{DefaultStyles.Muted.Render(where) + " " + keys} + rows = []string{chrome.DefaultStyles.Muted.Render(where) + " " + keys} } else { - rows = []string{DefaultStyles.Muted.Render(ansi.Truncate(where, width, "…")), ansi.Truncate(keys, width, "…")} + rows = []string{chrome.DefaultStyles.Muted.Render(ansi.Truncate(where, width, "…")), ansi.Truncate(keys, width, "…")} } if m.movedFailed { for line := range strings.SplitSeq(ansi.Wrap(m.movedNote, width, " "), "\n") { - rows = append(rows, DefaultStyles.Error.Render(line)) + rows = append(rows, chrome.DefaultStyles.Error.Render(line)) } } return rows diff --git a/cli/internal/tui/chat_queue_edit.go b/cli/internal/tui/chat_queue_edit.go index 6f1e52901..0d028aaf3 100644 --- a/cli/internal/tui/chat_queue_edit.go +++ b/cli/internal/tui/chat_queue_edit.go @@ -7,6 +7,8 @@ import ( "strings" "time" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -327,7 +329,7 @@ func (m ChatModel) editRows(width int) []string { if m.editing.saving { line = "saving the edit…" } - return []string{DefaultStyles.Warning.Render(ansi.Truncate(line, width, "…"))} + return []string{chrome.DefaultStyles.Warning.Render(ansi.Truncate(line, width, "…"))} } // renewLater renews the hold a third of its lease from now. diff --git a/cli/internal/tui/chat_queue_edit_test.go b/cli/internal/tui/chat_queue_edit_test.go index eadbf2202..0840bc8a3 100644 --- a/cli/internal/tui/chat_queue_edit_test.go +++ b/cli/internal/tui/chat_queue_edit_test.go @@ -1,9 +1,10 @@ package tui import ( - tea "charm.land/bubbletea/v2" "testing" + tea "charm.land/bubbletea/v2" + "albedo/cli/internal/daemon" ) @@ -19,7 +20,7 @@ func heldMsg(m ChatModel, id string) ChatQueueHeldMsg { // without its attachments. func TestEditLoadsQueuedMessageAndKeepsTheDraft(t *testing.T) { m := newTestChatModel(t, &daemon.Session{ID: "s"}) - image := daemon.ImageAttachment{ImageMetadata: daemon.ImageMetadata{MimeType: "image/png"}} + image := daemon.ImageAttachment{MimeType: "image/png"} m.TextArea.SetValue("my draft") m.pendingUsers = []PendingUserTurn{queuedPending("a", "first"), queuedPending("b", "second [Image #1]")} m.pendingUsers[1].Images = []daemon.ImageAttachment{image} @@ -157,8 +158,8 @@ func TestHoldAnsweredAsReadChangesNothing(t *testing.T) { // Catches a joined draft that renumbers attachments twice, so one composer // marker names the wrong image. func TestJoinDraftsNumbersAttachmentsOnce(t *testing.T) { - one := daemon.ImageAttachment{ImageMetadata: daemon.ImageMetadata{MimeType: "image/png", Width: 1}} - two := daemon.ImageAttachment{ImageMetadata: daemon.ImageMetadata{MimeType: "image/png", Width: 2}} + one := daemon.ImageAttachment{MimeType: "image/png", Width: 1} + two := daemon.ImageAttachment{MimeType: "image/png", Width: 2} var first, second editDraft first.text = first.images.add(pastedImage{ImageAttachment: one}) second.text = second.images.add(pastedImage{ImageAttachment: two}) diff --git a/cli/internal/tui/chat_shell.go b/cli/internal/tui/chat_shell.go index 5a5012b2b..5b46e1255 100644 --- a/cli/internal/tui/chat_shell.go +++ b/cli/internal/tui/chat_shell.go @@ -8,6 +8,7 @@ import ( "strings" "albedo/cli/internal/daemon" + tea "charm.land/bubbletea/v2" ) diff --git a/cli/internal/tui/chat_shell_test.go b/cli/internal/tui/chat_shell_test.go index 0fd0c2410..62debc005 100644 --- a/cli/internal/tui/chat_shell_test.go +++ b/cli/internal/tui/chat_shell_test.go @@ -10,6 +10,7 @@ import ( "albedo/cli/internal/daemon" "albedo/cli/internal/daemon/protocol" + "github.com/charmbracelet/x/ansi" ) diff --git a/cli/internal/tui/chat_stream.go b/cli/internal/tui/chat_stream.go index 439b5d880..0abdafb84 100644 --- a/cli/internal/tui/chat_stream.go +++ b/cli/internal/tui/chat_stream.go @@ -149,6 +149,11 @@ func (m *ChatModel) handleStreamEvent(evt daemon.StreamEvent) { } watchedThought := !m.transcript.thinkingSince.IsZero() entries := m.transcript.apply(evt, m.AgentName) + // The snapshot's usage summary follows its complete history. An idle + // snapshot has no live completion event left to close its last reply. + if evt.EndsIdleHistory { + entries = append(entries, m.transcript.closeTurn(false)...) + } if retired { m.replaceHistory(anchor, func() { for _, entry := range entries { diff --git a/cli/internal/tui/chat_subscription.go b/cli/internal/tui/chat_subscription.go index 9de9be707..583ed73cc 100644 --- a/cli/internal/tui/chat_subscription.go +++ b/cli/internal/tui/chat_subscription.go @@ -31,7 +31,7 @@ func (m *ChatModel) startAnimation() tea.Cmd { func (m ChatModel) progressTickCmd() tea.Cmd { id, generation := m.SessionID, m.Generation - return tea.Tick(faceInterval, func(time.Time) tea.Msg { return ChatProgressTickMsg{SessionID: id, Generation: generation} }) + return tea.Tick(faceInterval, func(at time.Time) tea.Msg { return ChatProgressTickMsg{SessionID: id, Generation: generation, At: at} }) } // onlyGrew is whether an event did nothing but lengthen the reply streaming diff --git a/cli/internal/tui/chat_view.go b/cli/internal/tui/chat_view.go index 05c721bc5..2b521451c 100644 --- a/cli/internal/tui/chat_view.go +++ b/cli/internal/tui/chat_view.go @@ -2,6 +2,7 @@ package tui import ( "albedo/cli/internal/daemon" + "albedo/cli/internal/terminalui" "cmp" "fmt" "path/filepath" @@ -9,6 +10,8 @@ import ( "strings" "time" + "albedo/cli/internal/tui/chrome" + "charm.land/lipgloss/v2" "github.com/charmbracelet/x/ansi" ) @@ -96,7 +99,7 @@ func pythonSourceLine(preview *daemon.ToolCodePreview) string { if preview == nil { return "" } - return firstLine(preview.Text) + return chrome.FirstLine(preview.Text) } // renderProgress holds the last tool action in one row; a call still being @@ -117,14 +120,14 @@ func (m ChatModel) renderProgress() string { } } } - return markChrome + DefaultStyles.Faint.Render(ansi.Truncate(row, width, "…")) + return markChrome + chrome.DefaultStyles.Faint.Render(ansi.Truncate(row, width, "…")) } // renderThought follows the newest line while the thought streams. func (m ChatModel) renderThought() string { header := cmp.Or(thinkingLine(m.transcript.activeText), "thinking") width := max(1, m.Renderer.BodyWidth-railWidth) - return markChrome + DefaultStyles.Faint.Render(ansi.Truncate(header+"…", width, "…")) + return markChrome + chrome.DefaultStyles.Faint.Render(ansi.Truncate(header+"…", width, "…")) } func (m ChatModel) statusLine() string { @@ -285,11 +288,11 @@ func (m ChatModel) header(width int) string { // a remote workspace's host stays whole in every layout lead := "" if host == "" { - workspace = homePath(workspace) + workspace = chrome.HomePath(workspace) } else { host = cmp.Or(m.Host, host) lead = "● " + host + ":" - workspace = scpRelative(underHome(workspace, m.hostHome)) + workspace = chrome.ScpRelative(chrome.UnderHome(workspace, m.hostHome)) } model := m.displayModelName() if m.CyberAccess == "daybreak_blue" { @@ -306,7 +309,7 @@ func (m ChatModel) header(width int) string { model += " ϟ" } counts := m.glanceCounts() - folds := pathFolds(workspace) + folds := chrome.PathFolds(workspace) type layout struct { place string counts int @@ -330,16 +333,16 @@ func (m ChatModel) header(width int) string { if lipgloss.Width(left)+lipgloss.Width(right)+l.rule+2 > width { continue } - place := DefaultStyles.Muted.Render(l.place) + place := chrome.DefaultStyles.Muted.Render(l.place) if host != "" { - place = m.hostSegment(host) + DefaultStyles.Muted.Render(":"+l.place) + place = m.hostSegment(host) + chrome.DefaultStyles.Muted.Render(":"+l.place) } if l.brand { - return titleRule(width, brand(m.AgentName)+DefaultStyles.Faint.Render(" on ")+place, DefaultStyles.Faint.Render(right)) + return chrome.TitleRule(width, chrome.Brand(m.AgentName)+chrome.DefaultStyles.Faint.Render(" on ")+place, chrome.DefaultStyles.Faint.Render(right)) } - return titleRule(width, place, DefaultStyles.Faint.Render(right)) + return chrome.TitleRule(width, place, chrome.DefaultStyles.Faint.Render(right)) } - return DefaultStyles.Faint.Render(ansi.Truncate(model, width, "…")) + return chrome.DefaultStyles.Faint.Render(ansi.Truncate(model, width, "…")) } // hostSegment is the header's host in its own color once the kernel there is @@ -348,11 +351,11 @@ func (m ChatModel) header(width int) string { func (m ChatModel) hostSegment(host string) string { switch m.Status.KernelLink { case "booting", "reattaching", "busy": - return DefaultStyles.Faint.Render("◌ " + host) + return chrome.DefaultStyles.Faint.Render("◌ " + host) case "lost": - return DefaultStyles.Error.Render("○ " + host) + return chrome.DefaultStyles.Error.Render("○ " + host) } - return hostStyle(host).Render("● " + host) + return chrome.HostStyle(host).Render("● " + host) } // reaching is the remote host a booting or reattaching kernel is on. @@ -373,12 +376,13 @@ func (m *ChatModel) View() string { m.frame = &frameCache{} } width := m.chatWidth() - pad := strings.Repeat(" ", chatMargin) - rows := m.frame.scratch[:0] - rows = append(rows, m.header(width), "") - rows = append(rows, m.noticeRows(width)...) - - rows = append(rows, m.body()...) + page := terminalui.Conversation{ + Heading: m.header(width), + Notices: m.noticeRows(width), + Messages: m.body(), + Rule: chrome.DefaultStyles.Decor.Render(strings.Repeat("─", width)), + Footer: m.renderFooter(), + } // one row: a job's command may span lines, or run past the width status := ansi.Truncate(oneLine(m.statusLine()), width, "…") // the face trails the text, so its frames never move anything @@ -386,11 +390,15 @@ func (m *ChatModel) View() string { face := m.phaseMood().frame(m.moodSeed, m.ProgressFrame, m.Fast) if host := m.reaching(); host != "" { face = connectingFace(host, m.ProgressFrame) // the picker's face for this host + } else if turn := m.transcript.turn; turn != nil && m.Status.Running && m.Status.Compaction == nil { + face = formatElapsed(max(0, m.progressAt-turn.start)) + " " + face } - if m.Width > 0 { - status = ansi.Truncate(status, max(1, m.chatWidth()-ansi.StringWidth(face)-1), "…") + face = ansi.Truncate(face, width, "…") + status = ansi.Truncate(status, max(0, width-ansi.StringWidth(face)-1), "…") + if status != "" { + status = chrome.DefaultStyles.Faint.Render(status) + " " } - status = DefaultStyles.Faint.Render(status) + " " + DefaultStyles.Agent.Render(face) + status += chrome.DefaultStyles.Agent.Render(face) } if !m.Follow { status = fmt.Sprintf("history · %d rows below · pgdn", max(0, m.scrollLimit-m.scrollOffset)) @@ -398,37 +406,24 @@ func (m *ChatModel) View() string { if m.CopyStatus != "" { status = m.CopyStatus } - statusStyle := DefaultStyles.Faint + statusStyle := chrome.DefaultStyles.Faint if m.TurnFailed || m.Notices.HasError() { - statusStyle = DefaultStyles.Error - } - rows = append(rows, statusStyle.Render(status)) - if len(m.effortOptions) == 0 { - rows = append(rows, m.chipStrip(width)...) - rows = append(rows, m.direnvRows(width)...) - rows = append(rows, m.movedRows(width)...) + statusStyle = chrome.DefaultStyles.Error } - rows = append(rows, DefaultStyles.Decor.Render(strings.Repeat("─", width))) + page.Status = statusStyle.Render(status) if len(m.effortOptions) > 0 { - rows = append(rows, "", DefaultStyles.Bold.Render(ansi.Truncate("Reasoning · "+reasoningValue(m.selectedEffort(), m.effortDefault, m.effortProfile), width, "")), DefaultStyles.Faint.Render(ansi.Truncate(m.effortSelectorDescription(), width, "…")), m.effortSelectorView(), DefaultStyles.Faint.Render(ansi.Truncate(m.effortSelectorHint(), width, ""))) + page.Input = []string{"", chrome.DefaultStyles.Bold.Render(ansi.Truncate("Reasoning · "+reasoningValue(m.selectedEffort(), m.effortDefault, m.effortProfile), width, "")), chrome.DefaultStyles.Faint.Render(ansi.Truncate(m.effortSelectorDescription(), width, "…")), m.effortSelectorView(), chrome.DefaultStyles.Faint.Render(ansi.Truncate(m.effortSelectorHint(), width, ""))} } else { - rows = append(rows, m.editRows(width)...) - rows = append(rows, m.composer()...) + page.Accessories = append(page.Accessories, m.chipStrip(width)...) + page.Accessories = append(page.Accessories, m.direnvRows(width)...) + page.Accessories = append(page.Accessories, m.movedRows(width)...) + page.Input = append(page.Input, m.editRows(width)...) + page.Input = append(page.Input, m.composer()...) if menu := m.CommandMenu.View(m.TextArea.Value(), m.composerCursor(), width); menu != "" { - rows = append(rows, strings.Split(strings.TrimSuffix(menu, "\n"), "\n")...) + page.Input = append(page.Input, strings.Split(strings.TrimSuffix(menu, "\n"), "\n")...) } } - rows = append(rows, DefaultStyles.Decor.Render(strings.Repeat("─", width))) - rows = append(rows, m.renderFooter()) - for i := range rows { - rows[i] = pad + rows[i] - } - - m.frame.scratch = rows - if m.frame.content == "" || !sameStrings(rows, m.frame.rows) { - m.frame.rows = append(m.frame.rows[:0], rows...) - m.frame.content = stripPrivateMarks(strings.Join(rows, "\n")) - } + m.frame.content = m.frame.transcript.Render(page, chatMargin, stripPrivateMarks) if m.terms != nil { return overlay(m.frame.content, m.terms.view(m.Width, m.Height), m.Width, m.Height) } @@ -447,7 +442,7 @@ func (m ChatModel) noticeRows(width int) []string { } var rows []string for _, n := range m.Notices { - text := DefaultStyles.Faint.Render(n.Message) + text := chrome.DefaultStyles.Faint.Render(n.Message) if n.Error { text = m.Renderer.errorRow(n.Message) } @@ -471,12 +466,8 @@ type frameCache struct { body []string composer []string - // rows is the padded frame as last drawn and content the string handed to - // Bubble Tea, so a frame that changed nothing is not joined again. - rows []string - content string - // scratch is the row slice the next frame is assembled into. - scratch []string + transcript terminalui.TranscriptFrame + content string sidebarKey sidebarKey bodyKey bodyKey @@ -636,7 +627,7 @@ func (m *ChatModel) body() []string { textWidth := max(1, min(m.Renderer.BodyWidth, m.Viewport.Width())-railWidth) shown.rows = nil for _, line := range wrapOrChunkLine("What would you like to work on?", textWidth) { - shown.rows = append(shown.rows, m.Renderer.rail(laneNone)+DefaultStyles.Faint.Render(line)) + shown.rows = append(shown.rows, m.Renderer.rail(laneNone)+chrome.DefaultStyles.Faint.Render(line)) } } column := m.sidebarColumn() diff --git a/cli/internal/tui/chips.go b/cli/internal/tui/chips.go index 84b24d386..8ab96fb2f 100644 --- a/cli/internal/tui/chips.go +++ b/cli/internal/tui/chips.go @@ -5,6 +5,8 @@ import ( "strconv" "strings" + "albedo/cli/internal/tui/chrome" + "github.com/charmbracelet/x/ansi" ) @@ -49,7 +51,7 @@ func (m ChatModel) imageChip(n int, image pastedImage) chip { if clip, _, found := strings.Cut(string(image.MimeType), "/"); found && clip != "image" { kind, caption = clip, string(image.MimeType) } - content := []string{"", DefaultStyles.Faint.Render(kind)} + content := []string{"", chrome.DefaultStyles.Faint.Render(kind)} if image.thumb != nil { content = placeholderRows(*image.thumb) } @@ -70,7 +72,7 @@ func (m ChatModel) pasteChip(n int, text string) chip { for _, line := range lines[:min(len(lines), thumbRows)] { line = ansi.Truncate(strings.ReplaceAll(line, "\t", " "), thumbCols, "") // padded to the full width, so the card keeps the lines left-aligned - content = append(content, DefaultStyles.Faint.Render(line+strings.Repeat(" ", thumbCols-ansi.StringWidth(line)))) + content = append(content, chrome.DefaultStyles.Faint.Render(line+strings.Repeat(" ", thumbCols-ansi.StringWidth(line)))) } return chip{title: "paste #" + strconv.Itoa(n), caption: caption, content: content} } @@ -95,7 +97,7 @@ func (m ChatModel) chipStrip(width int) []string { } } if hidden := len(chips) - max(0, shown); hidden > 0 { - rows[chipRows/2] += DefaultStyles.Faint.Render(" +" + strconv.Itoa(hidden)) + rows[chipRows/2] += chrome.DefaultStyles.Faint.Render(" +" + strconv.Itoa(hidden)) } return rows } @@ -106,11 +108,11 @@ func (m ChatModel) card(c chip) []string { edge := func(left, label, right string) string { label = ansi.Truncate(label, thumbCols-2, "…") fill := thumbCols - ansi.StringWidth(label) - 2 - return DefaultStyles.Decor.Render(left+strings.Repeat("─", fill-fill/2)+" ") + - DefaultStyles.Muted.Render(label) + - DefaultStyles.Decor.Render(" "+strings.Repeat("─", fill/2)+right) + return chrome.DefaultStyles.Decor.Render(left+strings.Repeat("─", fill-fill/2)+" ") + + chrome.DefaultStyles.Muted.Render(label) + + chrome.DefaultStyles.Decor.Render(" "+strings.Repeat("─", fill/2)+right) } - side := DefaultStyles.Decor.Render("│") + side := chrome.DefaultStyles.Decor.Render("│") rows := []string{edge("╭", c.title, "╮")} top := (thumbRows - len(c.content)) / 2 for r := range thumbRows { diff --git a/cli/internal/tui/chroma_patch_test.go b/cli/internal/tui/chroma_patch_test.go index c9d9955cc..ef374d7ba 100644 --- a/cli/internal/tui/chroma_patch_test.go +++ b/cli/internal/tui/chroma_patch_test.go @@ -9,6 +9,8 @@ package tui import ( + "albedo/cli/internal/testutil/tuishots" + "albedo/cli/internal/tui/chrome" "os" "strconv" "strings" @@ -100,15 +102,15 @@ func TestChromaHighlightsLikeStock(t *testing.T) { // columns, or the lines of a diff highlighted for a file. func chromaRender(t *testing.T) []string { t.Helper() - before, styles := transcriptInk, DefaultStyles - t.Cleanup(func() { useInk(before); DefaultStyles = styles }) + before, styles := chrome.CurrentInk, chrome.DefaultStyles + t.Cleanup(func() { chrome.UseInk(before); chrome.DefaultStyles = styles }) var out []string render := func(section string, text string) { out = append(out, strconv.Quote(section+"\x00"+text)) } for _, palette := range []bool{false, true} { if palette { - useInk(testInk(t)) + chrome.UseInk(tuishots.TestInk(t)) } for _, c := range chromaFences { fence := "```" diff --git a/cli/internal/tui/chrome/cell.go b/cli/internal/tui/chrome/cell.go new file mode 100644 index 000000000..4d396c119 --- /dev/null +++ b/cli/internal/tui/chrome/cell.go @@ -0,0 +1,23 @@ +package chrome + +import ( + "strings" + + "github.com/charmbracelet/x/ansi" +) + +// Cell fits plain text into exactly w columns. +func Cell(s string, w int, right bool) string { + if w <= 0 { + return "" + } + s = ansi.Truncate(s, w, "…") + pad := strings.Repeat(" ", max(0, w-ansi.StringWidth(s))) + if right { + return pad + s + } + return s + pad +} + +// Fit pads or cuts a styled line to exactly w columns. +func Fit(s string, w int) string { return Cell(s, w, false) } diff --git a/cli/internal/tui/chrome/confirm.go b/cli/internal/tui/chrome/confirm.go new file mode 100644 index 000000000..964522572 --- /dev/null +++ b/cli/internal/tui/chrome/confirm.go @@ -0,0 +1,55 @@ +package chrome + +import ( + "strings" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" +) + +// Confirm is the one way a screen asks before something far-reaching: +// enter does it, esc leaves it, and every other key is ignored, so a stray +// press while you read the question changes nothing. +type Confirm struct { + Prompt string // what will happen, and the question + verb string // what enter does, in the hint + What string // which action this asks about; the screen dispatches on it + Target string // what the action applies to + Failed bool // the last attempt failed, so enter retries +} + +func (c Confirm) Asking() bool { return c.Prompt != "" } + +func (c *Confirm) Ask(what, target, verb, prompt string) { + *c = Confirm{Prompt: prompt, verb: verb, What: what, Target: target} +} + +func (c *Confirm) Dismiss() { *c = Confirm{} } + +// Key settles a key press while asking: yes on enter, dismissed on esc, +// and ignored otherwise. It reports whether the key was for the question. +func (c *Confirm) Key(msg tea.KeyPressMsg) (yes bool) { + switch msg.String() { + case "enter": + return true + case "esc", "ctrl+c": + c.Dismiss() + } + return false +} + +// Footer is the question, the last failure if there was one, and the keys. +func (c Confirm) Footer(width int, failure string) string { + var rows []string + for line := range strings.SplitSeq(ansi.Wrap(c.Prompt, max(1, width-1), " "), "\n") { + rows = append(rows, " "+DefaultStyles.Warning.Render(line)) + } + if failure != "" { + rows = append(rows, " "+DefaultStyles.Error.Render(ansi.Truncate(failure, max(1, width-1), "…"))) + } + verb := c.verb + if c.Failed || failure != "" { + verb = "retry" + } + return strings.Join(append(rows, " "+KeyHints(Hint{"enter", verb}, Hint{"esc", "cancel"})), "\n") +} diff --git a/cli/internal/tui/chrome/field.go b/cli/internal/tui/chrome/field.go new file mode 100644 index 000000000..899c96a30 --- /dev/null +++ b/cli/internal/tui/chrome/field.go @@ -0,0 +1,12 @@ +package chrome + +import ( + "charm.land/bubbles/v2/textinput" +) + +// NewField is a text input that follows a label instead of a prompt. +func NewField() textinput.Model { + input := NewTextInput() + input.Prompt = "" + return input +} diff --git a/cli/internal/tui/chrome/footer.go b/cli/internal/tui/chrome/footer.go new file mode 100644 index 000000000..ecf913bd7 --- /dev/null +++ b/cli/internal/tui/chrome/footer.go @@ -0,0 +1,49 @@ +package chrome + +import ( + "strings" + + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" +) + +// FooterLine is the keys on the left and a status on the right. When both +// do not fit, an urgent status (an error, a notice, work in flight) takes +// a row of its own above the keys, and any other status gives way to them. +// The keys lose their labels only when no three labelled hints fit at all. +func FooterLine(width int, hints []Hint, status string, urgent bool) string { + if len(hints) == 0 { + return StatusRows(width, status) + } + if status != "" { + left := FitHints(hints, width-ansi.StringWidth(status)-3) + if left != "" && (urgent || left == " "+KeyHints(hints...)) { + return left + strings.Repeat(" ", width-ansi.StringWidth(left)-ansi.StringWidth(status)-1) + status + } + } + keys := FitHints(hints, width-1) + if keys == "" { + bare := make([]Hint, len(hints)) + for i, h := range hints { + bare[i] = Hint{Key: h.Key} + if h.Key == "" { + bare[i].Does = h.Does + } + } + keys = " " + ansi.Truncate(KeyHints(bare...), max(1, width-2), "…") + } + if urgent && status != "" { + return StatusRows(width, status) + "\n" + keys + } + return keys +} + +// StatusRows is a status on rows of its own, wrapped to two at most. +func StatusRows(width int, status string) string { + rows := strings.Split(lipgloss.Wrap(status, max(1, width-2), " /"), "\n") + if len(rows) > 2 { + rows = rows[:2] + rows[1] = ansi.Truncate(rows[1], max(1, width-3), "") + "…" + } + return " " + strings.Join(rows, "\n ") +} diff --git a/cli/internal/tui/chrome/hints.go b/cli/internal/tui/chrome/hints.go new file mode 100644 index 000000000..72f28e0e4 --- /dev/null +++ b/cli/internal/tui/chrome/hints.go @@ -0,0 +1,29 @@ +package chrome + +import ( + "slices" + + "github.com/charmbracelet/x/ansi" +) + +// FitHints is " " and the labelled hints in room columns. A screen lists its +// hints most important first and esc last. What the screen already says goes +// first: moving, then the least important hints one at a time from the end, +// always keeping esc. Empty when not even three of them fit. +func FitHints(hints []Hint, room int) string { + still := slices.DeleteFunc(slices.Clone(hints), func(h Hint) bool { return h.Key == "↑↓" }) + candidates := [][]Hint{hints, still} + leaving := slices.IndexFunc(still, func(h Hint) bool { return h.Key == "esc" }) + if leaving >= 0 { + staying := slices.Delete(slices.Clone(still), leaving, leaving+1) + for n := len(staying) - 1; n >= min(2, len(staying)); n-- { + candidates = append(candidates, append(slices.Clone(staying[:n]), still[leaving])) + } + } + for _, candidate := range candidates { + if line := " " + KeyHints(candidate...); len(candidate) > 0 && ansi.StringWidth(line) <= room { + return line + } + } + return "" +} diff --git a/cli/internal/tui/ink.go b/cli/internal/tui/chrome/ink.go similarity index 64% rename from cli/internal/tui/ink.go rename to cli/internal/tui/chrome/ink.go index 6aade0d2d..bda6a4ebf 100644 --- a/cli/internal/tui/ink.go +++ b/cli/internal/tui/chrome/ink.go @@ -1,4 +1,4 @@ -package tui +package chrome import ( "fmt" @@ -10,16 +10,18 @@ import ( "github.com/lucasb-eyer/go-colorful" ) -// ink is the transcript's brightness ramp. Each step is mixed from the +// Ink is the transcript's brightness ramp. Each step is mixed from the // terminal's own text and background colors to a contrast target, so the // ramp keeps its spacing on any theme instead of trusting palette slots. -type ink struct { +type Ink struct { + agents *agentPalette // code steps down from prose for inline and fenced code. - code string + Code string // secondary is text read at a glance: tool rows, timings, notices. - secondary string + Secondary string + hint string // decor is structure that is seen, not read: list markers, gutters. - decor string + Decor string // busy is albedo's rail color while it works in tools. busy string // codeBg tints the cells under inline code, so a span keeps prose @@ -28,14 +30,15 @@ type ink struct { // surface lifts a selected row off the background. surface string // added and removed are the diff row tints. - added, removed string + added, removed string + success, warning, failure string // brandFrom and brandTo are the ends of the brand gradient. - brandFrom, brandTo string + BrandFrom, BrandTo string // bg is the terminal's background, which language colors adapt to. bg string // heading, strong, inlineCode, link and math color markdown's marks, // each a palette hue made legible on bg. - heading, strong, inlineCode, link, math string + Heading, Strong, InlineCode, Link, Math string } // APCA contrast targets (Lc) for each step: about 60 suits content text, @@ -62,20 +65,20 @@ const ( headingLc = 75 ) -type rgb struct{ r, g, b float64 } +type RGB struct{ r, g, b float64 } -func (c rgb) hex() string { +func (c RGB) Hex() string { b := func(v float64) int { return int(math.Round(math.Max(0, math.Min(1, v)) * 255)) } return "#" + strconv.FormatInt(int64(1<<24|b(c.r)<<16|b(c.g)<<8|b(c.b)), 16)[1:] } -func (c rgb) mix(to rgb, t float64) rgb { - return rgb{c.r + (to.r-c.r)*t, c.g + (to.g-c.g)*t, c.b + (to.b-c.b)*t} +func (c RGB) Mix(to RGB, t float64) RGB { + return RGB{c.r + (to.r-c.r)*t, c.g + (to.g-c.g)*t, c.b + (to.b-c.b)*t} } // apca is the magnitude of the APCA 0.0.98G lightness contrast of text on bg. -func apca(text, bg rgb) float64 { - y := func(c rgb) float64 { +func apca(text, bg RGB) float64 { + y := func(c RGB) float64 { v := 0.2126729*math.Pow(c.r, 2.4) + 0.7151522*math.Pow(c.g, 2.4) + 0.0721750*math.Pow(c.b, 2.4) if v < 0.022 { v += math.Pow(0.022-v, 1.414) @@ -114,16 +117,16 @@ func bisect(still func(t float64) bool) (lo, hi float64) { // toward mixes from into bg until it reaches the target contrast. A color // already under the target stays as it is. -func toward(from, bg rgb, target float64) rgb { +func toward(from, bg RGB, target float64) RGB { if apca(from, bg) <= target { return from } - t, _ := bisect(func(t float64) bool { return apca(from.mix(bg, t), bg) > target }) - return from.mix(bg, t) + t, _ := bisect(func(t float64) bool { return apca(from.Mix(bg, t), bg) > target }) + return from.Mix(bg, t) } // luminance is relative luminance as the WCAG contrast ratio defines it. -func luminance(c rgb) float64 { +func luminance(c RGB) float64 { lin := func(v float64) float64 { if v <= 0.04045 { return v / 12.92 @@ -134,26 +137,26 @@ func luminance(c rgb) float64 { } // ratio is the WCAG contrast ratio between two colors. -func ratio(a, b rgb) float64 { +func ratio(a, b RGB) float64 { la, lb := luminance(a)+0.05, luminance(b)+0.05 return max(la, lb) / min(la, lb) } // step mixes bg toward to until the two differ by the given contrast ratio, // or reaches to when it cannot. -func step(bg, to rgb, target float64) rgb { +func step(bg, to RGB, target float64) RGB { if ratio(bg, to) <= target { return to } // hi is the first fraction that meets the ratio; lo only approaches it. - _, t := bisect(func(t float64) bool { return ratio(bg, bg.mix(to, t)) < target }) - return bg.mix(to, t) + _, t := bisect(func(t float64) bool { return ratio(bg, bg.Mix(to, t)) < target }) + return bg.Mix(to, t) } // legible moves c's OKLCH lightness away from bg, up on a dark background // and down on a light one, until its APCA contrast reaches target. Hue and // chroma stay, so a language keeps its color on every theme. -func legible(c, bg rgb, target float64) rgb { +func legible(c, bg RGB, target float64) RGB { if apca(c, bg) >= target { return c } @@ -162,103 +165,109 @@ func legible(c, bg rgb, target float64) rgb { if bgL, _, _ := (colorful.Color{R: bg.r, G: bg.g, B: bg.b}).OkLch(); bgL > 0.6 { end = 0 } - at := func(t float64) rgb { + at := func(t float64) RGB { v := colorful.OkLch(l+(end-l)*t, chroma, hue).Clamped() - return rgb{v.R, v.G, v.B} + return RGB{v.R, v.G, v.B} } _, t := bisect(func(t float64) bool { return apca(at(t), bg) < target }) return at(t) } -// termColors is what the terminal reported. A missing color is nil, and +// TermColors is what the terminal reported. A missing color is nil, and // palette holds only the entries that were reported. -type termColors struct { - fg, bg *rgb - palette map[int]rgb +type TermColors struct { + Fg, Bg *RGB + Palette map[int]RGB } // The palette entries the theme mixes from. const ( - ansiRed = 1 - ansiGreen = 2 + AnsiRed = 1 + AnsiGreen = 2 ansiYellow = 3 - ansiBlue = 4 - ansiMagenta = 5 - ansiCyan = 6 + AnsiBlue = 4 + AnsiMagenta = 5 + AnsiCyan = 6 ) -var queriedPalette = []int{ansiRed, ansiGreen, ansiYellow, ansiBlue, ansiMagenta, ansiCyan} - // minTrustLc is the least contrast a reported text color may have with the // reported background. Below it the reply describes something other than // what is on screen, like a multiplexer that answers with black for colors // it does not know, and the palette fallbacks are safer. const minTrustLc = 60 -func mixInk(c termColors) (ink, bool) { - if c.fg == nil || c.bg == nil || apca(*c.fg, *c.bg) < minTrustLc { - return ink{}, false +func MixInk(c TermColors) (Ink, bool) { + if c.Fg == nil || c.Bg == nil || apca(*c.Fg, *c.Bg) < minTrustLc { + return Ink{}, false } - fg, bg := *c.fg, *c.bg - out := ink{ - code: toward(fg, bg, codeLc).hex(), - secondary: toward(fg, bg, secondaryLc).hex(), - decor: toward(fg, bg, decorLc).hex(), - surface: step(bg, fg, surfaceRatio).hex(), - bg: bg.hex(), + fg, bg := *c.Fg, *c.Bg + out := Ink{ + Code: toward(fg, bg, codeLc).Hex(), + Secondary: toward(fg, bg, secondaryLc).Hex(), + hint: toward(fg, bg, 52).Hex(), + Decor: toward(fg, bg, decorLc).Hex(), + surface: step(bg, fg, surfaceRatio).Hex(), + bg: bg.Hex(), } - blue, hasBlue := c.palette[ansiBlue] + blue, hasBlue := c.Palette[AnsiBlue] codeTarget, codeRatio := fg, darkCodeBgRatio if luminance(bg) > luminance(fg) { codeRatio = lightCodeBgRatio } else if hasBlue { codeTarget = blue } - out.codeBg = step(bg, codeTarget, codeRatio).hex() - if magenta, ok := c.palette[ansiMagenta]; ok && apca(magenta, bg) >= busyLc { - out.busy = toward(magenta, bg, busyLc).hex() + out.codeBg = step(bg, codeTarget, codeRatio).Hex() + if magenta, ok := c.Palette[AnsiMagenta]; ok && apca(magenta, bg) >= busyLc { + out.busy = toward(magenta, bg, busyLc).Hex() + } + if red, ok := c.Palette[AnsiRed]; ok { + out.removed = step(bg, red, diffRatio).Hex() + out.failure = legible(red, bg, codeLc).Hex() } - if red, ok := c.palette[ansiRed]; ok { - out.removed = step(bg, red, diffRatio).hex() + if green, ok := c.Palette[AnsiGreen]; ok { + out.added = step(bg, green, diffRatio).Hex() + out.success = legible(green, bg, codeLc).Hex() } - if green, ok := c.palette[ansiGreen]; ok { - out.added = step(bg, green, diffRatio).hex() + if yellow, ok := c.Palette[ansiYellow]; ok { + out.warning = legible(yellow, bg, codeLc).Hex() } // the brand runs from your color toward violet, halfway between the // palette's blue and magenta - cyan, hasCyan := c.palette[ansiCyan] - magenta, hasMagenta := c.palette[ansiMagenta] + cyan, hasCyan := c.Palette[AnsiCyan] + magenta, hasMagenta := c.Palette[AnsiMagenta] if hasCyan && hasBlue && hasMagenta { - out.brandFrom, out.brandTo = cyan.hex(), blue.mix(magenta, 0.5).hex() + violet := blue.Mix(magenta, 0.5) + out.BrandFrom, out.BrandTo = legible(cyan, bg, secondaryLc).Hex(), legible(violet, bg, secondaryLc).Hex() + out.surface = step(bg, legible(violet, bg, headingLc), surfaceRatio).Hex() } - markdownAccents(&out, c.palette, bg) + markdownAccents(&out, c.Palette, bg) return out, true } // markdownAccents colors markdown from the palette: headings in the // brand's violet, strong text in the yellow pulled toward red, inline code // green, links blue and math cyan. -func markdownAccents(out *ink, palette map[int]rgb, bg rgb) { - onBg := func(c rgb, target float64) string { return legible(c, bg, target).hex() } - red, hasRed := palette[ansiRed] +func markdownAccents(out *Ink, palette map[int]RGB, bg RGB) { + onBg := func(c RGB, target float64) string { return legible(c, bg, target).Hex() } + red, hasRed := palette[AnsiRed] if yellow, ok := palette[ansiYellow]; ok { if hasRed { - yellow = yellow.mix(red, 0.35) + yellow = yellow.Mix(red, 0.35) } - out.strong = onBg(yellow, headingLc) + out.Strong = onBg(yellow, headingLc) } - blue, hasBlue := palette[ansiBlue] - if magenta, ok := palette[ansiMagenta]; ok && hasBlue { - out.heading = onBg(blue.mix(magenta, 0.5), headingLc) + blue, hasBlue := palette[AnsiBlue] + if magenta, ok := palette[AnsiMagenta]; ok && hasBlue { + out.Heading = onBg(blue.Mix(magenta, 0.5), headingLc) } if hasBlue { - out.link = onBg(blue, codeLc) + out.Link = onBg(blue, codeLc) } - if green, ok := palette[ansiGreen]; ok { - out.inlineCode = onBg(green, codeLc) + if green, ok := palette[AnsiGreen]; ok { + out.InlineCode = onBg(green, codeLc) } - if cyan, ok := palette[ansiCyan]; ok { - out.math = onBg(cyan, codeLc) + if cyan, ok := palette[AnsiCyan]; ok { + out.Math = onBg(cyan, codeLc) } } @@ -266,28 +275,28 @@ var oscColor = regexp.MustCompile(`\x1b\](10|11|4;(\d+));rgb:([0-9a-fA-F]{1,4})/ // parseColors reads OSC 10, 11 and 4 replies, whose channels carry one to // four hex digits each. -func parseColors(reply string) termColors { - c := termColors{palette: map[int]rgb{}} +func parseColors(reply string) TermColors { + c := TermColors{Palette: map[int]RGB{}} for _, m := range oscColor.FindAllStringSubmatch(reply, -1) { channel := func(h string) float64 { v, _ := strconv.ParseUint(h, 16, 16) return float64(v) / float64(uint64(1)<<(4*len(h))-1) } - col := &rgb{channel(m[3]), channel(m[4]), channel(m[5])} + col := &RGB{channel(m[3]), channel(m[4]), channel(m[5])} switch m[1] { case "10": - c.fg = col + c.Fg = col case "11": - c.bg = col + c.Bg = col default: index, _ := strconv.Atoi(m[2]) - c.palette[index] = *col + c.Palette[index] = *col } } return c } -var transcriptInk ink +var CurrentInk Ink // DetectInk asks the terminal for its colors and mixes the transcript's // ramp from them. It must run before the TUI owns the terminal's input. @@ -296,12 +305,12 @@ func DetectInk() error { if err != nil { return err } - detected, ok := mixInk(parseColors(reply)) + detected, ok := MixInk(parseColors(reply)) if path := os.Getenv("ALBEDO_INK_DEBUG"); path != "" { _ = os.WriteFile(path, fmt.Appendf(nil, "reply %q\ntrusted %v\nink %+v\n", reply, ok, detected), 0o644) } if ok { - useInk(detected) + UseInk(detected) } return nil } diff --git a/cli/internal/tui/ink_other.go b/cli/internal/tui/chrome/ink_other.go similarity index 89% rename from cli/internal/tui/ink_other.go rename to cli/internal/tui/chrome/ink_other.go index d3e5aba5a..74209cbf6 100644 --- a/cli/internal/tui/ink_other.go +++ b/cli/internal/tui/chrome/ink_other.go @@ -1,5 +1,5 @@ //go:build !(darwin || dragonfly || freebsd || linux || netbsd || openbsd) -package tui +package chrome func queryColors() (string, error) { return "", nil } diff --git a/cli/internal/tui/ink_unix.go b/cli/internal/tui/chrome/ink_unix.go similarity index 94% rename from cli/internal/tui/ink_unix.go rename to cli/internal/tui/chrome/ink_unix.go index 6804347d4..109ff2f8b 100644 --- a/cli/internal/tui/ink_unix.go +++ b/cli/internal/tui/chrome/ink_unix.go @@ -1,6 +1,6 @@ //go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd -package tui +package chrome import ( "fmt" @@ -13,6 +13,8 @@ import ( "golang.org/x/sys/unix" ) +var queriedPalette = []int{AnsiRed, AnsiGreen, ansiYellow, AnsiBlue, AnsiMagenta, AnsiCyan} + // queryColors asks for the text and background colors and the palette entries the theme mixes from, then asks // for the device attributes every terminal answers, so a terminal that // ignores the color queries ends the read instead of stalling it. diff --git a/cli/internal/tui/chrome/operation_error.go b/cli/internal/tui/chrome/operation_error.go new file mode 100644 index 000000000..499ff206c --- /dev/null +++ b/cli/internal/tui/chrome/operation_error.go @@ -0,0 +1,14 @@ +package chrome + +import ( + "errors" + + "albedo/cli/internal/daemon" +) + +func OperationError(err error, failure, guidance string) string { + if _, uncertain := errors.AsType[*daemon.UncertainOutcomeError](err); uncertain { + return guidance + } + return failure + err.Error() +} diff --git a/cli/internal/tui/rename.go b/cli/internal/tui/chrome/rename.go similarity index 56% rename from cli/internal/tui/rename.go rename to cli/internal/tui/chrome/rename.go index 82366a66a..fbdc2c400 100644 --- a/cli/internal/tui/rename.go +++ b/cli/internal/tui/chrome/rename.go @@ -1,4 +1,4 @@ -package tui +package chrome import ( "strings" @@ -13,18 +13,18 @@ import ( // the title back to the daemon, which takes it from the latest message. type SessionRenameMsg struct{ ID, Name, ETag string } -// sessionRenamedMsg is the daemon's answer to a SessionRenameMsg: the +// SessionRenamedMsg is the daemon's answer to a SessionRenameMsg: the // session as it is now listed. -type sessionRenamedMsg struct { +type SessionRenamedMsg struct { Err error Configuration daemon.SessionConfiguration SessionRenameMsg } -// renameField edits one session's name in place. While it is open its owner +// RenameField edits one session's name in place. While it is open its owner // hands it every key, so typing never reaches search or navigation. -type renameField struct { - id, was, etag string +type RenameField struct { + ID, was, ETag string input textinput.Model // selected holds until the first key: typing replaces the opening // draft, which a message title can fill to the limit; other keys edit it. @@ -34,9 +34,9 @@ type renameField struct { // renameLimit matches the daemon, which keeps 80 characters of a name. const renameLimit = 80 -// open starts a draft of current, prompting with placeholder once emptied. -func (f *renameField) open(id, current, placeholder string) { - in := newField() +// Open starts a draft of current, prompting with placeholder once emptied. +func (f *RenameField) Open(id, current, placeholder string) { + in := NewField() in.CharLimit = renameLimit in.Placeholder = placeholder st := in.Styles() @@ -46,25 +46,25 @@ func (f *renameField) open(id, current, placeholder string) { in.SetValue(current) in.CursorEnd() in.Focus() - f.id, f.was, f.input, f.selected = id, current, in, current != "" + f.ID, f.was, f.input, f.selected = id, current, in, current != "" } -func (f renameField) active() bool { return f.id != "" } +func (f RenameField) Active() bool { return f.ID != "" } -// key edits the draft. Enter saves a changed name and esc drops it; both +// Key edits the draft. Enter saves a changed name and esc drops it; both // close the field. -func (f *renameField) key(msg tea.KeyPressMsg) tea.Cmd { +func (f *RenameField) Key(msg tea.KeyPressMsg) tea.Cmd { switch msg.String() { case "esc", "ctrl+c": - f.id = "" + f.ID = "" return nil case "enter": - id, name := f.id, strings.TrimSpace(f.input.Value()) - f.id = "" + id, name := f.ID, strings.TrimSpace(f.input.Value()) + f.ID = "" if name == strings.TrimSpace(f.was) { return nil } - return func() tea.Msg { return SessionRenameMsg{ID: id, Name: name, ETag: f.etag} } + return func() tea.Msg { return SessionRenameMsg{ID: id, Name: name, ETag: f.ETag} } } if f.selected && msg.Text != "" { f.input.SetValue("") @@ -75,18 +75,18 @@ func (f *renameField) key(msg tea.KeyPressMsg) tea.Cmd { return cmd } -// view is the draft in exactly width cells. -func (f renameField) view(width int) string { +// View is the draft in exactly width cells. +func (f RenameField) View(width int) string { f.input.SetWidth(max(1, width-1)) if f.selected { st := f.input.Styles() st.Focused.Text = DefaultStyles.Cursor f.input.SetStyles(st) } - return svFit(f.input.View(), width) + return Fit(f.input.View(), width) } -// renameHints stand in for a screen's key hints while a name is being edited. -func renameHints(blank string) string { - return keyHints(hint{"enter", "save"}, hint{"esc", "cancel"}, hint{"", "empty " + blank}) +// RenameHints stand in for a screen's key hints while a name is being edited. +func RenameHints(blank string) string { + return KeyHints(Hint{"enter", "save"}, Hint{"esc", "cancel"}, Hint{"", "empty " + blank}) } diff --git a/cli/internal/tui/chrome/text.go b/cli/internal/tui/chrome/text.go new file mode 100644 index 000000000..c65088d3a --- /dev/null +++ b/cli/internal/tui/chrome/text.go @@ -0,0 +1,14 @@ +package chrome + +import ( + "strings" +) + +func FirstLine(text string) string { + for line := range strings.SplitSeq(text, "\n") { + if line = strings.TrimSpace(line); line != "" { + return line + } + } + return "" +} diff --git a/cli/internal/tui/theme.go b/cli/internal/tui/chrome/theme.go similarity index 58% rename from cli/internal/tui/theme.go rename to cli/internal/tui/chrome/theme.go index 898c37161..692f56c29 100644 --- a/cli/internal/tui/theme.go +++ b/cli/internal/tui/chrome/theme.go @@ -1,4 +1,5 @@ -package tui +// Package chrome provides Albedo’s terminal palette and shared screen controls. +package chrome import ( "cmp" @@ -17,7 +18,7 @@ import ( ) // Styles defines the shared terminal palette. Screens compose these -// styles and components, so the transcript, the session screen, and the +// Styles and components, so the transcript, the session screen, and the // pickers cannot drift into their own palettes. // // Tokens come in three kinds: @@ -71,22 +72,35 @@ var DefaultStyles = Styles{ Cursor: lipgloss.NewStyle().Reverse(true), } -func useInk(detected ink) { - transcriptInk = detected +func UseInk(detected Ink) { + detected.agents = graphPalette(detected) + CurrentInk = detected fg := func(hex string) lipgloss.Style { return lipgloss.NewStyle().Foreground(lipgloss.Color(hex)) } - DefaultStyles.Muted = fg(detected.code) - DefaultStyles.Faint = fg(detected.secondary) - DefaultStyles.Decor = fg(detected.decor) + if detected.success != "" { + DefaultStyles.Success = fg(detected.success) + } + if detected.warning != "" { + DefaultStyles.Warning = fg(detected.warning) + } + if detected.failure != "" { + DefaultStyles.Error = fg(detected.failure) + } + if detected.BrandFrom != "" { + DefaultStyles.Prompt = fg(detected.BrandFrom) + } + DefaultStyles.Muted = fg(detected.Code) + DefaultStyles.Faint = fg(cmp.Or(detected.hint, detected.Secondary)) + DefaultStyles.Decor = fg(detected.Decor) if detected.busy != "" { DefaultStyles.Busy = fg(detected.busy) } DefaultStyles.Selected = lipgloss.NewStyle().Background(lipgloss.Color(detected.surface)) } -// newTextInput is a text input in the theme: plain text and prompt whether +// NewTextInput is a text input in the theme: plain text and prompt whether // focused or not, and a reverse-video cursor that holds still, so an idle // input never wakes the program to blink. -func newTextInput() textinput.Model { +func NewTextInput() textinput.Model { ti := textinput.New() s := ti.Styles() s.Focused.Prompt, s.Focused.Text = lipgloss.NewStyle(), lipgloss.NewStyle() @@ -97,17 +111,17 @@ func newTextInput() textinput.Model { } const ( - ansiReset = "\x1b[0m" - ansiItalic = "\x1b[3m" + AnsiReset = "\x1b[0m" + AnsiItalic = "\x1b[3m" ansiGray = "\x1b[90m" ) -// sgr is a foreground color as an escape sequence, or fallback when the +// Sgr is a foreground color as an escape sequence, or fallback when the // ramp is unknown. Bubble Tea downsamples it to the terminal's profile. -func sgr(hex, fallback string) string { return sgrLayer(hex, fallback, false) } +func Sgr(hex, fallback string) string { return sgrLayer(hex, fallback, false) } func sgrLayer(hex, fallback string, background bool) string { - if parseHex(hex) == nil { + if ParseHex(hex) == nil { return fallback } if background { @@ -116,50 +130,42 @@ func sgrLayer(hex, fallback string, background bool) string { return ansi.NewStyle().ForegroundColor(lipgloss.Color(hex)).String() } -// codeInk steps code down from prose so a reply that decorates every -// identifier stays quiet. -func codeInk() string { return sgr(transcriptInk.code, "\x1b[37m") } - -// faintInk is the Faint token as a raw sequence, for markdown's own spans. -func faintInk() string { return sgr(transcriptInk.secondary, ansiGray) } - -// decorInk is the Decor token as a raw sequence. -func decorInk() string { return sgr(transcriptInk.decor, ansiGray) } +// DecorInk is the Decor token as a raw sequence. +func DecorInk() string { return Sgr(CurrentInk.Decor, ansiGray) } -// Diff rows sit on tints mixed toward the palette's red and green. The -// fallbacks are dark tints, the only case without reported colors. -func diffPanel() string { return sgrLayer(transcriptInk.surface, "\x1b[48;2;37;40;50m", true) } -func diffAdded() string { return sgrLayer(transcriptInk.added, "\x1b[48;2;24;53;39m", true) } -func diffRemoved() string { return sgrLayer(transcriptInk.removed, "\x1b[48;2;59;35;40m", true) } +// DiffPanel supplies the base background for diff rows. +func DiffPanel() string { return sgrLayer(CurrentInk.surface, "\x1b[48;2;37;40;50m", true) } +func DiffAdded() string { return sgrLayer(CurrentInk.added, "\x1b[48;2;24;53;39m", true) } +func DiffRemoved() string { return sgrLayer(CurrentInk.removed, "\x1b[48;2;59;35;40m", true) } -// keepBackground turns full resets into foreground and attribute resets, so +// KeepBackground turns full resets into foreground and attribute resets, so // a styled span inside a tinted row keeps the row's background. Lip Gloss // spells a full reset "ESC[m"; the raw ink spells it "ESC[0m". -func keepBackground(s string) string { - return strings.NewReplacer(ansiReset, "\x1b[39;22;23m", "\x1b[m", "\x1b[39;22;23m").Replace(s) +func KeepBackground(s string) string { + return strings.NewReplacer(AnsiReset, "\x1b[39;22;23m", "\x1b[m", "\x1b[39;22;23m").Replace(s) } // gradient is the brand ramp at t in [0, 1], or nil when the terminal did // not report the colors it is mixed from. func gradient(t float64) color.Color { - from, to := parseHex(transcriptInk.brandFrom), parseHex(transcriptInk.brandTo) + from, to := ParseHex(CurrentInk.BrandFrom), ParseHex(CurrentInk.BrandTo) if from == nil || to == nil { return nil } - return lipgloss.Color(from.mix(*to, min(1, max(0, t))).hex()) + return lipgloss.Color(from.Mix(*to, min(1, max(0, t))).Hex()) } -func parseHex(hex string) *rgb { +func ParseHex(hex string) *RGB { var r, g, b int if _, err := fmt.Sscanf(hex, "#%02x%02x%02x", &r, &g, &b); err != nil { return nil } - return &rgb{float64(r) / 255, float64(g) / 255, float64(b) / 255} + return &RGB{float64(r) / 255, float64(g) / 255, float64(b) / 255} } -// gradientText sweeps the brand ramp across s. Without it s takes the agent +// GradientText sweeps the brand ramp across s. Without it s takes the agent // color. -func gradientText(s string, bold bool) string { +func GradientText(s string, bold bool) string { if gradient(0) == nil { return DefaultStyles.Agent.Bold(bold).Render(s) } @@ -187,15 +193,15 @@ type rampKey struct { // detected ink, and every frame's header asks for the same few again. var ramps struct { byKey map[rampKey]string - ink ink + ink Ink sync.Mutex } func ramp(key rampKey, render func() string) string { ramps.Lock() defer ramps.Unlock() - if ramps.byKey == nil || ramps.ink != transcriptInk || len(ramps.byKey) > 256 { - ramps.ink, ramps.byKey = transcriptInk, map[rampKey]string{} + if ramps.byKey == nil || ramps.ink != CurrentInk || len(ramps.byKey) > 256 { + ramps.ink, ramps.byKey = CurrentInk, map[rampKey]string{} } s, ok := ramps.byKey[key] if !ok { @@ -205,19 +211,19 @@ func ramp(key rampKey, render func() string) string { return s } -// brandInk colors a mark along the brand ramp, or in the agent color. -func brandInk(t float64) lipgloss.Style { +// BrandInk colors a mark along the brand ramp, or in the agent color. +func BrandInk(t float64) lipgloss.Style { if c := gradient(t); c != nil { return lipgloss.NewStyle().Foreground(c) } return DefaultStyles.Agent } -func brand(name string) string { return gradientText("✦ "+name, true) } +func Brand(name string) string { return GradientText("✦ "+name, true) } -// titleRule heads a screen: left, a rule that fades from the brand's end +// TitleRule heads a screen: left, a rule that fades from the brand's end // into Decor, then right. Without room for one rule cell it is left alone. -func titleRule(width int, left, right string) string { +func TitleRule(width int, left, right string) string { if right != "" { right = " " + right } @@ -231,11 +237,11 @@ func titleRule(width int, left, right string) string { // fadeRule is n rule cells fading from the brand's end into Decor. func fadeRule(n int) string { var rule strings.Builder - from, to := parseHex(transcriptInk.brandTo), parseHex(transcriptInk.decor) + from, to := ParseHex(CurrentInk.BrandTo), ParseHex(CurrentInk.Decor) for i := range n { t := float64(i) / float64(n) if from != nil && to != nil && t < 0.35 { - rule.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color(from.mix(*to, t/0.35).hex())).Render("─")) + rule.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color(from.Mix(*to, t/0.35).Hex())).Render("─")) continue } rule.WriteString(DefaultStyles.Decor.Render("─")) @@ -243,76 +249,76 @@ func fadeRule(n int) string { return rule.String() } -// located is the brand at a place: "✦ albedo on ~/path". -func located(name, place string) string { +// Located is the brand at a place: "✦ albedo on ~/path". +func Located(name, place string) string { if place == "" { - return brand(name) + return Brand(name) } - return brand(name) + DefaultStyles.Faint.Render(" on ") + DefaultStyles.Muted.Render(place) + return Brand(name) + DefaultStyles.Faint.Render(" on ") + DefaultStyles.Muted.Render(place) } -// hint is a key and what it does. -type hint struct{ key, does string } +// Hint is a key and what it does. +type Hint struct{ Key, Does string } -// keyHints lists keys in Muted and what they do in Faint. A hint without a +// KeyHints lists keys in Muted and what they do in Faint. A hint without a // key is a plain note. -func keyHints(hints ...hint) string { +func KeyHints(hints ...Hint) string { parts := make([]string, len(hints)) for i, h := range hints { switch { - case h.key == "": - parts[i] = DefaultStyles.Faint.Render(h.does) - case h.does == "": - parts[i] = DefaultStyles.Muted.Render(h.key) + case h.Key == "": + parts[i] = DefaultStyles.Faint.Render(h.Does) + case h.Does == "": + parts[i] = DefaultStyles.Prompt.Bold(true).Render(h.Key) default: - parts[i] = DefaultStyles.Muted.Render(h.key) + " " + DefaultStyles.Faint.Render(h.does) + parts[i] = DefaultStyles.Prompt.Bold(true).Render(h.Key) + " " + DefaultStyles.Faint.Render(h.Does) } } return strings.Join(parts, DefaultStyles.Decor.Render(" · ")) } -// sectionRule heads a group in a list: " ─ label count ────". -func sectionRule(label string, count, width int) string { +// SectionRule heads a group in a list: " ─ label count ────". +func SectionRule(label string, count, width int) string { head := " " + label + " " tail := fmt.Sprintf("%d ", count) rule := strings.Repeat("─", max(0, width-2-ansi.StringWidth(head+tail))) return DefaultStyles.Decor.Render(" ─") + DefaultStyles.Muted.Bold(true).Render(head) + DefaultStyles.Decor.Render(tail+rule) } -// groupHeading heads a group of sections in a list, above their rules. -func groupHeading(label string, width int) string { +// GroupHeading heads a group of sections in a list, above their rules. +func GroupHeading(label string, width int) string { return DefaultStyles.Bold.Render(ansi.Truncate(" "+label, width, "…")) } -// promptMark is where you type. -const promptMark = "› " -const promptMarkWidth = 2 +// PromptMark precedes the focused input. +const PromptMark = "› " +const PromptMarkWidth = 2 -func promptLead() string { return DefaultStyles.Prompt.Render(promptMark) } +func PromptLead() string { return DefaultStyles.Prompt.Render(PromptMark) } -// selectBar marks the selected row. -func selectBar() string { return DefaultStyles.Agent.Render("▌") } +// SelectBar marks the selected row. +func SelectBar() string { return DefaultStyles.Agent.Render("▌") } -// selectedLine lays the selection surface under a styled line, reopening it +// SelectedLine lays the selection surface under a styled line, reopening it // after every reset inside the line, and fills it out to width. -func selectedLine(line string, width int) string { +func SelectedLine(line string, width int) string { marked := DefaultStyles.Selected.Render("\x00") open := marked[:strings.IndexByte(marked, 0)] if pad := width - ansi.StringWidth(line); pad > 0 { line += strings.Repeat(" ", pad) } - return open + strings.NewReplacer(ansiReset, ansiReset+open, "\x1b[m", "\x1b[m"+open).Replace(line) + ansiReset + return open + strings.NewReplacer(AnsiReset, AnsiReset+open, "\x1b[m", "\x1b[m"+open).Replace(line) + AnsiReset } -// homePath shortens a path under your home directory to start with ~. -func homePath(p string) string { +// HomePath shortens a path under your home directory to start with ~. +func HomePath(p string) string { home, _ := os.UserHomeDir() - return underHome(p, home) + return UnderHome(p, home) } -// pathFolds shortens a path by folding its middle into "…" one more segment +// PathFolds shortens a path by folding its middle into "…" one more segment // at a time, keeping its root and its name: ~/a/b/c, ~/…/b/c, ~/…/c. -func pathFolds(p string) []string { +func PathFolds(p string) []string { sep := string(filepath.Separator) parts := strings.Split(p, sep) folds := []string{p} @@ -322,8 +328,8 @@ func pathFolds(p string) []string { return folds } -// underHome shortens p under home to start with ~. -func underHome(p, home string) string { +// UnderHome shortens p under home to start with ~. +func UnderHome(p, home string) string { rest, ok := strings.CutPrefix(p, home) if home == "" || !ok || rest != "" && rest[0] != filepath.Separator { return p @@ -331,9 +337,9 @@ func underHome(p, home string) string { return "~" + rest } -// scpRelative is a remote path after its host's colon as scp reads it: +// ScpRelative is a remote path after its host's colon as scp reads it: // one under ~ relative to the home, which itself stays ~. -func scpRelative(p string) string { +func ScpRelative(p string) string { if rest, ok := strings.CutPrefix(p, "~/"); ok { return rest } @@ -363,60 +369,77 @@ var languageHues = map[string]string{ // file names are read, so about what content text gets. const languageLc = 60 -// languageStyle colors a language: our hue for it, else linguist's, adapted +// LanguageStyle colors a language: our hue for it, else linguist's, adapted // to the terminal. A language with neither steps back like other metadata. -func languageStyle(name, linguist string) lipgloss.Style { - c := parseHex(cmp.Or(languageHues[name], linguist)) +func LanguageStyle(name, linguist string) lipgloss.Style { + c := ParseHex(cmp.Or(languageHues[name], linguist)) if c == nil { return DefaultStyles.Muted } - if bg := parseHex(transcriptInk.bg); bg != nil { + if bg := ParseHex(CurrentInk.bg); bg != nil { *c = legible(*c, *bg, languageLc) } - return lipgloss.NewStyle().Foreground(lipgloss.Color(c.hex())) + return lipgloss.NewStyle().Foreground(lipgloss.Color(c.Hex())) } // identityHues tell things apart that have no meaning of their own to show: // agents in the orchestrator view, hosts beside their paths. var identityHues = []string{"#e08cf5", "#6fd1c4", "#b6e37a", "#b9a6f5", "#80aaf9", "#f5a97f"} -// hostStyle colors a host label the same way every time, legible on the +// HostStyle colors a host label the same way every time, legible on the // terminal's background like a language's color. -func hostStyle(host string) lipgloss.Style { +func HostStyle(host string) lipgloss.Style { h := fnv.New32a() h.Write([]byte(host)) - c := parseHex(identityHues[h.Sum32()%uint32(len(identityHues))]) - if bg := parseHex(transcriptInk.bg); bg != nil { + c := ParseHex(identityHues[h.Sum32()%uint32(len(identityHues))]) + if bg := ParseHex(CurrentInk.bg); bg != nil { *c = legible(*c, *bg, languageLc) } - return lipgloss.NewStyle().Foreground(lipgloss.Color(c.hex())) + return lipgloss.NewStyle().Foreground(lipgloss.Color(c.Hex())) } // agentPalette colors the orchestrator view. Each agent keeps one identity // hue wherever it appears; structure and quiet text follow the terminal's // own ink like every other screen. type agentPalette struct { - hues []rgb - you, mail, faint, decor, hi rgb + Hues []RGB + You, Mail, Faint, Decor, Hi RGB } -func agentColors() agentPalette { - hex := func(val, fallback string) rgb { - if c := parseHex(val); c != nil { +var fallbackAgentColors = graphPalette(Ink{}) + +func AgentColors() *agentPalette { + if CurrentInk.agents != nil { + return CurrentInk.agents + } + return fallbackAgentColors +} + +func graphPalette(colors Ink) *agentPalette { + hex := func(val, fallback string) RGB { + if c := ParseHex(val); c != nil { return *c } - return *parseHex(fallback) + return *ParseHex(fallback) + } + bg := ParseHex(colors.bg) + readable := func(value string) RGB { + c := *ParseHex(value) + if bg != nil { + return legible(c, *bg, languageLc) + } + return c } - hues := make([]rgb, len(identityHues)) - for i, h := range identityHues { - hues[i] = *parseHex(h) + hues := make([]RGB, len(identityHues)) + for i, hue := range identityHues { + hues[i] = readable(hue) } - return agentPalette{ - hues: hues, - you: *parseHex("#7fd8e6"), - mail: *parseHex("#f0c674"), - faint: hex(transcriptInk.secondary, "#6a6378"), - decor: hex(transcriptInk.decor, "#3a3448"), - hi: *parseHex("#ffffff"), + return &agentPalette{ + Hues: hues, + You: readable("#7fd8e6"), + Mail: readable("#f0c674"), + Faint: hex(colors.Secondary, "#6a6378"), + Decor: hex(colors.Decor, "#3a3448"), + Hi: readable("#ffffff"), } } diff --git a/cli/internal/tui/clipboard_terminal_test.go b/cli/internal/tui/clipboard_terminal_test.go index 71bf1e1e1..634ef4141 100644 --- a/cli/internal/tui/clipboard_terminal_test.go +++ b/cli/internal/tui/clipboard_terminal_test.go @@ -9,6 +9,7 @@ import ( "testing" "albedo/cli/internal/daemon" + uv "github.com/charmbracelet/ultraviolet" ) @@ -58,13 +59,13 @@ func TestTerminalClipboardReadAnswers(t *testing.T) { t.Fatal(err) } for _, tc := range []struct { - name string style func(pending string) terminalStyle + name string wantImg bool }{ - {"echoed id", func(pending string) terminalStyle { return terminalStyle{id: pending, chunk: 4096} }, true}, - {"foot", func(string) terminalStyle { return terminalStyle{chunk: 4099, okPerMime: true} }, true}, - {"another client's id", func(string) terminalStyle { return terminalStyle{id: "someone-else", chunk: 4096} }, false}, + {name: "echoed id", style: func(pending string) terminalStyle { return terminalStyle{id: pending, chunk: 4096} }, wantImg: true}, + {name: "foot", style: func(string) terminalStyle { return terminalStyle{chunk: 4099, okPerMime: true} }, wantImg: true}, + {name: "another client's id", style: func(string) terminalStyle { return terminalStyle{id: "someone-else", chunk: 4096} }, wantImg: false}, } { t.Run(tc.name, func(t *testing.T) { m := newTestChatModel(t, &daemon.Session{ID: "s"}) diff --git a/cli/internal/tui/commands.go b/cli/internal/tui/commands.go index b98cf0629..b8378b96d 100644 --- a/cli/internal/tui/commands.go +++ b/cli/internal/tui/commands.go @@ -6,6 +6,8 @@ import ( "strings" "unicode/utf8" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -222,9 +224,9 @@ func (m CommandMenuModel) View(input string, cursor, width int) string { var b strings.Builder for i := start; i < end; i++ { cmd := matches[i] - desc := ansi.Truncate(cmd.Name+" "+DefaultStyles.Faint.Render(cmd.Description), max(0, width-2), "…") + desc := ansi.Truncate(cmd.Name+" "+chrome.DefaultStyles.Faint.Render(cmd.Description), max(0, width-2), "…") if i == idx { - b.WriteString(selectedLine(selectBar()+" "+desc, 0)) + b.WriteString(chrome.SelectedLine(chrome.SelectBar()+" "+desc, 0)) } else { b.WriteString(" ") b.WriteString(desc) diff --git a/cli/internal/tui/config_form.go b/cli/internal/tui/config_form.go index dfca68b56..236ff4c81 100644 --- a/cli/internal/tui/config_form.go +++ b/cli/internal/tui/config_form.go @@ -9,6 +9,8 @@ import ( "strconv" "strings" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -158,7 +160,7 @@ func (f *configForm) view(width int) []string { // declared label is cut here instead of pushing the row past the frame. const labelWidth = 16 f.fit(width - labelWidth - 3) - rows := []string{DefaultStyles.Bold.Render("edit " + f.Section + " · " + f.Setting.Key)} + rows := []string{chrome.DefaultStyles.Bold.Render("edit " + f.Section + " · " + f.Setting.Key)} for i, field := range f.fields() { label := map[string]string{configFieldName: "Name", configFieldValue: "Value"}[field] if f.Setting.Kind != daemon.SettingMap { @@ -166,7 +168,7 @@ func (f *configForm) view(width int) []string { } rows = append(rows, formRow(i == f.Focus, label, labelWidth, f.Inputs[field].View(), width)) } - return append(rows, DefaultStyles.Faint.Render(configContext(f.Setting))) + return append(rows, chrome.DefaultStyles.Faint.Render(configContext(f.Setting))) } // configContext is the line under the fields: what a map entry holds, or what diff --git a/cli/internal/tui/config_page.go b/cli/internal/tui/config_page.go index dc62c0219..29d67261a 100644 --- a/cli/internal/tui/config_page.go +++ b/cli/internal/tui/config_page.go @@ -3,6 +3,7 @@ package tui import ( "albedo/cli/internal/daemon" "albedo/cli/internal/daemon/protocol" + "albedo/cli/internal/terminalui" "cmp" "context" "encoding/json" @@ -12,6 +13,8 @@ import ( "slices" "strings" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -35,7 +38,7 @@ type ConfigPageModel struct { Sections []daemon.ExtensionSettingsSection ETag string places map[string]configPlace - confirm + confirm chrome.Confirm pageStatus listView // noticeWarns says the notice is a warning rather than a save that went through. @@ -70,8 +73,8 @@ func (p configPlace) key() string { type configLoadedMsg struct { UI daemon.UIPreferences - Settings daemon.ExtensionSettings Err error + Settings daemon.ExtensionSettings Gen int } @@ -131,7 +134,7 @@ func NewConfigPageModel(conn *daemon.Connection) ConfigPageModel { func (m *ConfigPageModel) SetSize(width, height int) { m.pageStatus.SetSize(width, height) - m.listView.setSize(width, height) + m.setSize(width, height) } func (m ConfigPageModel) Init() tea.Cmd { return m.loadCmd(m.Generation) } @@ -207,7 +210,7 @@ func (m ConfigPageModel) Update(msg tea.Msg) (ConfigPageModel, tea.Cmd) { switch { case m.Form != nil: return m.formKey(msg) - case m.asking(): + case m.confirm.Asking(): return m.confirmKey(msg) case msg.String() == "esc" || msg.String() == "ctrl+c": return m, func() tea.Msg { return ConfigPageDoneMsg{} } @@ -216,7 +219,7 @@ func (m ConfigPageModel) Update(msg tea.Msg) (ConfigPageModel, tea.Cmd) { } return m.listKey(msg) } - return m, m.listView.update(msg) + return m, m.update(msg) } // formKey routes keys to the open form; esc closes it without saving. A value @@ -263,7 +266,7 @@ func (m ConfigPageModel) listKey(msg tea.KeyPressMsg) (ConfigPageModel, tea.Cmd) case key == "ctrl+d": if ok && kind == daemon.SettingMap && place.entry != "" { m.Error = "" - m.ask("delete", place.entry, "delete", fmt.Sprintf("Delete %s from %s?", place.entry, place.setting.Label)) + m.confirm.Ask("delete", place.entry, "delete", fmt.Sprintf("Delete %s from %s?", place.entry, place.setting.Label)) } case (key == "left" || key == "right") && ok && kind == daemon.SettingChoices && place.entry != "": return m.pick(place, map[string]int{"left": -1, "right": 1}[key]) @@ -272,18 +275,18 @@ func (m ConfigPageModel) listKey(msg tea.KeyPressMsg) (ConfigPageModel, tea.Cmd) m.Generation = nextPageGeneration() return m, m.loadCmd(m.Generation) default: - return m, m.listView.update(msg) + return m, m.update(msg) } return m, nil } // confirmKey deletes the map entry the question asked about on enter. func (m ConfigPageModel) confirmKey(msg tea.KeyPressMsg) (ConfigPageModel, tea.Cmd) { - if !m.key(msg) { + if !m.confirm.Key(msg) { return m, nil } - entry := m.target - m.dismiss() + entry := m.confirm.Target + m.confirm.Dismiss() place, ok := m.current() if !ok || place.entry != entry { return m, nil @@ -463,11 +466,11 @@ func (m ConfigPageModel) placeEntry(place configPlace) listEntry { entry.name = " + " + configAddEntry case setting.Kind == daemon.SettingMap && place.entry != "": entry.name = " " + place.entry - entry.tag = DefaultStyles.Bold.Render(ansi.Truncate(setting.Saved.Map[place.entry], configTagWidth, "…")) + entry.tag = chrome.DefaultStyles.Bold.Render(ansi.Truncate(setting.Saved.Map[place.entry], configTagWidth, "…")) case place.entry != "": - style, pick := DefaultStyles.Bold, setting.Saved.Map[place.entry] + style, pick := chrome.DefaultStyles.Bold, setting.Saved.Map[place.entry] if pick == "" { - style, pick = DefaultStyles.Muted, place.unset + style, pick = chrome.DefaultStyles.Muted, place.unset } entry.name = " " + place.entry entry.tag, entry.selTag = style.Render(pick), style.Render("‹ "+pick+" ›") @@ -496,7 +499,7 @@ func (m ConfigPageModel) sectionEntry(section daemon.ExtensionSettingsSection) l // every row of that section. func (m ConfigPageModel) sectionProblem(entry listEntry, section daemon.ExtensionSettingsSection) listEntry { if section.Problem != "" { - entry.lead = DefaultStyles.Warning.Render("problem") + entry.lead = chrome.DefaultStyles.Warning.Render("problem") entry.desc = section.Problem } return entry @@ -506,9 +509,9 @@ func (m ConfigPageModel) sectionProblem(entry listEntry, section daemon.Extensio // default in muted style, the colour alone saying it is only the default. func configTag(setting daemon.ExtensionSetting) string { if setting.Saved.Set() { - return DefaultStyles.Bold.Render(ansi.Truncate(configValue(setting, setting.Saved), configTagWidth, "…")) + return chrome.DefaultStyles.Bold.Render(ansi.Truncate(configValue(setting, setting.Saved), configTagWidth, "…")) } - return DefaultStyles.Muted.Render(ansi.Truncate(configDefault(setting), configTagWidth, "…")) + return chrome.DefaultStyles.Muted.Render(ansi.Truncate(configDefault(setting), configTagWidth, "…")) } // settingDetails is the pane: what the setting is, what it takes, and what it @@ -558,23 +561,23 @@ func (m ConfigPageModel) sectionDetails(section daemon.ExtensionSettingsSection, } // hints are the keys this screen answers now for the highlighted row. -func (m ConfigPageModel) hints(place configPlace, ok bool) []hint { - hints := []hint{{"↑↓", "move"}} +func (m ConfigPageModel) hints(place configPlace, ok bool) []chrome.Hint { + hints := []chrome.Hint{{Key: "↑↓", Does: "move"}} switch kind := place.setting.Kind; { case !ok: case place.add: - hints = append(hints, hint{"enter", "add"}) + hints = append(hints, chrome.Hint{Key: "enter", Does: "add"}) case kind == daemon.SettingMap && place.entry != "": - hints = append(hints, hint{"enter", "edit"}, hint{"ctrl+d", "delete"}) + hints = append(hints, chrome.Hint{Key: "enter", Does: "edit"}, chrome.Hint{Key: "ctrl+d", Does: "delete"}) case kind == daemon.SettingChoices && place.entry != "": - hints = append(hints, hint{"←→", "pick"}) + hints = append(hints, chrome.Hint{Key: "←→", Does: "pick"}) case !place.inline(): - hints = append(hints, hint{"enter", "edit"}) + hints = append(hints, chrome.Hint{Key: "enter", Does: "edit"}) } if ok && place.field() && place.setting.Saved.Set() { - hints = append(hints, hint{"ctrl+x", "reset"}) + hints = append(hints, chrome.Hint{Key: "ctrl+x", Does: "reset"}) } - return append(hints, hint{"ctrl+r", "refresh"}, hint{"esc", "back"}) + return append(hints, chrome.Hint{Key: "ctrl+r", Does: "refresh"}, chrome.Hint{Key: "esc", Does: "back"}) } // status is the footer's one line: work in flight, the last refusal or @@ -585,34 +588,34 @@ func (m ConfigPageModel) status() (string, bool) { } switch { case m.Saving: - return DefaultStyles.Busy.Render("saving…"), true + return chrome.DefaultStyles.Busy.Render("saving…"), true case m.Loading: - return DefaultStyles.Faint.Render("loading…"), false + return chrome.DefaultStyles.Faint.Render("loading…"), false case m.Error != "": - return DefaultStyles.Error.Render(m.Error), true + return chrome.DefaultStyles.Error.Render(m.Error), true case m.Notice != "": return notice(m.Notice, m.noticeWarns), true } - return DefaultStyles.Faint.Render(counted(len(m.Sections), "section")), false + return chrome.DefaultStyles.Faint.Render(counted(len(m.Sections), "section")), false } func (m ConfigPageModel) footer(width int) string { status, urgent := m.status() switch { case m.Form != nil: - hints := []hint{{"enter", "save"}, {"ctrl+s", "save"}, {"esc", "cancel"}} + hints := []chrome.Hint{{Key: "enter", Does: "save"}, {Key: "ctrl+s", Does: "save"}, {Key: "esc", Does: "cancel"}} if m.Form.Setting.Kind == daemon.SettingMap { - hints = append([]hint{{"tab", "move"}}, hints...) + hints = append([]chrome.Hint{{Key: "tab", Does: "move"}}, hints...) } if m.Form.Setting.Kind == daemon.SettingMap && m.Form.Focus == 0 { - hints[1].does = "next" + hints[1].Does = "next" } - return footerLine(width, hints, status, urgent) - case m.asking(): - return m.confirm.footer(width, m.Error) + return chrome.FooterLine(width, hints, status, urgent) + case m.confirm.Asking(): + return m.confirm.Footer(width, m.Error) } place, ok := m.current() - return footerLine(width, m.hints(place, ok), status, urgent) + return chrome.FooterLine(width, m.hints(place, ok), status, urgent) } // summary is the highlighted row's place and rule, for a width too narrow for @@ -631,7 +634,7 @@ func (m ConfigPageModel) formList(width, height int) []string { return rows[:min(len(rows), height)] } -func (m ConfigPageModel) View() string { +func (m ConfigPageModel) Page() terminalui.Page { width := max(1, m.Width) lv := m.listView lv.Empty = "Nothing declares settings." @@ -641,11 +644,11 @@ func (m ConfigPageModel) View() string { case m.Error != "" && len(m.Sections) == 0: lv.Empty = "Could not load settings; the reason is in the footer." } - frame := lv.frame(brand("albedo")+" "+DefaultStyles.Muted.Render("/config"), "", m.footer(width)) + frame := lv.frame(chrome.Brand("albedo")+" "+chrome.DefaultStyles.Muted.Render("/config"), "", m.footer(width)) if m.Form != nil { - frame.filter, frame.pane, frame.list = "", nil, m.formList + frame.Filter, frame.Detail, frame.List = "", nil, m.formList } else { - frame.summary = m.summary() + frame.Summary = m.summary() } - return frame.view(m.Width, m.Height) + return frame } diff --git a/cli/internal/tui/confirm.go b/cli/internal/tui/confirm.go deleted file mode 100644 index 214756f4a..000000000 --- a/cli/internal/tui/confirm.go +++ /dev/null @@ -1,55 +0,0 @@ -package tui - -import ( - "strings" - - tea "charm.land/bubbletea/v2" - "github.com/charmbracelet/x/ansi" -) - -// confirm is the one way a screen asks before something far-reaching: -// enter does it, esc leaves it, and every other key is ignored, so a stray -// press while you read the question changes nothing. -type confirm struct { - prompt string // what will happen, and the question - verb string // what enter does, in the hint - what string // which action this asks about; the screen dispatches on it - target string // what the action applies to - failed bool // the last attempt failed, so enter retries -} - -func (c confirm) asking() bool { return c.prompt != "" } - -func (c *confirm) ask(what, target, verb, prompt string) { - *c = confirm{prompt: prompt, verb: verb, what: what, target: target} -} - -func (c *confirm) dismiss() { *c = confirm{} } - -// key settles a key press while asking: yes on enter, dismissed on esc, -// and ignored otherwise. It reports whether the key was for the question. -func (c *confirm) key(msg tea.KeyPressMsg) (yes bool) { - switch msg.String() { - case "enter": - return true - case "esc", "ctrl+c": - c.dismiss() - } - return false -} - -// footer is the question, the last failure if there was one, and the keys. -func (c confirm) footer(width int, failure string) string { - var rows []string - for line := range strings.SplitSeq(ansi.Wrap(c.prompt, max(1, width-1), " "), "\n") { - rows = append(rows, " "+DefaultStyles.Warning.Render(line)) - } - if failure != "" { - rows = append(rows, " "+DefaultStyles.Error.Render(ansi.Truncate(failure, max(1, width-1), "…"))) - } - verb := c.verb - if c.failed || failure != "" { - verb = "retry" - } - return strings.Join(append(rows, " "+keyHints(hint{"enter", verb}, hint{"esc", "cancel"})), "\n") -} diff --git a/cli/internal/tui/context_inspector.go b/cli/internal/tui/context_inspector.go index 4ecbea4a1..4723a5cdf 100644 --- a/cli/internal/tui/context_inspector.go +++ b/cli/internal/tui/context_inspector.go @@ -2,6 +2,7 @@ package tui import ( "albedo/cli/internal/daemon" + "albedo/cli/internal/terminalui" "cmp" "context" "errors" @@ -9,6 +10,8 @@ import ( "slices" "strings" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" "golang.org/x/text/language" @@ -18,18 +21,18 @@ import ( // ContextDetail is one section's content, read a page at a time and scrolled // line by line. type ContextDetail struct { - Value *daemon.ContextPage - Error string + Value *daemon.ContextPage + wrappedFrom *daemon.ContextPage + Error string + // wrapped is wrappedFrom's content at wrappedWidth, kept because every + // scroll step reads it and a page can be long. + wrapped []string Section daemon.ContextSection Page int Scroll int // visible is the body rows the last frame drew; page jumps move by it. - visible int - // wrapped is wrappedFrom's content at wrappedWidth, kept because every - // scroll step reads it and a page can be long. - wrapped []string + visible int wrappedWidth int - wrappedFrom *daemon.ContextPage } // rows is the page's content wrapped to width. @@ -52,16 +55,16 @@ func (d *ContextDetail) scroll(by int) { // from, any warning, then the scrolled rows. func (d *ContextDetail) list(width, height int) []string { sec := d.Section - head := []string{DefaultStyles.Faint.Render(fmt.Sprintf("%s · page %d/%d · %s", sec.Source, d.Page+1, sec.Pages, contextCount(sec.ByteCount, "byte")))} + head := []string{chrome.DefaultStyles.Faint.Render(fmt.Sprintf("%s · page %d/%d · %s", sec.Source, d.Page+1, sec.Pages, contextCount(sec.ByteCount, "byte")))} var rows []string switch { case d.Error != "": - head = append(head, DefaultStyles.Error.Render(d.Error)) + head = append(head, chrome.DefaultStyles.Error.Render(d.Error)) case d.Value == nil: - head = append(head, DefaultStyles.Faint.Render("loading inspectable prepared content…")) + head = append(head, chrome.DefaultStyles.Faint.Render("loading inspectable prepared content…")) default: if d.Value.Omitted != "" { - head = append(head, DefaultStyles.Warning.Render("omitted: "+d.Value.Omitted)) + head = append(head, chrome.DefaultStyles.Warning.Render("omitted: "+d.Value.Omitted)) } head = append(head, "") rows = d.rows(max(1, width-2)) @@ -121,7 +124,7 @@ func NewContextInspectorModel(conn *daemon.Connection, sessionID string) Context func (m *ContextInspectorModel) SetSize(width, height int) { m.pageStatus.SetSize(width, height) - m.listView.setSize(width, height) + m.setSize(width, height) } func (m ContextInspectorModel) Init() tea.Cmd { @@ -194,13 +197,13 @@ func (m *ContextInspectorModel) setSections() { } func sectionEntry(i int, sec daemon.ContextSection) listEntry { - tag := DefaultStyles.Faint.Render("no content") + tag := chrome.DefaultStyles.Faint.Render("no content") if sec.Pages > 0 { - tag = DefaultStyles.Muted.Render(contextCount(sec.Pages, "page")) + tag = chrome.DefaultStyles.Muted.Render(contextCount(sec.Pages, "page")) } return listEntry{ key: sec.ID, - lead: DefaultStyles.Faint.Render(fmt.Sprintf("%d.", i+1)), + lead: chrome.DefaultStyles.Faint.Render(fmt.Sprintf("%d.", i+1)), name: sec.Label, desc: sec.Source, tag: tag, @@ -343,7 +346,7 @@ func (m ContextInspectorModel) list(width, height int) []string { head = nil } for i := range head { - head[i] = svFit(" "+head[i], width) + head[i] = chrome.Fit(" "+head[i], width) } lv := m.listView lv.Empty = m.emptyText() @@ -351,23 +354,23 @@ func (m ContextInspectorModel) list(width, height int) []string { } func (m ContextInspectorModel) footer(width int) string { - hints := []hint{{"↑↓", "move"}, {"enter", "inspect"}, {"ctrl+r", "refresh"}, {"esc", "back"}} + hints := []chrome.Hint{{Key: "↑↓", Does: "move"}, {Key: "enter", Does: "inspect"}, {Key: "ctrl+r", Does: "refresh"}, {Key: "esc", Does: "back"}} var status string urgent := true switch { case m.Error != "": - status = DefaultStyles.Error.Render(m.Error) + status = chrome.DefaultStyles.Error.Render(m.Error) case m.Loading: - status, urgent = DefaultStyles.Faint.Render("loading…"), false + status, urgent = chrome.DefaultStyles.Faint.Render("loading…"), false case m.Snapshot != nil: - status, urgent = DefaultStyles.Faint.Render(counted(len(m.Snapshot.Sections), "section")), false + status, urgent = chrome.DefaultStyles.Faint.Render(counted(len(m.Snapshot.Sections), "section")), false } - return footerLine(width, hints, status, urgent) + return chrome.FooterLine(width, hints, status, urgent) } // readerFooter is the footer while a section's content is open. func readerFooter(width int) string { - return footerLine(width, []hint{{"↑↓", "scroll"}, {"pgup/pgdn", "jump"}, {"←→", "page"}, {"esc", "sections"}}, "", false) + return chrome.FooterLine(width, []chrome.Hint{{Key: "↑↓", Does: "scroll"}, {Key: "pgup/pgdn", Does: "jump"}, {Key: "←→", Does: "page"}, {Key: "esc", Does: "sections"}}, "", false) } func (m ContextInspectorModel) Update(msg tea.Msg) (ContextInspectorModel, tea.Cmd) { @@ -397,7 +400,7 @@ func (m ContextInspectorModel) Update(msg tea.Msg) (ContextInspectorModel, tea.C } return m.sectionsKey(msg) } - cmd := m.listView.update(msg) + cmd := m.update(msg) return m, cmd } @@ -448,7 +451,7 @@ func (m ContextInspectorModel) sectionsKey(msg tea.KeyPressMsg) (ContextInspecto m.Generation = nextPageGeneration() return m, m.loadSnapshotCmd(m.Generation) } - cmd := m.listView.update(msg) + cmd := m.update(msg) return m, cmd } @@ -469,22 +472,22 @@ func contextCount(n int, unit string) string { } // reader is the section's content as a list with no filter and no pane. -func (m ContextInspectorModel) reader() listFrame { - title := brand("albedo") + " " + DefaultStyles.Muted.Render("/context") - return listFrame{ - title: title, - right: DefaultStyles.Faint.Render(m.Detail.Section.Label), - list: m.Detail.list, - footer: readerFooter(max(1, m.Width)), +func (m ContextInspectorModel) reader() terminalui.Page { + title := chrome.Brand("albedo") + " " + chrome.DefaultStyles.Muted.Render("/context") + return terminalui.Page{ + Title: title, + Meta: chrome.DefaultStyles.Faint.Render(m.Detail.Section.Label), + List: m.Detail.list, + Footer: readerFooter(max(1, m.Width)), } } -func (m ContextInspectorModel) View() string { +func (m ContextInspectorModel) Page() terminalui.Page { if m.Detail != nil { - return m.reader().view(m.Width, m.Height) + return m.reader() } - title := brand("albedo") + " " + DefaultStyles.Muted.Render("/context") - f := m.listView.frame(title, DefaultStyles.Faint.Render("prepared request"), m.footer(max(1, m.Width))) - f.list = m.list - return f.view(m.Width, m.Height) + title := chrome.Brand("albedo") + " " + chrome.DefaultStyles.Muted.Render("/context") + f := m.frame(title, chrome.DefaultStyles.Faint.Render("prepared request"), m.footer(max(1, m.Width))) + f.List = m.list + return f } diff --git a/cli/internal/tui/discord_form.go b/cli/internal/tui/discord_form.go index 49aeb7137..472c9e71b 100644 --- a/cli/internal/tui/discord_form.go +++ b/cli/internal/tui/discord_form.go @@ -8,6 +8,8 @@ import ( "strings" "unicode/utf8" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" ) @@ -118,13 +120,13 @@ func (f *discordForm) view(width int) []string { title = "edit " + f.Editing.Name } f.fit(width - 17) - rows := []string{DefaultStyles.Bold.Render(title)} + rows := []string{chrome.DefaultStyles.Bold.Render(title)} indent := strings.Repeat(" ", 16) for i, key := range discordFields { value := f.Inputs[key].View() switch { case key == discordFieldSession && f.Editing != nil: - value = DefaultStyles.Faint.Render(f.label()) + value = chrome.DefaultStyles.Faint.Render(f.label()) case key == discordFieldSession && i != f.Focus: value = f.label() } @@ -136,7 +138,7 @@ func (f *discordForm) view(width int) []string { rows = append(rows, f.rows(f.Inputs[discordFieldSession].Value(), indent, width)...) } for _, line := range svWrap(f.help(), max(1, width-len(indent)), 3) { - rows = append(rows, indent+DefaultStyles.Faint.Render(line)) + rows = append(rows, indent+chrome.DefaultStyles.Faint.Render(line)) } } return rows @@ -160,13 +162,13 @@ func (f *discordForm) help() string { // footer offers the keys every form shares, and ←→ on the session picker. func (f *discordForm) footer(width int) string { - var own []hint + var own []chrome.Hint if f.current() == discordFieldSession && f.Editing == nil { - own = []hint{{"←→", "choose"}} + own = []chrome.Hint{{Key: "←→", Does: "choose"}} } - keys := append(own, hint{"ctrl+s", "save"}) - keys = append(keys, hint{"enter", "next"}, hint{"tab/↑↓", "move"}, hint{"esc", "cancel"}) - return footerLine(width, keys, "", false) + keys := append(own, chrome.Hint{Key: "ctrl+s", Does: "save"}) + keys = append(keys, chrome.Hint{Key: "enter", Does: "next"}, chrome.Hint{Key: "tab/↑↓", Does: "move"}, chrome.Hint{Key: "esc", Does: "cancel"}) + return chrome.FooterLine(width, keys, "", false) } // discordPersonForm lets one more person DM the bot: their user ID, and a @@ -209,20 +211,20 @@ func (f *discordPersonForm) person() (id, name string, err error) { func (f *discordPersonForm) view(width int) []string { f.fit(width - 17) - rows := []string{DefaultStyles.Bold.Render("let someone DM this bot")} + rows := []string{chrome.DefaultStyles.Bold.Render("let someone DM this bot")} for i, key := range personFields { rows = append(rows, formRow(i == f.Focus, discordFieldLabels[key], 14, f.Inputs[key].View(), width)) } note := "Turn on Developer Mode in Discord (Settings → Advanced), right-click them → Copy User ID." rows = append(rows, "") for _, line := range svWrap(note, max(1, width-2), 3) { - rows = append(rows, " "+DefaultStyles.Faint.Render(line)) + rows = append(rows, " "+chrome.DefaultStyles.Faint.Render(line)) } return rows } func (f *discordPersonForm) footer(width int) string { - return footerLine(width, []hint{{"ctrl+s", "allow"}, {"enter", "next"}, {"tab/↑↓", "move"}, {"esc", "cancel"}}, "", false) + return chrome.FooterLine(width, []chrome.Hint{{Key: "ctrl+s", Does: "allow"}, {Key: "enter", Does: "next"}, {Key: "tab/↑↓", Does: "move"}, {Key: "esc", Does: "cancel"}}, "", false) } func validDiscordName(name string) bool { diff --git a/cli/internal/tui/discord_page.go b/cli/internal/tui/discord_page.go index 11d3dedec..a950f5377 100644 --- a/cli/internal/tui/discord_page.go +++ b/cli/internal/tui/discord_page.go @@ -9,6 +9,8 @@ import ( "slices" "time" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" ) @@ -18,24 +20,32 @@ import ( // screen polls while it is open. type DiscordPageModel struct { Conn *daemon.Connection - SessionID string - Sessions []daemon.Session - Bots []daemon.DiscordBot Form *discordForm Person *discordPersonForm + now func() time.Time + SessionID string // Open is the bot whose channels or DMs are shown; empty for the list. - Open string - Tab discordTab + Open string + GuildsErr string + // pollErr is the last failure a background refresh showed, so the next + // good one can clear it. + pollErr string + // selected is the bot to put the cursor on once it is listed. + selected string + DMs daemon.DiscordDMs + confirm chrome.Confirm + Sessions []daemon.Session + Bots []daemon.DiscordBot // Guilds are the open bot's servers, read from the running bot; // GuildsErr says why they could not be, usually that it is offline. - Guilds []daemon.DiscordGuild - GuildsErr string - DMs daemon.DiscordDMs + Guilds []daemon.DiscordGuild // inner is the open bot's channels or DMs, with its own filter. inner listView - pageStatus listView - confirm + pageStatus + Tab discordTab + // ticker tells this screen's poll ticks from an earlier one's. + ticker int // Mounted reports the extension on globally; its API exists only then. Mounted bool // SessionOff reports the extension off for this session, whose agent @@ -44,15 +54,6 @@ type DiscordPageModel struct { Loaded bool // Missing reports a daemon without the extension at all. Missing bool - // pollErr is the last failure a background refresh showed, so the next - // good one can clear it. - pollErr string - // ticker tells this screen's poll ticks from an earlier one's. - ticker int - now func() time.Time - - // selected is the bot to put the cursor on once it is listed. - selected string } type discordTab int @@ -64,11 +65,11 @@ const ( type discordLoadedMsg struct { Err error + GuildsErr error + DMs *daemon.DiscordDMs Sessions []daemon.Session Bots []daemon.DiscordBot Guilds []daemon.DiscordGuild - GuildsErr error - DMs *daemon.DiscordDMs Gen int Quiet bool Mounted bool @@ -106,12 +107,12 @@ func NewDiscordPageModel(conn *daemon.Connection, sessionID string) DiscordPageM func (m *DiscordPageModel) SetSize(width, height int) { m.pageStatus.SetSize(width, height) - m.listView.setSize(width, height) + m.setSize(width, height) m.inner.setSize(width, height) } // Confirming reports a question waiting for enter or esc. -func (m DiscordPageModel) Confirming() bool { return m.confirm.asking() } +func (m DiscordPageModel) Confirming() bool { return m.confirm.Asking() } func (m DiscordPageModel) Init() tea.Cmd { return tea.Batch(m.loadCmd(m.Generation, false), m.tick()) @@ -150,9 +151,9 @@ func (m DiscordPageModel) loadCmd(gen int, quiet bool) tea.Cmd { return msg } if !quiet { - all, err := daemon.ListAllSessions(ctx, conn) - if err != nil { - msg.Err = err + all, listErr := daemon.ListAllSessions(ctx, conn) + if listErr != nil { + msg.Err = listErr return msg } for _, s := range all { @@ -370,7 +371,7 @@ func (m DiscordPageModel) handleKey(msg tea.KeyPressMsg) (DiscordPageModel, tea. return m.formKey(msg) case m.Person != nil: return m.personKey(msg) - case m.confirm.asking(): + case m.confirm.Asking(): return m.confirmKey(msg) case (key == "esc" || key == "ctrl+c") && m.Open != "": m.Open, m.Guilds, m.GuildsErr, m.Error, m.Notice = "", nil, "", "", "" @@ -459,11 +460,11 @@ func (m DiscordPageModel) personKey(msg tea.KeyPressMsg) (DiscordPageModel, tea. // confirmKey runs the change a question asked about on enter; esc cancels and // every other key is ignored. func (m DiscordPageModel) confirmKey(msg tea.KeyPressMsg) (DiscordPageModel, tea.Cmd) { - if !m.confirm.key(msg) { + if !m.confirm.Key(msg) { return m, nil } - what, target := m.confirm.what, m.confirm.target - m.confirm.dismiss() + what, target := m.confirm.What, m.confirm.Target + m.confirm.Dismiss() switch what { case "delete": bot, ok := m.bot(target) @@ -506,7 +507,7 @@ func (m DiscordPageModel) browseKey(msg tea.KeyPressMsg) (DiscordPageModel, tea. case "ctrl+d", "ctrl+x": if selected { m.Error = "" - m.confirm.ask("delete", bot.ID, "delete", "The bot goes offline and forgets its channels and DM list; the Discord application stays. Delete "+bot.Name+"?") + m.confirm.Ask("delete", bot.ID, "delete", "The bot goes offline and forgets its channels and DM list; the Discord application stays. Delete "+bot.Name+"?") } case "ctrl+t": if selected { @@ -517,7 +518,7 @@ func (m DiscordPageModel) browseKey(msg tea.KeyPressMsg) (DiscordPageModel, tea. return m.copyInvite(bot) } default: - cmd := m.listView.update(msg) + cmd := m.update(msg) return m, cmd } return m, nil @@ -632,7 +633,7 @@ func (m DiscordPageModel) dmKey(msg tea.KeyPressMsg) (DiscordPageModel, tea.Cmd) }) case selected && kind == "allowed": m.Error = "" - m.confirm.ask("remove", user, "remove", "They will no longer reach the session by DM. Remove "+row.name+"?") + m.confirm.Ask("remove", user, "remove", "They will no longer reach the session by DM. Remove "+row.name+"?") } return m, nil } diff --git a/cli/internal/tui/discord_render.go b/cli/internal/tui/discord_render.go index 34d8bbb52..b92ca7dda 100644 --- a/cli/internal/tui/discord_render.go +++ b/cli/internal/tui/discord_render.go @@ -2,25 +2,28 @@ package tui import ( "albedo/cli/internal/daemon" + "albedo/cli/internal/terminalui" "cmp" "fmt" "slices" "strings" "time" + "albedo/cli/internal/tui/chrome" + "charm.land/lipgloss/v2" "github.com/charmbracelet/x/ansi" ) -// View draws the bot list beside the highlighted bot, or the open bot's +// Page draws the bot list beside the highlighted bot, or the open bot's // channels or DMs beside the highlighted one. A form takes the list's place, // and a question takes the footer. -func (m DiscordPageModel) View() string { - title := brand("albedo") + " " + DefaultStyles.Muted.Render("/discord") - lv, right := m.listView, DefaultStyles.Faint.Render("all sessions") +func (m DiscordPageModel) Page() terminalui.Page { + title := chrome.Brand("albedo") + " " + chrome.DefaultStyles.Muted.Render("/discord") + lv, right := m.listView, chrome.DefaultStyles.Faint.Render("all sessions") bot, open := m.bot(m.Open) if open { - title += DefaultStyles.Muted.Render(" › " + bot.Name) + title += chrome.DefaultStyles.Muted.Render(" › " + bot.Name) lv, right = m.inner, m.tabs() lv.Empty = m.innerEmpty(bot) } else { @@ -29,17 +32,17 @@ func (m DiscordPageModel) View() string { frame := lv.frame(title, right, m.footer(max(1, m.Width))) switch { case m.Form != nil: - frame.filter, frame.pane = "", nil - frame.list = func(width, height int) []string { return inset(scrolled(m.Form.view(width-1), 1+m.Form.Focus, height)) } + frame.Filter, frame.Detail = "", nil + frame.List = func(width, height int) []string { return inset(scrolled(m.Form.view(width-1), 1+m.Form.Focus, height)) } case m.Person != nil: - frame.filter, frame.pane = "", nil - frame.list = func(width, height int) []string { return inset(m.Person.view(width - 1)) } + frame.Filter, frame.Detail = "", nil + frame.List = func(width, height int) []string { return inset(m.Person.view(width - 1)) } case !m.Loaded || !m.Mounted || (!open && len(m.Bots) == 0): - frame.filter, frame.pane = "", nil - frame.list = func(width, _ int) []string { return m.guide(width) } + frame.Filter, frame.Detail = "", nil + frame.List = func(width, _ int) []string { return m.guide(width) } case open: - list := frame.list - frame.list = func(width, height int) []string { + list := frame.List + frame.List = func(width, height int) []string { head := m.statusRows(bot, width) if height < len(head)+3 { return list(width, height) @@ -47,7 +50,7 @@ func (m DiscordPageModel) View() string { return append(head, list(width, height-len(head))...) } } - return frame.view(m.Width, m.Height) + return frame } // tabs is the open bot's two lists, the shown one bright. @@ -62,22 +65,22 @@ func (m DiscordPageModel) tabs() string { } names := []string{fmt.Sprintf("channels %d", channels), fmt.Sprintf("dms %d", 1+len(m.DMs.Allowed))} if n := len(m.DMs.Requests); n > 0 { - names[1] += DefaultStyles.Warning.Render(fmt.Sprintf(" +%d", n)) + names[1] += chrome.DefaultStyles.Warning.Render(fmt.Sprintf(" +%d", n)) } for i := range names { if discordTab(i) == m.Tab { - names[i] = DefaultStyles.Bold.Render(names[i]) + names[i] = chrome.DefaultStyles.Bold.Render(names[i]) } else { - names[i] = DefaultStyles.Faint.Render(names[i]) + names[i] = chrome.DefaultStyles.Faint.Render(names[i]) } } - return names[0] + DefaultStyles.Decor.Render(" │ ") + names[1] + return names[0] + chrome.DefaultStyles.Decor.Render(" │ ") + names[1] } // guide stands in for the list while there is nothing to list: loading, // a failed load, the extension off, or no bots yet. func (m DiscordPageModel) guide(width int) []string { - faint := DefaultStyles.Faint.Render + faint := chrome.DefaultStyles.Faint.Render switch { case m.Loading && !m.Loaded: return []string{faint(" loading discord bots…")} @@ -85,20 +88,20 @@ func (m DiscordPageModel) guide(width int) []string { return []string{faint(" discord bots did not load · ctrl+r retries")} case m.Missing: return slices.Concat( - guideText(width, DefaultStyles.Bold, "This daemon has no discord extension."), - guideText(width, DefaultStyles.Faint, "Update albedo, restart the daemon, and come back."), + guideText(width, chrome.DefaultStyles.Bold, "This daemon has no discord extension."), + guideText(width, chrome.DefaultStyles.Faint, "Update albedo, restart the daemon, and come back."), ) case !m.Mounted: return slices.Concat( - guideText(width, DefaultStyles.Bold, "Discord bots are off."), + guideText(width, chrome.DefaultStyles.Bold, "Discord bots are off."), []string{""}, guideText(width, lipgloss.NewStyle(), "Open /extensions, select discord and press enter to turn it on for every session."), - guideText(width, DefaultStyles.Faint, "Bots connect as soon as it is on; come back here to add one."), + guideText(width, chrome.DefaultStyles.Faint, "Bots connect as soon as it is on; come back here to add one."), ) } rows := slices.Concat( - guideText(width, DefaultStyles.Bold, "Give a session its own Discord bot"), - guideText(width, DefaultStyles.Faint, "It reads the channels you pick and DMs from people you allow, and replies as the session."), + guideText(width, chrome.DefaultStyles.Bold, "Give a session its own Discord bot"), + guideText(width, chrome.DefaultStyles.Faint, "It reads the channels you pick and DMs from people you allow, and replies as the session."), []string{""}, ) rows = append(rows, guideStep(width, "1", "Create the bot in Discord", "discord.com/developers/applications → New Application → Bot → Reset Token, and turn on Message Content Intent on the same page.")...) @@ -131,19 +134,19 @@ func (m DiscordPageModel) innerEmpty(bot daemon.DiscordBot) string { // statusRows head the open bot's lists: its state, and its invite link. func (m DiscordPageModel) statusRows(bot daemon.DiscordBot, width int) []string { lead, state := botState(bot) - invite := DefaultStyles.Faint.Render("invite ") + bot.Invite + DefaultStyles.Faint.Render(" ctrl+l copies") + invite := chrome.DefaultStyles.Faint.Render("invite ") + bot.Invite + chrome.DefaultStyles.Faint.Render(" ctrl+l copies") if bot.Invite == "" { - invite = DefaultStyles.Faint.Render("invite appears once the bot has connected") + invite = chrome.DefaultStyles.Faint.Render("invite appears once the bot has connected") } rows := []string{" " + lead + " " + state} if bot.State == "failed" && bot.Detail != "" { for _, l := range svWrap(bot.Detail, max(1, width-6), 2) { - rows = append(rows, " "+DefaultStyles.Error.Render(l)) + rows = append(rows, " "+chrome.DefaultStyles.Error.Render(l)) } } rows = append(rows, " "+invite, "") for i, row := range rows { - rows[i] = svFit(row, width) + rows[i] = chrome.Fit(row, width) } return rows } @@ -156,15 +159,15 @@ func botState(bot daemon.DiscordBot) (string, string) { } switch bot.State { case "online": - return DefaultStyles.Success.Render("●"), "online" + as + return chrome.DefaultStyles.Success.Render("●"), "online" + as case "connecting": - return DefaultStyles.Busy.Render("◌"), "connecting…" + return chrome.DefaultStyles.Busy.Render("◌"), "connecting…" case "reconnecting": - return DefaultStyles.Warning.Render("◌"), "reconnecting" + cmp.Or(prefixed(" · ", bot.Detail), "…") + return chrome.DefaultStyles.Warning.Render("◌"), "reconnecting" + cmp.Or(prefixed(" · ", bot.Detail), "…") case "failed": - return DefaultStyles.Error.Render("●"), "failed" + return chrome.DefaultStyles.Error.Render("●"), "failed" } - return DefaultStyles.Faint.Render("○"), "off" + return chrome.DefaultStyles.Faint.Render("○"), "off" } func prefixed(prefix, text string) string { @@ -181,72 +184,72 @@ func (m DiscordPageModel) footer(width int) string { return m.formFooter(width, m.Form.footer(width)) case m.Person != nil: return m.formFooter(width, m.Person.footer(width)) - case m.confirm.asking(): - return m.confirm.footer(width, m.Error) + case m.confirm.Asking(): + return m.confirm.Footer(width, m.Error) } status, urgent := m.status() - return footerLine(width, m.hints(), status, urgent) + return chrome.FooterLine(width, m.hints(), status, urgent) } // status is the footer's state beside the keys. func (m DiscordPageModel) status() (string, bool) { switch { case m.Error != "": - return DefaultStyles.Error.Render(m.Error), true + return chrome.DefaultStyles.Error.Render(m.Error), true case m.Saving: - return DefaultStyles.Busy.Render("saving…"), true + return chrome.DefaultStyles.Busy.Render("saving…"), true case m.Loading: - return DefaultStyles.Faint.Render("loading…"), false + return chrome.DefaultStyles.Faint.Render("loading…"), false case m.Notice != "": - return DefaultStyles.Success.Render(m.Notice), true + return chrome.DefaultStyles.Success.Render(m.Notice), true case m.SessionOff && m.Mounted: - return DefaultStyles.Warning.Render("discord is off for this session · /extensions"), false + return chrome.DefaultStyles.Warning.Render("discord is off for this session · /extensions"), false } return "", false } // hints are the keys of what is shown, the row's main action first. -func (m DiscordPageModel) hints() []hint { +func (m DiscordPageModel) hints() []chrome.Hint { switch { case !m.Loaded || !m.Mounted: - return []hint{{"ctrl+r", "retry"}, {"esc", "back"}} + return []chrome.Hint{{Key: "ctrl+r", Does: "retry"}, {Key: "esc", Does: "back"}} case m.Open != "" && m.Tab == discordDMs: row, selected := m.inner.highlighted() kind, _ := dmRowKind(row.key) - var hints []hint + var hints []chrome.Hint switch { case selected && kind == "request": - hints = append(hints, hint{"enter", "allow"}, hint{"ctrl+x", "dismiss"}) + hints = append(hints, chrome.Hint{Key: "enter", Does: "allow"}, chrome.Hint{Key: "ctrl+x", Does: "dismiss"}) case selected && kind == "allowed": - hints = append(hints, hint{"ctrl+x", "remove"}) + hints = append(hints, chrome.Hint{Key: "ctrl+x", Does: "remove"}) } - return append(hints, hint{"ctrl+o", "add person"}, hint{"tab", "channels"}, hint{"ctrl+l", "copy invite"}, hint{"ctrl+e", "edit bot"}, hint{"ctrl+r", "refresh"}, hint{"esc", "bots"}) + return append(hints, chrome.Hint{Key: "ctrl+o", Does: "add person"}, chrome.Hint{Key: "tab", Does: "channels"}, chrome.Hint{Key: "ctrl+l", Does: "copy invite"}, chrome.Hint{Key: "ctrl+e", Does: "edit bot"}, chrome.Hint{Key: "ctrl+r", Does: "refresh"}, chrome.Hint{Key: "esc", Does: "bots"}) case m.Open != "": - var hints []hint + var hints []chrome.Hint if _, selected := m.inner.highlighted(); selected { - hints = append(hints, hint{"space", "delivery"}, hint{"ctrl+t", "mentions only"}) + hints = append(hints, chrome.Hint{Key: "space", Does: "delivery"}, chrome.Hint{Key: "ctrl+t", Does: "mentions only"}) } - return append(hints, hint{"tab", "dms"}, hint{"ctrl+l", "copy invite"}, hint{"ctrl+e", "edit bot"}, hint{"ctrl+r", "refresh"}, hint{"esc", "bots"}) + return append(hints, chrome.Hint{Key: "tab", Does: "dms"}, chrome.Hint{Key: "ctrl+l", Does: "copy invite"}, chrome.Hint{Key: "ctrl+e", Does: "edit bot"}, chrome.Hint{Key: "ctrl+r", Does: "refresh"}, chrome.Hint{Key: "esc", Does: "bots"}) } bot, selected := m.current() - var hints []hint + var hints []chrome.Hint if selected { - hints = append(hints, hint{"enter", "channels & dms"}, hint{"ctrl+l", "copy invite"}) + hints = append(hints, chrome.Hint{Key: "enter", Does: "channels & dms"}, chrome.Hint{Key: "ctrl+l", Does: "copy invite"}) } - hints = append(hints, hint{"ctrl+o", "add bot"}) + hints = append(hints, chrome.Hint{Key: "ctrl+o", Does: "add bot"}) if selected { - hints = append(hints, hint{"ctrl+t", "turn " + onOff(!bot.Enabled)}, hint{"ctrl+e", "edit"}, hint{"ctrl+x", "delete"}) + hints = append(hints, chrome.Hint{Key: "ctrl+t", Does: "turn " + onOff(!bot.Enabled)}, chrome.Hint{Key: "ctrl+e", Does: "edit"}, chrome.Hint{Key: "ctrl+x", Does: "delete"}) } - return append(hints, hint{"ctrl+r", "refresh"}, hint{"esc", "back"}) + return append(hints, chrome.Hint{Key: "ctrl+r", Does: "refresh"}, chrome.Hint{Key: "esc", Does: "back"}) } // formFooter is a form's keys, with a failure or the save in flight above them. func (m DiscordPageModel) formFooter(width int, line string) string { switch { case m.Error != "": - return footerLine(width, nil, DefaultStyles.Error.Render(m.Error), true) + "\n" + line + return chrome.FooterLine(width, nil, chrome.DefaultStyles.Error.Render(m.Error), true) + "\n" + line case m.Saving: - return footerLine(width, nil, DefaultStyles.Busy.Render("saving…"), true) + "\n" + line + return chrome.FooterLine(width, nil, chrome.DefaultStyles.Busy.Render("saving…"), true) + "\n" + line } return line } @@ -262,9 +265,9 @@ func (m DiscordPageModel) botEntry(bot daemon.DiscordBot) listEntry { tag := "" switch { case bot.Requests > 0: - tag = DefaultStyles.Warning.Render(plural(bot.Requests, "DM request")) + tag = chrome.DefaultStyles.Warning.Render(plural(bot.Requests, "DM request")) case bot.State == "failed": - tag = DefaultStyles.Error.Render("failed") + tag = chrome.DefaultStyles.Error.Render("failed") } section := sessionLabel(m.Sessions, bot.SessionID, m.SessionID) return listEntry{ @@ -281,7 +284,7 @@ func (m DiscordPageModel) botDetails(bot daemon.DiscordBot, width int) []string lines := paneTitle(bot.Name, state, width) if bot.State == "failed" || bot.State == "reconnecting" { for _, l := range svWrap(cmp.Or(bot.Detail, "no reason given"), width, 4) { - lines = append(lines, DefaultStyles.Error.Render(l)) + lines = append(lines, chrome.DefaultStyles.Error.Render(l)) } lines = append(lines, "") } @@ -336,7 +339,7 @@ func (m DiscordPageModel) channelEntry(g daemon.DiscordGuild, section, category desc := map[int]string{2: "voice chat", 5: "announcements", 15: "forum"}[c.Type] tag := "" if c.MentionsOnly && c.Delivery != "off" { - tag = DefaultStyles.Muted.Render("@mentions only") + tag = chrome.DefaultStyles.Muted.Render("@mentions only") } return listEntry{ key: c.ID, section: section, lead: deliveryBadge(c.Delivery), name: "#" + c.Name, desc: desc, tag: tag, @@ -349,11 +352,11 @@ func (m DiscordPageModel) channelEntry(g daemon.DiscordGuild, section, category func deliveryBadge(delivery string) string { switch delivery { case "turn": - return DefaultStyles.Success.Render("end of turn") + return chrome.DefaultStyles.Success.Render("end of turn") case "tool": - return DefaultStyles.Prompt.Render("after tool") + return chrome.DefaultStyles.Prompt.Render("after tool") } - return DefaultStyles.Faint.Render("off") + return chrome.DefaultStyles.Faint.Render("off") } // channelDetails explain what the channel's setting does. @@ -383,21 +386,21 @@ func (m DiscordPageModel) dmEntries() []listEntry { owner := m.DMs.Owner rows := []listEntry{{ key: "owner:" + owner.UserID, section: "you", name: cmp.Or(owner.Name, "you"), desc: owner.UserID, - tag: DefaultStyles.Faint.Render("always allowed"), + tag: chrome.DefaultStyles.Faint.Render("always allowed"), detail: func(width int) []string { return m.personDetails("owner", owner.UserID, width) }, }} now := m.now() for _, p := range m.DMs.Allowed { rows = append(rows, listEntry{ key: "allowed:" + p.UserID, section: "allowed", name: cmp.Or(p.Name, p.UserID), desc: p.UserID, - tag: DefaultStyles.Faint.Render("added " + ago(now, p.AddedAt)), + tag: chrome.DefaultStyles.Faint.Render("added " + ago(now, p.AddedAt)), detail: func(width int) []string { return m.personDetails("allowed", p.UserID, width) }, }) } for _, r := range m.DMs.Requests { rows = append(rows, listEntry{ key: "request:" + r.UserID, section: "wants to DM you", name: "@" + r.Username, desc: "“" + r.Preview + "”", - tag: DefaultStyles.Warning.Render(plural(r.Count, "message") + " · " + ago(now, r.LastAt)), + tag: chrome.DefaultStyles.Warning.Render(plural(r.Count, "message") + " · " + ago(now, r.LastAt)), search: []string{r.UserID}, detail: func(width int) []string { return m.personDetails("request", r.UserID, width) }, }) @@ -432,7 +435,7 @@ func (m DiscordPageModel) personDetails(kind, user string, width int) []string { lines := paneTitle("@"+r.Username, "", width) lines = append(lines, factRows("user id", r.UserID, width)...) lines = append(lines, factRows("sent", plural(r.Count, "message")+" · last "+ago(now, r.LastAt), width)...) - lines = append(lines, "", DefaultStyles.Muted.Render("latest")) + lines = append(lines, "", chrome.DefaultStyles.Muted.Render("latest")) for _, l := range svWrap(r.Preview, max(1, width-2), 6) { lines = append(lines, " "+l) } diff --git a/cli/internal/tui/editor.go b/cli/internal/tui/editor.go index 77ca17304..e1ab0cd43 100644 --- a/cli/internal/tui/editor.go +++ b/cli/internal/tui/editor.go @@ -14,6 +14,7 @@ import ( "strings" "albedo/cli/internal/daemon" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -49,11 +50,11 @@ func (p *promptEditorProcess) Run() error { } path := file.Name() defer os.Remove(path) - if _, err := file.WriteString(p.prompt); err != nil { + if _, err = file.WriteString(p.prompt); err != nil { file.Close() return fmt.Errorf("could not write to temporary file: %w", err) } - if err := file.Close(); err != nil { + if err = file.Close(); err != nil { return fmt.Errorf("could not close temporary file: %w", err) } diff --git a/cli/internal/tui/effort_selector.go b/cli/internal/tui/effort_selector.go index 94ec7f1a4..117eef534 100644 --- a/cli/internal/tui/effort_selector.go +++ b/cli/internal/tui/effort_selector.go @@ -4,6 +4,8 @@ import ( "slices" "strings" + "albedo/cli/internal/tui/chrome" + "github.com/charmbracelet/x/ansi" ) @@ -57,14 +59,14 @@ func (m ChatModel) effortSelectorView() string { preferred := reasoningEffort(m.effortDefaultChoice, m.effortDefault, m.effortProfile) if choice == "inherit" { label = "Provider default · level not reported" - } else if !slices.Contains(m.effortLevels, choice) && !(choice == preferred && m.usesAdapterEffortDefault()) { + } else if !slices.Contains(m.effortLevels, choice) && (choice != preferred || !m.usesAdapterEffortDefault()) { label += " · Unsupported" } else if choice == preferred { label += " · Default" } - marker, style := " ", DefaultStyles.Muted + marker, style := " ", chrome.DefaultStyles.Muted if i == m.effortSelected { - marker, style = "● ", DefaultStyles.Selected.Bold(true) + marker, style = "● ", chrome.DefaultStyles.Selected.Bold(true) } rows = append(rows, style.Render(ansi.Truncate(marker+label, width, "…"))) } diff --git a/cli/internal/tui/effort_selector_test.go b/cli/internal/tui/effort_selector_test.go index d60265318..e8783ce6a 100644 --- a/cli/internal/tui/effort_selector_test.go +++ b/cli/internal/tui/effort_selector_test.go @@ -5,10 +5,11 @@ package tui import ( "albedo/cli/internal/config" "albedo/cli/internal/daemon" - tea "charm.land/bubbletea/v2" "slices" "strings" "testing" + + tea "charm.land/bubbletea/v2" ) func TestEffortSourceSwitchStagesAndAppliesOnlyOnEnter(t *testing.T) { @@ -77,11 +78,11 @@ func TestModelPickerSavingDefaultsRequiresSeparateConfirmation(t *testing.T) { } save := tea.KeyPressMsg{Code: 's', Mod: tea.ModCtrl} m, cmd = m.Update(save) - if cmd != nil || !m.confirm.asking() { + if cmd != nil || !m.confirm.Asking() { t.Fatal("saving a profile default must ask first") } m, cmd = m.Update(keyEsc) - if cmd != nil || m.confirm.asking() { + if cmd != nil || m.confirm.Asking() { t.Fatal("escape must cancel saving defaults") } m, _ = m.Update(save) diff --git a/cli/internal/tui/extension_picker.go b/cli/internal/tui/extension_picker.go index 66ffd69ee..a16b1bc88 100644 --- a/cli/internal/tui/extension_picker.go +++ b/cli/internal/tui/extension_picker.go @@ -2,12 +2,15 @@ package tui import ( "albedo/cli/internal/daemon" + "albedo/cli/internal/terminalui" "context" "errors" "fmt" "slices" "strings" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" ) @@ -45,7 +48,7 @@ type ExtensionPickerModel struct { SessionID string Extensions []ExtensionItem listView - confirm + confirm chrome.Confirm pageStatus // noticeWarns says the notice is a warning rather than a save that went through. noticeWarns bool @@ -67,7 +70,7 @@ func (m *ExtensionPickerModel) SetSize(width, height int) { } // Confirming reports a question waiting for enter or esc. -func (m ExtensionPickerModel) Confirming() bool { return m.asking() } +func (m ExtensionPickerModel) Confirming() bool { return m.confirm.Asking() } func (m ExtensionPickerModel) Init() tea.Cmd { return m.loadExtensionsCmd(m.Generation) @@ -208,7 +211,7 @@ func (m *ExtensionPickerModel) askToggle(scope string) { if scope == scopeSession { prompt += " This will reload this session." } - m.ask(scope, ext.Name, "switch", prompt) + m.confirm.Ask(scope, ext.Name, "switch", prompt) return } verb := "enable" @@ -217,31 +220,31 @@ func (m *ExtensionPickerModel) askToggle(scope string) { } switch scope { case scopeInherit: - m.ask(scope, ext.Name, "follow global", fmt.Sprintf("This session will follow the global default for %s. Remove its own choice?", ext.Name)) + m.confirm.Ask(scope, ext.Name, "follow global", fmt.Sprintf("This session will follow the global default for %s. Remove its own choice?", ext.Name)) case scopeSession: - m.ask(scope, ext.Name, verb, fmt.Sprintf("This will reload this session. %s %s for this session only?", strings.ToUpper(verb[:1])+verb[1:], ext.Name)) + m.confirm.Ask(scope, ext.Name, verb, fmt.Sprintf("This will reload this session. %s %s for this session only?", strings.ToUpper(verb[:1])+verb[1:], ext.Name)) default: - m.ask(scope, ext.Name, verb, fmt.Sprintf("Sessions following global defaults will use this change. %s %s globally?", strings.ToUpper(verb[:1])+verb[1:], ext.Name)) + m.confirm.Ask(scope, ext.Name, verb, fmt.Sprintf("Sessions following global defaults will use this change. %s %s globally?", strings.ToUpper(verb[:1])+verb[1:], ext.Name)) } } // save sends the change the confirmation asked about. func (m *ExtensionPickerModel) save() tea.Cmd { ext, ok := m.current() - if !ok || ext.Name != m.target { - m.dismiss() + if !ok || ext.Name != m.confirm.Target { + m.confirm.Dismiss() return nil } m.Saving, m.Error = true, "" m.Generation = nextPageGeneration() enabled := !ext.GlobalEnabled - switch m.what { + switch m.confirm.What { case scopeSession: enabled = !ext.Enabled case scopeInherit: enabled = false } - return m.changeExtensionCmd(ext.Name, m.what, enabled, m.Generation) + return m.changeExtensionCmd(ext.Name, m.confirm.What, enabled, m.Generation) } func (m ExtensionPickerModel) Update(msg tea.Msg) (ExtensionPickerModel, tea.Cmd) { @@ -258,17 +261,17 @@ func (m ExtensionPickerModel) Update(msg tea.Msg) (ExtensionPickerModel, tea.Cmd if msg.Gen == m.Generation { if apiErr, ok := errors.AsType[*daemon.APIError](msg.Err); ok && apiErr.StatusCode == 412 { m.Saving, m.Loading, m.Error = false, true, "" - m.dismiss() + m.confirm.Dismiss() m.Notice, m.noticeWarns = "The configuration changed. Review the refreshed choices before saving.", true m.Generation = nextPageGeneration() return m, m.loadExtensionsCmd(m.Generation) } } if !m.settle(msg.Gen, msg.Err, &m.Saving) { - m.failed = msg.Gen == m.Generation + m.confirm.Failed = msg.Gen == m.Generation return m, nil } - m.dismiss() + m.confirm.Dismiss() m.setExtensions(msg.Extensions) m.Error = "" m.Notice, m.noticeWarns = msg.Notice, msg.Warns @@ -277,12 +280,12 @@ func (m ExtensionPickerModel) Update(msg tea.Msg) (ExtensionPickerModel, tea.Cmd case tea.KeyPressMsg: key := msg.String() switch { - case m.asking() && !m.Saving: - if m.key(msg) { + case m.confirm.Asking() && !m.Saving: + if m.confirm.Key(msg) { cmd := m.save() return m, cmd } - if !m.asking() { + if !m.confirm.Asking() { m.Error = "" } return m, nil @@ -342,15 +345,15 @@ func (m ExtensionPickerModel) Update(msg tea.Msg) (ExtensionPickerModel, tea.Cmd func stateLead(on bool) string { if on { - return DefaultStyles.Success.Render("on") + return chrome.DefaultStyles.Success.Render("on") } - return DefaultStyles.Faint.Render("off") + return chrome.DefaultStyles.Faint.Render("off") } // daggered marks a row's state as this session's own choice. func daggered(lead string, overridden bool) string { if overridden { - return lead + DefaultStyles.Muted.Render("†") + return lead + chrome.DefaultStyles.Muted.Render("†") } return lead } @@ -360,7 +363,7 @@ func daggerLegend(marked bool) string { if !marked { return "" } - return DefaultStyles.Muted.Render("†") + DefaultStyles.Faint.Render(" session override") + return chrome.DefaultStyles.Muted.Render("†") + chrome.DefaultStyles.Faint.Render(" session override") } func onOff(on bool) string { @@ -375,7 +378,7 @@ func extensionDetails(ext ExtensionItem, asked string, width int) []string { lines := paneTitle(ext.Name, ext.Description, width) if ext.Quarantined != "" { for _, line := range svWrap("quarantined: "+ext.Quarantined, width, 6) { - lines = append(lines, DefaultStyles.Error.Render(line)) + lines = append(lines, chrome.DefaultStyles.Error.Render(line)) } lines = append(lines, "") } @@ -420,34 +423,34 @@ func joinOr(items []string, sep, empty string) string { } func (m ExtensionPickerModel) footer(width int) string { - if m.asking() && !m.Saving { - return m.confirm.footer(width, m.Error) + if m.confirm.Asking() && !m.Saving { + return m.confirm.Footer(width, m.Error) } if len(m.Extensions) == 0 && m.Error != "" { - return footerLine(width, []hint{{"ctrl+r", "retry"}, {"esc", "back"}}, DefaultStyles.Error.Render(m.Error), true) + return chrome.FooterLine(width, []chrome.Hint{{Key: "ctrl+r", Does: "retry"}, {Key: "esc", Does: "back"}}, chrome.DefaultStyles.Error.Render(m.Error), true) } ext, _ := m.current() - hints := []hint{{"↑↓", "move"}, {"enter", "everywhere"}, {"shift+enter", "here"}} + hints := []chrome.Hint{{Key: "↑↓", Does: "move"}, {Key: "enter", Does: "everywhere"}, {Key: "shift+enter", Does: "here"}} if row, ok := m.highlighted(); ok && row.heading { - hints = []hint{{"↑↓", "move"}, {"enter", "open/close"}} + hints = []chrome.Hint{{Key: "↑↓", Does: "move"}, {Key: "enter", Does: "open/close"}} } if ext.Overridden { - hints = append(hints, hint{"ctrl+x", "follow global"}) + hints = append(hints, chrome.Hint{Key: "ctrl+x", Does: "follow global"}) } if (ext.Name == "webhooks" || ext.Name == "discord") && ext.Enabled { - hints = append(hints, hint{"ctrl+w", ext.Name}) + hints = append(hints, chrome.Hint{Key: "ctrl+w", Does: ext.Name}) } - hints = append(hints, hint{"ctrl+r", "refresh"}, hint{"esc", "back"}) + hints = append(hints, chrome.Hint{Key: "ctrl+r", Does: "refresh"}, chrome.Hint{Key: "esc", Does: "back"}) var status string urgent := true switch { case m.Saving: - status = DefaultStyles.Busy.Render("saving…") + status = chrome.DefaultStyles.Busy.Render("saving…") case m.Loading: - status, urgent = DefaultStyles.Faint.Render("loading…"), false + status, urgent = chrome.DefaultStyles.Faint.Render("loading…"), false case m.Error != "": - status = DefaultStyles.Error.Render(m.Error) + status = chrome.DefaultStyles.Error.Render(m.Error) case m.Notice != "": status = notice(m.Notice, m.noticeWarns) default: @@ -457,12 +460,12 @@ func (m ExtensionPickerModel) footer(width int) string { on++ } } - status, urgent = DefaultStyles.Faint.Render(fmt.Sprintf("%s · %d on here", counted(len(m.Extensions), "extension"), on)), false + status, urgent = chrome.DefaultStyles.Faint.Render(fmt.Sprintf("%s · %d on here", counted(len(m.Extensions), "extension"), on)), false } - return footerLine(width, hints, status, urgent) + return chrome.FooterLine(width, hints, status, urgent) } -func (m ExtensionPickerModel) View() string { +func (m ExtensionPickerModel) Page() terminalui.Page { lv := m.listView lv.Empty = "No extensions are available for this session." switch { @@ -479,11 +482,11 @@ func (m ExtensionPickerModel) View() string { } right := "" if own > 0 { - right = DefaultStyles.Muted.Render(fmt.Sprintf("%d own choices here", own)) + right = chrome.DefaultStyles.Muted.Render(fmt.Sprintf("%d own choices here", own)) } - frame := lv.frame(brand("albedo")+" "+DefaultStyles.Muted.Render("/extensions"), right, m.footer(max(1, m.Width))) - if ext, ok := m.current(); ok && m.asking() { - frame.pane = detailPane(func(width int) []string { return extensionDetails(ext, m.what, width) }) + frame := lv.frame(chrome.Brand("albedo")+" "+chrome.DefaultStyles.Muted.Render("/extensions"), right, m.footer(max(1, m.Width))) + if ext, ok := m.current(); ok && m.confirm.Asking() { + frame.Detail = detailPane(func(width int) []string { return extensionDetails(ext, m.confirm.What, width) }) } - return frame.view(m.Width, m.Height) + return frame } diff --git a/cli/internal/tui/extension_shelves.go b/cli/internal/tui/extension_shelves.go index 92b4e3276..beddaa769 100644 --- a/cli/internal/tui/extension_shelves.go +++ b/cli/internal/tui/extension_shelves.go @@ -5,6 +5,8 @@ import ( "slices" "strings" + "albedo/cli/internal/tui/chrome" + "github.com/charmbracelet/x/ansi" ) @@ -114,7 +116,7 @@ func extensionEntry(ext ExtensionItem) listEntry { if name == "notes" { name = "+ notes" } - global, here := stateLead(ext.GlobalEnabled), DefaultStyles.Faint.Render("·") + global, here := stateLead(ext.GlobalEnabled), chrome.DefaultStyles.Faint.Render("·") if memoryStrategy(ext) { global = memoryDot(ext.GlobalEnabled) } @@ -123,15 +125,15 @@ func extensionEntry(ext ExtensionItem) listEntry { if memoryStrategy(ext) { here = memoryDot(ext.Enabled) } - here = DefaultStyles.Bold.Render(here) + here = chrome.DefaultStyles.Bold.Render(here) } return listEntry{ key: ext.Name, name: name, desc: ext.Summary, search: slices.Concat([]string{ext.Description, ext.Shelf}, ext.Plugins, ext.Requires), draw: func(width int, hits []int) string { - style := DefaultStyles.Bold.UnsetBold() + style := chrome.DefaultStyles.Bold.UnsetBold() if ext.Quarantined != "" { - style = DefaultStyles.Error + style = chrome.DefaultStyles.Error } label := markedCell(name, hits, min(17, max(1, width-22)), style) return shelfColumns(label, ext.Summary, global, here, width, false) @@ -142,9 +144,9 @@ func extensionEntry(ext ExtensionItem) listEntry { func memoryDot(on bool) string { if on { - return DefaultStyles.Success.Render("●") + return chrome.DefaultStyles.Success.Render("●") } - return DefaultStyles.Faint.Render("○") + return chrome.DefaultStyles.Faint.Render("○") } // shelfColumns keeps both scope columns when the summary no longer fits. @@ -155,14 +157,14 @@ func shelfColumns(name, summary, global, here string, width int, heading bool) s if heading { nameW = min(ansi.StringWidth(name), leftW) } - left := svCell(name, nameW, false) + left := chrome.Cell(name, nameW, false) if heading { - left = DefaultStyles.Bold.Render(left) + left = chrome.DefaultStyles.Bold.Render(left) } room := leftW - nameW - 2 if summary != "" && room >= 12 { - left += DefaultStyles.Faint.Render(" " + ansi.Truncate(summary, room, "…")) + left += chrome.DefaultStyles.Faint.Render(" " + ansi.Truncate(summary, room, "…")) } left += strings.Repeat(" ", max(0, leftW-ansi.StringWidth(left))) - return left + " " + svCell(global, globalW, false) + " " + svCell(here, hereW, false) + return left + " " + chrome.Cell(global, globalW, false) + " " + chrome.Cell(here, hereW, false) } diff --git a/cli/internal/tui/folder_picker.go b/cli/internal/tui/folder_picker.go index d219b8c2b..8d185c077 100644 --- a/cli/internal/tui/folder_picker.go +++ b/cli/internal/tui/folder_picker.go @@ -7,6 +7,8 @@ import ( "strings" "time" + "albedo/cli/internal/tui/chrome" + "charm.land/bubbles/v2/textinput" tea "charm.land/bubbletea/v2" ) @@ -14,10 +16,10 @@ import ( // WorkspaceRetry is a turn refused because the session's folder had gone // missing; it goes out again once the session moves. type WorkspaceRetry struct { - Images []daemon.ImageAttachment - Pastes []string Missing string Prompt string + Images []daemon.ImageAttachment + Pastes []string Continue bool } @@ -25,10 +27,10 @@ type WorkspaceRetry struct { type FolderMovedMsg struct { Err error Retry *WorkspaceRetry - SessionID string - Workspace string Location *daemon.Location Session *daemon.Session + SessionID string + Workspace string } type FolderPickerCancelMsg struct{} @@ -40,23 +42,23 @@ type FolderOpenSessionMsg struct{ Session daemon.Session } type FolderNewSessionMsg struct{ Workspace string } type folderListMsg struct { - Gen int64 Err error Path string List daemon.FolderList + Gen int64 } type folderRepoMsg struct { - Gen int64 Repo *daemon.Repo Path string + Gen int64 } type folderPreviewMsg struct { - Gen int64 Err error Path string Preview daemon.FolderPreview + Gen int64 } type folderPreviewTickMsg struct { @@ -65,18 +67,18 @@ type folderPreviewTickMsg struct { } type hostsMsg struct { - Gen int64 Err error Hosts []daemon.KnownHost + Gen int64 } // hostStatusMsg is a host's probe as the daemon answered it; Warmed marks // the answer to warming it, which has always settled. type hostStatusMsg struct { - Gen int64 Err error - Host string Status daemon.HostStatus + Host string + Gen int64 Warmed bool } @@ -90,9 +92,9 @@ type hostPollMsg struct { type connectTickMsg struct{ Gen int64 } type hostSignedInMsg struct { - Gen int64 Err error Host string + Gen int64 } type folderSessionsMsg struct { @@ -140,20 +142,17 @@ type cachedFolderPreview struct { // folder. Browsing, from the sessions view, it starts a session in the // folder instead. Either way → steps into the folder's sessions to open one. type FolderPicker struct { + // session is the one being moved; browsing, only its workspace is set. + session daemon.Session readCtx context.Context - cancelReads context.CancelFunc src folderSource + cancelReads context.CancelFunc Tick TickFunc asked map[string]bool retry *WorkspaceRetry previews map[string]*cachedFolderPreview repos map[string]*daemon.Repo listings map[string]*folderListMsg - - // session is the one being moved; browsing, only its workspace is set. - session daemon.Session - // Session failures survive query edits; a reopened picker rejects the old load. - sessionsError string // homes are the folders ~ names: the daemon's under "", a remote // host's under its [user@]host, as listings and probes report them. homes map[string]string @@ -161,41 +160,39 @@ type FolderPicker struct { // typed one turned out to be. labels map[string]string aliases map[string]string - hosts []daemon.KnownHost // probes are hosts' reachability, warmed once each per picker. - probes map[string]daemon.HostStatus - warmed map[string]bool - section string - listed string - notice string - sessions []daemon.Session - + probes map[string]daemon.HostStatus + warmed map[string]bool + // Session failures survive query edits; a reopened picker rejects the old load. + sessionsError string + section string + listed string + notice string + hosts []daemon.KnownHost + sessions []daemon.Session rows []folderRow input textinput.Model sessionsGeneration int64 Width, Height int cursor int sessionCursor int - browse bool - + // frame animates the face beside a host still connecting; ticking is + // whether its next tick is already on its way. + frame int + browse bool sessionsLoading bool moving bool - // inSessions moves the cursor through the highlighted folder's sessions. inSessions bool - - // frame animates the face beside a host still connecting; ticking is - // whether its next tick is already on its way. - frame int - ticking bool + ticking bool } func NewFolderPicker(src folderSource, session daemon.Session, retry *WorkspaceRetry) FolderPicker { - ti := newTextInput() + ti := chrome.NewTextInput() ti.Prompt = "" ti.Placeholder = "Type a path, host:path, or @host" st := ti.Styles() - st.Focused.Placeholder, st.Blurred.Placeholder = DefaultStyles.Faint, DefaultStyles.Faint + st.Focused.Placeholder, st.Blurred.Placeholder = chrome.DefaultStyles.Faint, chrome.DefaultStyles.Faint ti.SetStyles(st) ti.Focus() readCtx, cancelReads := context.WithCancel(context.Background()) diff --git a/cli/internal/tui/folder_picker_view.go b/cli/internal/tui/folder_picker_view.go index 98b88c2cd..cc6864c3b 100644 --- a/cli/internal/tui/folder_picker_view.go +++ b/cli/internal/tui/folder_picker_view.go @@ -2,6 +2,7 @@ package tui import ( "albedo/cli/internal/daemon" + "albedo/cli/internal/terminalui" "cmp" "fmt" "math" @@ -10,6 +11,8 @@ import ( "strings" "time" + "albedo/cli/internal/tui/chrome" + "charm.land/lipgloss/v2" "github.com/charmbracelet/x/ansi" ) @@ -65,31 +68,31 @@ func (m FolderPicker) visibleRows() (first, last int) { return first, last } -func (m FolderPicker) View() string { +func (m FolderPicker) Page() terminalui.Page { width := cmp.Or(m.Width, 80) heading, title := "sessions by folder", "" if !m.browse { - heading, title = "move session", DefaultStyles.Faint.Render(sessionTitle(m.session)) - } - frame := listFrame{ - title: brand("albedo") + " " + DefaultStyles.Muted.Render(heading), - right: title, - filter: promptLead() + m.input.View(), - list: m.list, - paneWidth: halfPane, - pane: func(w, h int) []string { + heading, title = "move session", chrome.DefaultStyles.Faint.Render(sessionTitle(m.session)) + } + frame := terminalui.Page{ + Title: chrome.Brand("albedo") + " " + chrome.DefaultStyles.Muted.Render(heading), + Meta: title, + Filter: chrome.PromptLead() + m.input.View(), + List: m.list, + DetailWidth: halfPane, + Detail: func(w, h int) []string { pane := m.preview(w-1, h) for i := range pane { - pane[i] = svFit(pane[i], w-1) + " " + pane[i] = chrome.Fit(pane[i], w-1) + " " } return pane }, - footer: m.footer(width), + Footer: m.footer(width), } if m.waitingForFolders() { - frame.pane = nil + frame.Detail = nil } - return frame.view(m.Width, m.Height) + return frame } // narrowKeys is the width the full keys need beside a status; less than that @@ -101,16 +104,16 @@ const narrowKeys = 28 // the keys leave. func (m FolderPicker) footer(width int) string { hints := m.hints() - keys := " " + keyHints(hints...) + keys := " " + chrome.KeyHints(hints...) if m.sessionsError != "" && width-ansi.StringWidth(keys) < narrowKeys { - hints = []hint{m.retryHint()} - keys = " " + keyHints(hints...) + hints = []chrome.Hint{m.retryHint()} + keys = " " + chrome.KeyHints(hints...) } status, urgent := m.status(width - 2) if !urgent { status, _ = m.status(width - ansi.StringWidth(keys) - 3) } - return footerLine(width, hints, status, urgent) + return chrome.FooterLine(width, hints, status, urgent) } // status is the most pressing thing to say in room columns: a move in @@ -119,14 +122,14 @@ func (m FolderPicker) footer(width int) string { func (m FolderPicker) status(room int) (string, bool) { switch { case m.moving: - return DefaultStyles.Faint.Render("moving…"), true + return chrome.DefaultStyles.Faint.Render("moving…"), true case m.notice != "": - return DefaultStyles.Warning.Render(tailFit(m.notice, room)), true + return chrome.DefaultStyles.Warning.Render(tailFit(m.notice, room)), true case m.sessionsError != "": - return DefaultStyles.Warning.Render(ansi.Truncate("Recent sessions: "+m.sessionsError, room, "…")), true + return chrome.DefaultStyles.Warning.Render(ansi.Truncate("Recent sessions: "+m.sessionsError, room, "…")), true case m.retry != nil: const missing = "Folder not found: " - return DefaultStyles.Warning.Render(missing) + DefaultStyles.Muted.Render(tailFit(m.homed(m.retry.Missing), room-ansi.StringWidth(missing))), true + return chrome.DefaultStyles.Warning.Render(missing) + chrome.DefaultStyles.Muted.Render(tailFit(m.homed(m.retry.Missing), room-ansi.StringWidth(missing))), true case m.browse: // nothing moves, so there is no "now in" return "", false } @@ -135,46 +138,46 @@ func (m FolderPicker) status(room int) (string, bool) { if where == "" { return "", false } - return DefaultStyles.Faint.Render(here) + DefaultStyles.Muted.Render(where), false + return chrome.DefaultStyles.Faint.Render(here) + chrome.DefaultStyles.Muted.Render(where), false } // hints are the footer's keys for where the cursor is; → shows only when // the highlighted folder has sessions to step into. -func (m FolderPicker) hints() []hint { - var hints []hint +func (m FolderPicker) hints() []chrome.Hint { + var hints []chrome.Hint if m.sessionsError != "" { hints = append(hints, m.retryHint()) } if m.inSessions { - return append(hints, hint{"↑↓", "move"}, hint{"enter", "open"}, hint{"←", "folders"}) + return append(hints, chrome.Hint{Key: "↑↓", Does: "move"}, chrome.Hint{Key: "enter", Does: "open"}, chrome.Hint{Key: "←", Does: "folders"}) } row, ok := m.highlighted() if ok { - hints = append(hints, hint{"↑↓", "move"}, hint{"tab", "open"}) + hints = append(hints, chrome.Hint{Key: "↑↓", Does: "move"}, chrome.Hint{Key: "tab", Does: "open"}) } - hints = append(hints, hint{"shift+tab", "up"}) + hints = append(hints, chrome.Hint{Key: "shift+tab", Does: "up"}) if ok && len(m.sessionsFor(row)) > 0 { - hints = append(hints, hint{"→", "sessions"}) + hints = append(hints, chrome.Hint{Key: "→", Does: "sessions"}) } if ok && m.probe(row.hostKey).State == "needs_auth" { - hints = append(hints, hint{"ctrl+l", "sign in"}) + hints = append(hints, chrome.Hint{Key: "ctrl+l", Does: "sign in"}) } if m.target() != "" { action := "move here" if m.browse { action = "new session" } - hints = append(hints, hint{"enter", action}) + hints = append(hints, chrome.Hint{Key: "enter", Does: action}) } - return append(hints, hint{"esc", "back"}) + return append(hints, chrome.Hint{Key: "esc", Does: "back"}) } // retryHint is the way back into a session list that failed to load. -func (m FolderPicker) retryHint() hint { +func (m FolderPicker) retryHint() chrome.Hint { if m.sessionsLoading { - return hint{"ctrl+r", "retrying…"} + return chrome.Hint{Key: "ctrl+r", Does: "retrying…"} } - return hint{"ctrl+r", "retry sessions"} + return chrome.Hint{Key: "ctrl+r", Does: "retry sessions"} } // tailFit keeps the end of plain text, where a path names its folder. @@ -191,11 +194,11 @@ func tailFit(s string, w int) string { // list is the section rule over the rows, at exactly width × height. func (m FolderPicker) list(width, height int) []string { if len(m.rows) == 0 { - rule := sectionRule(m.section, 0, width) + rule := chrome.SectionRule(m.section, 0, width) if m.waitingForFolders() { rule = plainRule("opening "+m.homed(m.listed), width) } - return scrollWindow([]string{rule, DefaultStyles.Faint.Render(" " + m.emptyNote())}, 1, width, height) + return scrollWindow([]string{rule, chrome.DefaultStyles.Faint.Render(" " + m.emptyNote())}, 1, width, height) } here := m.workspace() tagW := 0 @@ -214,9 +217,9 @@ func (m FolderPicker) list(width, height int) []string { return drawWindow(n, func(i int) string { switch { case i == 0: - return sectionRule(sec, topCount, width) + return chrome.SectionRule(sec, topCount, width) case split > 0 && i == split+1: - return sectionRule("hosts", len(m.rows)-split, width) + return chrome.SectionRule("hosts", len(m.rows)-split, width) } r := i - 1 if split > 0 && i > split+1 { @@ -253,11 +256,11 @@ func (m FolderPicker) emptyNote() string { return "no matches" case l == nil && remote && m.probe(m.canonical(host)).State == "warming": label := m.labelOf(host) - return reachingText(label, m.probe(m.canonical(host)).Step) + " " + DefaultStyles.Agent.Render(connectingFace(label, m.frame)) + return reachingText(label, m.probe(m.canonical(host)).Step) + " " + chrome.DefaultStyles.Agent.Render(connectingFace(label, m.frame)) case l == nil: return "loading…" case l.Err != nil: - return DefaultStyles.Error.Render(l.Err.Error()) + return chrome.DefaultStyles.Error.Render(l.Err.Error()) case len(l.List.Entries) == 0: return "No folders here" } @@ -274,7 +277,7 @@ func (m FolderPicker) where(row folderRow) string { return strings.Join(crumbParts(m.homed(path.Dir(p))), " › ") } // the host leads the first crumb, as in the preview's rule - crumbs := crumbParts(scpRelative(underHome(path.Dir(p), m.homes[m.canonical(host)]))) + crumbs := crumbParts(chrome.ScpRelative(chrome.UnderHome(path.Dir(p), m.homes[m.canonical(host)]))) crumbs[0] = cmp.Or(row.host, m.labelOf(host)) + ":" + crumbs[0] return strings.Join(crumbs, " › ") } @@ -286,13 +289,13 @@ func (m FolderPicker) reach(row folderRow) (note string, style lipgloss.Style, d p := m.probe(row.hostKey) switch p.State { case "warming": - return "", DefaultStyles.Faint, true + return "", chrome.DefaultStyles.Faint, true case "needs_auth": - return "sign in · ctrl+l", DefaultStyles.Warning, false + return "sign in · ctrl+l", chrome.DefaultStyles.Warning, false case "unreachable", "unsupported": - return cmp.Or(p.Detail, p.State), DefaultStyles.Error, false + return cmp.Or(p.Detail, p.State), chrome.DefaultStyles.Error, false } - return "", DefaultStyles.Faint, false + return "", chrome.DefaultStyles.Faint, false } // row is a folder in the sessions view's grammar: bar, glyph, name with @@ -300,12 +303,12 @@ func (m FolderPicker) reach(row folderRow) (note string, style lipgloss.Style, d // head column is tagW wide, none when no row has a head, and where takes // what the others leave. func (m FolderPicker) row(row folderRow, selected, here bool, width, tagW int, now time.Time) string { - glyph, glyphStyle := "· ", DefaultStyles.Faint + glyph, glyphStyle := "· ", chrome.DefaultStyles.Faint switch { case selected: - glyph, glyphStyle = "◆ ", DefaultStyles.Agent + glyph, glyphStyle = "◆ ", chrome.DefaultStyles.Agent case here: - glyph, glyphStyle = "● ", DefaultStyles.Success + glyph, glyphStyle = "● ", chrome.DefaultStyles.Success } ageW := 4 if here { @@ -322,17 +325,17 @@ func (m FolderPicker) row(row folderRow, selected, here bool, width, tagW int, n } bar := " " if selected { - bar = selectBar() + bar = chrome.SelectBar() } note, noteStyle, dim := m.reach(row) base := lipgloss.NewStyle() switch { case dim: - base = DefaultStyles.Faint + base = chrome.DefaultStyles.Faint case row.hostRow: - base = hostStyle(row.host).Bold(selected) + base = chrome.HostStyle(row.host).Bold(selected) case selected: - base = DefaultStyles.Bold + base = chrome.DefaultStyles.Bold } line := bar + glyphStyle.Render(glyph) + " " + litName(row.name, row.matched, nameW, base) if note != "" { @@ -341,34 +344,34 @@ func (m FolderPicker) row(row folderRow, selected, here bool, width, tagW int, n } } if whereW > 0 { - line += " " + DefaultStyles.Faint.Render(svCell(m.where(row), whereW, false)) + line += " " + chrome.DefaultStyles.Faint.Render(chrome.Cell(m.where(row), whereW, false)) } if note != "" { - line += " " + noteStyle.Render(svCell(note, noteW, false)) + line += " " + noteStyle.Render(chrome.Cell(note, noteW, false)) if selected { - return selectedLine(line, width) + return chrome.SelectedLine(line, width) } return line } if tagW > 0 { - line += " " + DefaultStyles.Faint.Render(svCell(repoTag(m.repos[row.path]), tagW, false)) + line += " " + chrome.DefaultStyles.Faint.Render(chrome.Cell(repoTag(m.repos[row.path]), tagW, false)) } - age, ageStyle := "", DefaultStyles.Faint + age, ageStyle := "", chrome.DefaultStyles.Faint if here { - age, ageStyle = "current", DefaultStyles.Success + age, ageStyle = "current", chrome.DefaultStyles.Success } else if row.age != nil { age = svCompactAge(row.age, now) } - line += " " + ageStyle.Render(svCell(age, ageW, true)) + line += " " + ageStyle.Render(chrome.Cell(age, ageW, true)) if selected { - return selectedLine(line, width) + return chrome.SelectedLine(line, width) } return line } // litName fits name into w columns in base, its fuzzy-matched letters lit. func litName(name string, matched []int, w int, base lipgloss.Style) string { - lit := DefaultStyles.Prompt.Bold(true).Underline(true) + lit := chrome.DefaultStyles.Prompt.Bold(true).Underline(true) fitted := ansi.Truncate(name, w, "…") var b strings.Builder for i, r := range fitted { @@ -433,9 +436,9 @@ func (m FolderPicker) preview(width, height int) []string { var tree *daemon.FolderPreview switch { case c == nil || c.loading: - body = []string{DefaultStyles.Faint.Render("looking…")} + body = []string{chrome.DefaultStyles.Faint.Render("looking…")} case c.err: - body = []string{DefaultStyles.Faint.Render("Could not open this folder")} + body = []string{chrome.DefaultStyles.Faint.Render("Could not open this folder")} default: languages, tree = c.Languages, &c.FolderPreview if c.Repo != nil { @@ -481,22 +484,22 @@ func (m FolderPicker) hostPane(row folderRow, width, height int) []string { var body []string switch p.State { case "", "warming": - body = []string{DefaultStyles.Faint.Render(reachingText(label, p.Step)+" ") + DefaultStyles.Agent.Render(connectingFace(label, m.frame))} + body = []string{chrome.DefaultStyles.Faint.Render(reachingText(label, p.Step)+" ") + chrome.DefaultStyles.Agent.Render(connectingFace(label, m.frame))} case "ready": if p.OS != "" { - body = append(body, DefaultStyles.Muted.Render(strings.TrimSpace(p.OS+" "+p.Arch))) + body = append(body, chrome.DefaultStyles.Muted.Render(strings.TrimSpace(p.OS+" "+p.Arch))) } if home := m.homes[m.canonical(row.hostKey)]; home != "" { - body = append(body, DefaultStyles.Faint.Render("~ is ")+DefaultStyles.Muted.Render(home)) + body = append(body, chrome.DefaultStyles.Faint.Render("~ is ")+chrome.DefaultStyles.Muted.Render(home)) } case "needs_auth": - body = []string{DefaultStyles.Warning.Render(cmp.Or(p.Detail, "needs a person to sign in")), DefaultStyles.Faint.Render("ctrl+l signs in here")} + body = []string{chrome.DefaultStyles.Warning.Render(cmp.Or(p.Detail, "needs a person to sign in")), chrome.DefaultStyles.Faint.Render("ctrl+l signs in here")} default: - body = []string{DefaultStyles.Error.Render(cmp.Or(p.Detail, p.State))} + body = []string{chrome.DefaultStyles.Error.Render(cmp.Or(p.Detail, p.State))} } - head := DefaultStyles.Decor.Render("─ ") + hostStyle(label).Render(label) + " " + DefaultStyles.Decor.Render(strings.Repeat("─", max(0, width-3-ansi.StringWidth(label)))) + head := chrome.DefaultStyles.Decor.Render("─ ") + chrome.HostStyle(label).Render(label) + " " + chrome.DefaultStyles.Decor.Render(strings.Repeat("─", max(0, width-3-ansi.StringWidth(label)))) if m.stacked() { - head = hostStyle(label).Bold(true).Render(label) + head = chrome.HostStyle(label).Bold(true).Render(label) } lines := []string{head, ""} for _, l := range body { @@ -524,31 +527,31 @@ func (m FolderPicker) sessionRows(sessions []daemon.Session, width, room int) [] rows := make([]string, len(sessions)) for i, s := range sessions { selected := m.inSessions && i == m.sessionCursor - glyph, style := "· ", DefaultStyles.Faint + glyph, style := "· ", chrome.DefaultStyles.Faint switch { case selected: - glyph, style = "◆ ", DefaultStyles.Agent + glyph, style = "◆ ", chrome.DefaultStyles.Agent case s.LastAssistantAt != nil && now.Sub(time.Unix(*s.LastAssistantAt, 0)) < time.Hour: - glyph, style = "● ", DefaultStyles.Success + glyph, style = "● ", chrome.DefaultStyles.Success } - titleStyle := DefaultStyles.Muted + titleStyle := chrome.DefaultStyles.Muted bar := " " if selected { - titleStyle = DefaultStyles.Bold - bar = selectBar() + titleStyle = chrome.DefaultStyles.Bold + bar = chrome.SelectBar() } title := titleStyle.Render(sessionTitle(s)) line := bar + " " + style.Render(glyph) + title if s.LastAssistantAt != nil { - line += DefaultStyles.Faint.Render(" " + svCompactAge(s.LastAssistantAt, now)) + line += chrome.DefaultStyles.Faint.Render(" " + svCompactAge(s.LastAssistantAt, now)) } if selected { - line = selectedLine(line, width) + line = chrome.SelectedLine(line, width) } rows[i] = line } if len(rows) > room && !m.inSessions { - rows = append(rows[:room-1], DefaultStyles.Faint.Render(fmt.Sprintf(" … %d more", len(sessions)-room+1))) + rows = append(rows[:room-1], chrome.DefaultStyles.Faint.Render(fmt.Sprintf(" … %d more", len(sessions)-room+1))) } return scrollWindow(rows, m.sessionCursor, width, min(room, len(rows))) } @@ -573,10 +576,10 @@ func (m FolderPicker) sessionsFor(row folderRow) []daemon.Session { // leads. func (m FolderPicker) paneRule(p string, languages []daemon.LanguageShare, w int) string { parts := crumbParts(m.homed(p)) - lead := func() string { return DefaultStyles.Decor.Render("─ ") + crumbs(parts) + " " } + lead := func() string { return chrome.DefaultStyles.Decor.Render("─ ") + crumbs(parts) + " " } tail := "" if len(languages) > 0 { - tail = " " + languageStyle(languages[0].Name, knownLanguageColor(languages[0].Color)).Render(strings.ToLower(languages[0].Name)) + " " + tail = " " + chrome.LanguageStyle(languages[0].Name, knownLanguageColor(languages[0].Color)).Render(strings.ToLower(languages[0].Name)) + " " } for len(parts) > 2 && ansi.StringWidth(lead()+tail) > w-8 { parts = append([]string{"…"}, parts[2:]...) @@ -590,10 +593,10 @@ func (m FolderPicker) paneRule(p string, languages []daemon.LanguageShare, w int for _, l := range languages { sum += l.Share k := min(n, int(float64(n)*sum+0.5)) - used - rule.WriteString(languageStyle(l.Name, knownLanguageColor(l.Color)).Render(strings.Repeat("─", k))) + rule.WriteString(chrome.LanguageStyle(l.Name, knownLanguageColor(l.Color)).Render(strings.Repeat("─", k))) used += k } - rule.WriteString(DefaultStyles.Decor.Render(strings.Repeat("─", n-used))) + rule.WriteString(chrome.DefaultStyles.Decor.Render(strings.Repeat("─", n-used))) return lead() + rule.String() + tail } @@ -601,15 +604,15 @@ func (m FolderPicker) paneRule(p string, languages []daemon.LanguageShare, w int func crumbs(parts []string) string { out := make([]string, len(parts)) for i, p := range parts { - out[i] = DefaultStyles.Muted.Bold(i == len(parts)-1).Render(p) + out[i] = chrome.DefaultStyles.Muted.Bold(i == len(parts)-1).Render(p) } - return strings.Join(out, DefaultStyles.Decor.Render(" › ")) + return strings.Join(out, chrome.DefaultStyles.Decor.Render(" › ")) } // plainRule is a section rule without a count. func plainRule(label string, w int) string { head := " " + label + " " - return DefaultStyles.Decor.Render("─") + DefaultStyles.Muted.Bold(true).Render(head) + DefaultStyles.Decor.Render(strings.Repeat("─", max(0, w-1-ansi.StringWidth(head)))) + return chrome.DefaultStyles.Decor.Render("─") + chrome.DefaultStyles.Muted.Bold(true).Render(head) + chrome.DefaultStyles.Decor.Render(strings.Repeat("─", max(0, w-1-ansi.StringWidth(head)))) } // repoLine is the repository at the root of the tree: the head, how many @@ -620,23 +623,23 @@ func repoLine(r *daemon.Repo, now time.Time) string { case r.Kind == "jj": head := "" if r.Bookmark != nil { - head = DefaultStyles.Agent.Render("⚑ " + r.Bookmark.Name) + head = chrome.DefaultStyles.Agent.Render("⚑ " + r.Bookmark.Name) if r.Bookmark.Ahead > 0 { - head += DefaultStyles.Faint.Render(fmt.Sprintf("+%d", r.Bookmark.Ahead)) + head += chrome.DefaultStyles.Faint.Render(fmt.Sprintf("+%d", r.Bookmark.Ahead)) } parts = append(parts, head) } if r.Change != "" { - parts = append(parts, DefaultStyles.Faint.Render("@ ")+DefaultStyles.Muted.Render(r.Change)) + parts = append(parts, chrome.DefaultStyles.Faint.Render("@ ")+chrome.DefaultStyles.Muted.Render(r.Change)) } case r.Branch != "" || r.Commit != "": - parts = append(parts, DefaultStyles.Agent.Render("⎇ "+cmp.Or(r.Branch, r.Commit))) + parts = append(parts, chrome.DefaultStyles.Agent.Render("⎇ "+cmp.Or(r.Branch, r.Commit))) } if r.Changed != nil && *r.Changed > 0 { - parts = append(parts, DefaultStyles.Warning.Render(fmt.Sprintf("✎ %d", *r.Changed))) + parts = append(parts, chrome.DefaultStyles.Warning.Render(fmt.Sprintf("✎ %d", *r.Changed))) } if r.Touched != nil { - parts = append(parts, DefaultStyles.Faint.Render(svCompactAge(r.Touched, now))) + parts = append(parts, chrome.DefaultStyles.Faint.Render(svCompactAge(r.Touched, now))) } return strings.Join(parts, " ") } @@ -672,16 +675,16 @@ func folderTree(p daemon.FolderPreview, children, top int) []string { if last { text = "╰─ " } - return DefaultStyles.Decor.Render(text) + return chrome.DefaultStyles.Decor.Render(text) } - more := func(n int) string { return DefaultStyles.Faint.Render(fmt.Sprintf("… %d more", n)) } + more := func(n int) string { return chrome.DefaultStyles.Faint.Render(fmt.Sprintf("… %d more", n)) } name := func(n daemon.FolderNode) string { - s := DefaultStyles.Muted.Render(n.Name) + DefaultStyles.Decor.Render("/") + s := chrome.DefaultStyles.Muted.Render(n.Name) + chrome.DefaultStyles.Decor.Render("/") if !n.Dir { - s = languageStyle(n.Language, colors[n.Language]).Render(n.Name) + s = chrome.LanguageStyle(n.Language, colors[n.Language]).Render(n.Name) } if n.Changed > 0 { - s += " " + DefaultStyles.Faint.Render(fmt.Sprintf("✎ %d", n.Changed)) + s += " " + chrome.DefaultStyles.Faint.Render(fmt.Sprintf("✎ %d", n.Changed)) } return s } @@ -697,7 +700,7 @@ func folderTree(p daemon.FolderPreview, children, top int) []string { if last { indentText = " " } - indent := DefaultStyles.Decor.Render(indentText) + indent := chrome.DefaultStyles.Decor.Render(indentText) shown := entry.Children[:min(children, len(entry.Children))] rest := entry.More + len(entry.Children) - len(shown) for j, child := range shown { diff --git a/cli/internal/tui/folder_query.go b/cli/internal/tui/folder_query.go index f0142fb7b..facc925a5 100644 --- a/cli/internal/tui/folder_query.go +++ b/cli/internal/tui/folder_query.go @@ -8,6 +8,9 @@ import ( "strings" "time" + "albedo/cli/internal/pickersearch" + "albedo/cli/internal/tui/chrome" + "github.com/sahilm/fuzzy" ) @@ -179,7 +182,7 @@ func recentFolders(sessions []daemon.Session, current string, now time.Time) []r // fuzzyNames matches segment against names via matchFields, best first; an // empty segment keeps them all in order. func fuzzyNames(segment string, names []string) []fuzzy.Match { - words := searchWords(segment) + words := pickersearch.Words(segment) if len(words) == 0 { all := make([]fuzzy.Match, len(names)) for i, n := range names { @@ -189,15 +192,15 @@ func fuzzyNames(segment string, names []string) []fuzzy.Match { } type scored struct { match fuzzy.Match - rank matchRank + rank pickersearch.Rank } var out []scored for i, n := range names { - if rank, hits, ok := matchFields(words, n); ok { + if rank, hits, ok := pickersearch.Match(words, n); ok { out = append(out, scored{fuzzy.Match{Str: n, Index: i, MatchedIndexes: hits}, rank}) } } - slices.SortStableFunc(out, func(a, b scored) int { return b.rank.compare(a.rank) }) + slices.SortStableFunc(out, func(a, b scored) int { return b.rank.Compare(a.rank) }) res := make([]fuzzy.Match, len(out)) for i, s := range out { res[i] = s.match @@ -400,7 +403,7 @@ func (m FolderPicker) parentQuery() string { if rest == "~" { return m.input.Value() } - return host + ":" + scpRelative(path.Dir(rest)) + "/" + return host + ":" + chrome.ScpRelative(path.Dir(rest)) + "/" } up := m.homed(parentPlace(dir)) if strings.HasSuffix(up, "/") { diff --git a/cli/internal/tui/form.go b/cli/internal/tui/form.go index b8c777769..34933397f 100644 --- a/cli/internal/tui/form.go +++ b/cli/internal/tui/form.go @@ -4,6 +4,8 @@ import ( "slices" "strings" + "albedo/cli/internal/tui/chrome" + "charm.land/bubbles/v2/textinput" tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" @@ -16,13 +18,6 @@ type form struct { Focus int } -// newField is a text input that follows a label instead of a prompt. -func newField() textinput.Model { - input := newTextInput() - input.Prompt = "" - return input -} - // ask re-arms input for the next question, masking a secret, and reports // the blink command that shows its cursor. func ask(input *textinput.Model, value string, secret bool) tea.Cmd { @@ -45,7 +40,7 @@ func echo(secret bool) textinput.EchoMode { func newForm(keys []string, masked ...string) form { f := form{Inputs: map[string]*textinput.Model{}} for _, key := range keys { - input := newField() + input := chrome.NewField() input.CharLimit, input.EchoMode = 4096, echo(slices.Contains(masked, key)) f.Inputs[key] = &input } @@ -110,23 +105,23 @@ func (f form) fit(width int) { func formRow(focused bool, label string, pad int, value string, width int) string { lead := " " if focused { - lead = promptLead() + lead = chrome.PromptLead() } return ansi.Truncate(lead+padRight(label, pad)+value, width, "…") } // formFooter explains the focused field, then offers the keys every form // shares after any of its own. -func formFooter(note string, width int, own ...hint) string { - hints := append(own, hint{"tab/↑↓", "move"}, hint{"ctrl+s", "save"}, hint{"enter", "next"}, hint{"esc", "cancel"}) +func formFooter(note string, width int, own ...chrome.Hint) string { + hints := append(own, chrome.Hint{Key: "tab/↑↓", Does: "move"}, chrome.Hint{Key: "ctrl+s", Does: "save"}, chrome.Hint{Key: "enter", Does: "next"}, chrome.Hint{Key: "esc", Does: "cancel"}) if note == "" { - return footerLine(width, hints, "", false) + return chrome.FooterLine(width, hints, "", false) } - note = DefaultStyles.Faint.Render(note) - if keys := fitHints(hints, width-ansi.StringWidth(note)-3); keys != "" { - return " " + note + DefaultStyles.Decor.Render(" · ") + keys[1:] + note = chrome.DefaultStyles.Faint.Render(note) + if keys := chrome.FitHints(hints, width-ansi.StringWidth(note)-3); keys != "" { + return " " + note + chrome.DefaultStyles.Decor.Render(" · ") + keys[1:] } - return " " + ansi.Truncate(note, max(1, width-2), "…") + "\n" + footerLine(width, hints, "", false) + return " " + ansi.Truncate(note, max(1, width-2), "…") + "\n" + chrome.FooterLine(width, hints, "", false) } func padRight(s string, n int) string { diff --git a/cli/internal/tui/frame.go b/cli/internal/tui/frame.go index def23f9fe..d989b5cdb 100644 --- a/cli/internal/tui/frame.go +++ b/cli/internal/tui/frame.go @@ -1,38 +1,19 @@ package tui import ( - "cmp" - "slices" - "strings" + "albedo/cli/internal/terminalui" + + "albedo/cli/internal/tui/chrome" "charm.land/lipgloss/v2" "github.com/charmbracelet/x/ansi" ) -// listFrame is the layout every list screen shares: the title rule, an optional -// filter, the list beside the highlighted row's detail pane when there is -// room, and the footer, all clipped to the terminal once. A screen supplies -// the parts and none of the arithmetic. -type listFrame struct { - title, right string // the title rule's two ends, styled - filter string // the search line as drawn; empty for a screen without one - list func(width, height int) []string - // pane is the detail beside the list; nil for a list alone. - pane func(width, height int) []string - // paneWidth is the pane's width at a terminal width; nil is sidePane. - paneWidth func(width int) int - // summary is the detail's one-line stand-in when the pane has no room at all. - summary string - // footer is the finished bottom rows: hints, status, or a confirmation. - footer string -} - // Side by side needs this much terminal; a narrower one with this many body // rows stacks the pane under the list instead, which gets the larger part. const ( - paneMinWidth = 96 - paneMinHeight = 14 - stackMinBody = 12 + paneMinWidth = terminalui.SideWidth + paneMinHeight = terminalui.SideHeight ) // inset moves rows drawn in the list's place, a form or a guide, to the @@ -58,135 +39,25 @@ func guideText(width int, style lipgloss.Style, text string) []string { // guideStep is one numbered step of a guide: its title, then its detail // faint and hung under the title. func guideStep(width int, n, title, detail string) []string { - lines := []string{" " + DefaultStyles.Prompt.Render(n) + " " + title} + lines := []string{" " + chrome.DefaultStyles.Prompt.Render(n) + " " + title} for _, l := range svWrap(detail, max(1, width-9), 3) { - lines = append(lines, " "+DefaultStyles.Faint.Render(l)) + lines = append(lines, " "+chrome.DefaultStyles.Faint.Render(l)) } return append(lines, "") } -// sidePane is a narrow detail column for facts about the highlighted row. -func sidePane(width int) int { return min(max(width/3, 34), 48) } - // halfPane is half the terminal, for previews that read like text. func halfPane(width int) int { return width - width/2 - ansi.StringWidth(svSep()) } -// view draws the frame at exactly the terminal's size or less; an unsized -// terminal is 80 by 24. -func (f listFrame) view(width, height int) string { - width, height = cmp.Or(width, 80), cmp.Or(height, 24) - roomy := height >= 12 - - lines := []string{" " + titleRule(width-1, f.title, f.right)} - if roomy { - lines = append(lines, "") - } - if f.filter != "" { - lines = append(lines, " "+f.filter) - if height >= 9 { - lines = append(lines, "") - } - } - - paned := f.pane != nil && width >= paneMinWidth && height >= paneMinHeight - var tail []string - if roomy { - tail = append(tail, "") - } - tail = append(tail, strings.Split(f.footer, "\n")...) - body := max(1, height-len(lines)-len(tail)) - stacked := !paned && f.pane != nil && body >= stackMinBody - if !paned && !stacked && f.summary != "" && height >= 16 { - tail = slices.Insert(tail, len(tail)-strings.Count(f.footer, "\n")-1, " "+f.summary) - body = max(1, height-len(lines)-len(tail)) - } - - if paned { - paneW := sidePane(width) - if f.paneWidth != nil { - paneW = f.paneWidth(width) - } - list := f.list(width-paneW-ansi.StringWidth(svSep()), body) - pane := f.pane(paneW, body) - for i := range body { - lines = append(lines, list[i]+svSep()+pane[i]) - } - } else if stacked { - // The pane gets the rows a short list leaves blank. - paneH := body * 2 / 5 - list := f.list(width, body-paneH-1) - used := len(list) - for used > 1 && strings.TrimSpace(ansi.Strip(list[used-1])) == "" { - used-- - } - paneH = body - used - 1 - lines = append(lines, list[:used]...) - lines = append(lines, " "+DefaultStyles.Decor.Render(strings.Repeat("─", max(0, width-2)))) - for _, line := range f.pane(width-1, paneH) { - lines = append(lines, " "+line) - } - } else { - list := f.list(width, body) - lines = append(lines, list...) - lines = append(lines, make([]string, max(0, body-len(list)))...) - } - lines = append(lines, tail...) - - if len(lines) > height { - lines = append(lines[:max(0, height-1)], lines[len(lines)-1]) - } - for i, line := range lines { - lines[i] = ansi.Truncate(line, width, "…") - } - return strings.Join(lines, "\n") +func pageTheme() terminalui.Chrome { + return terminalui.Chrome{Title: chrome.TitleRule, Rule: chrome.DefaultStyles.Decor, Divider: svSep()} } // notice is a notice in the colour of what it reports: a warning, or a save // that went through. func notice(text string, warns bool) string { if warns { - return DefaultStyles.Warning.Render(text) - } - return DefaultStyles.Success.Render(text) -} - -// footerLine is the keys on the left and a status on the right. When both -// do not fit, an urgent status (an error, a notice, work in flight) takes -// a row of its own above the keys, and any other status gives way to them. -// The keys lose their labels only when no three labelled hints fit at all. -func footerLine(width int, hints []hint, status string, urgent bool) string { - if len(hints) == 0 { - return statusRows(width, status) - } - if status != "" { - left := fitHints(hints, width-ansi.StringWidth(status)-3) - if left != "" && (urgent || left == " "+keyHints(hints...)) { - return left + strings.Repeat(" ", width-ansi.StringWidth(left)-ansi.StringWidth(status)-1) + status - } - } - keys := fitHints(hints, width-1) - if keys == "" { - bare := make([]hint, len(hints)) - for i, h := range hints { - bare[i] = hint{key: h.key} - if h.key == "" { - bare[i].does = h.does - } - } - keys = " " + ansi.Truncate(keyHints(bare...), max(1, width-2), "…") - } - if urgent && status != "" { - return statusRows(width, status) + "\n" + keys - } - return keys -} - -// statusRows is a status on rows of its own, wrapped to two at most. -func statusRows(width int, status string) string { - rows := strings.Split(lipgloss.Wrap(status, max(1, width-2), " /"), "\n") - if len(rows) > 2 { - rows = rows[:2] - rows[1] = ansi.Truncate(rows[1], max(1, width-3), "") + "…" + return chrome.DefaultStyles.Warning.Render(text) } - return " " + strings.Join(rows, "\n ") + return chrome.DefaultStyles.Success.Render(text) } diff --git a/cli/internal/tui/frame_cache_test.go b/cli/internal/tui/frame_cache_test.go index dac13d81d..295d3507e 100644 --- a/cli/internal/tui/frame_cache_test.go +++ b/cli/internal/tui/frame_cache_test.go @@ -9,6 +9,7 @@ import ( "testing" "albedo/cli/internal/daemon" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -233,3 +234,42 @@ func TestComposerCacheFollowsTheTextarea(t *testing.T) { t.Fatal("the draft vanished from the composer") } } + +// An idle snapshot replays the persisted reply without its live completion event. +func TestResumedReplyHasTimedCopyableSignoff(t *testing.T) { + for _, running := range []bool{false, true} { + conn := daemon.NewConnection(daemon.ConnectionSnapshot{Port: 1}, nil) + m := NewChatModel(&daemon.Session{ID: "s"}, daemon.NewChatClient(conn, "s")) + m.SetSize(80, 24) + start, end := int64(1000), int64(4200) + const reply = "**original** markdown" + for _, event := range []daemon.StreamEvent{ + {Type: daemon.EventReset, Snapshot: &daemon.Session{Status: daemon.AgentStatus{Running: running, Idle: !running}}}, + {Type: daemon.EventUser, Replayed: true, Timestamp: &start, Text: "hello"}, + {Type: daemon.EventMessage, Replayed: true, Timestamp: &end, Text: reply}, + {Type: daemon.EventUsage, Replayed: true, SnapshotOrigin: true, EndsIdleHistory: !running}, + } { + m.handleStreamEvent(event) + } + m.refreshViewportContent() + rows := strings.Split(ansi.Strip(m.View()), "\n") + found := false + for _, row := range rows { + if strings.Contains(row, "⧉") { + found = true + if !strings.Contains(row, "3s") || !strings.Contains(row, outcome(false, false, end-start).face(end)) { + t.Fatalf("restored signoff lost face or elapsed time: %q", row) + } + } + } + if found == running { + t.Fatalf("running=%v: signoff visible=%v", running, found) + } + if found { + last := m.History.Entries()[m.History.Len()-1] + if got, ok := m.replyMarkdown(entryKey(last)); !ok || got != reply { + t.Fatalf("restored copy returned %q, %v", got, ok) + } + } + } +} diff --git a/cli/internal/tui/list_view.go b/cli/internal/tui/list_view.go index fa24e6167..8d2022159 100644 --- a/cli/internal/tui/list_view.go +++ b/cli/internal/tui/list_view.go @@ -1,9 +1,13 @@ package tui import ( + "albedo/cli/internal/terminalui" "slices" "strings" + "albedo/cli/internal/pickersearch" + "albedo/cli/internal/tui/chrome" + "charm.land/bubbles/v2/textinput" tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" @@ -40,8 +44,9 @@ type listShown struct { // or type belong to it; keys that act on a row belong to the screen, which // asks for them first. Actions are therefore never bare letters. type listView struct { - rows []listEntry - shown []listShown + layout *listLayout + rows []listEntry + shown []listShown // Empty is said when there are no rows at all. Empty string groupTitle func(group string, width int) string @@ -54,10 +59,10 @@ type listView struct { // newFilter is a focused search field. func newFilter(placeholder string) textinput.Model { - input := newField() + input := chrome.NewField() input.Placeholder = placeholder st := input.Styles() - st.Focused.Placeholder, st.Blurred.Placeholder = DefaultStyles.Faint, DefaultStyles.Faint + st.Focused.Placeholder, st.Blurred.Placeholder = chrome.DefaultStyles.Faint, chrome.DefaultStyles.Faint input.SetStyles(st) input.Focus() return input @@ -87,10 +92,10 @@ func (l *listView) setRows(rows []listEntry) { // section, sections within their group by their best row, and groups by // their best section; an empty filter keeps the order the rows came in. func (l *listView) refilter(keep string) { - words := searchWords(l.input.Value()) + words := pickersearch.Words(l.input.Value()) type scored struct { shown listShown - rank matchRank + rank pickersearch.Rank } type bucket struct{ group, section string } var order []bucket @@ -107,7 +112,7 @@ func (l *listView) refilter(keep string) { if r.hidden && len(words) == 0 { continue } - rank, hits, ok := matchFields(words, append([]string{r.name, r.desc}, r.search...)...) + rank, hits, ok := pickersearch.Match(words, append([]string{r.name, r.desc}, r.search...)...) if !ok { continue } @@ -119,9 +124,9 @@ func (l *listView) refilter(keep string) { } if len(words) > 0 { for _, g := range buckets { - slices.SortStableFunc(g, func(a, b scored) int { return b.rank.compare(a.rank) }) + slices.SortStableFunc(g, func(a, b scored) int { return b.rank.Compare(a.rank) }) } - slices.SortStableFunc(order, func(a, b bucket) int { return buckets[b][0].rank.compare(buckets[a][0].rank) }) + slices.SortStableFunc(order, func(a, b bucket) int { return buckets[b][0].rank.Compare(buckets[a][0].rank) }) } // A group stands where its best section stands, its other sections after. var groups []string @@ -151,6 +156,7 @@ func (l *listView) refilter(keep string) { } } } + l.layout = &listLayout{} l.Cursor = max(0, slices.IndexFunc(l.shown, func(s listShown) bool { return l.rows[s.row].key == keep })) if keep == "" && len(words) > 0 && len(l.shown) > 1 && l.rows[l.shown[0].row].heading { l.Cursor = 1 @@ -187,14 +193,14 @@ func (l *listView) update(msg tea.Msg) tea.Cmd { return cmd } -func (l listView) filterLine() string { return promptLead() + l.input.View() } +func (l listView) filterLine() string { return chrome.PromptLead() + l.input.View() } // frame is the screen's layout around this list and the highlighted row's // detail. -func (l listView) frame(title, right, footer string) listFrame { - f := listFrame{title: title, right: right, filter: l.filterLine(), list: l.list, footer: footer} +func (l listView) frame(title, right, footer string) terminalui.Page { + f := terminalui.Page{Title: title, Meta: right, Filter: l.filterLine(), List: l.list, Footer: footer} if len(l.shown) > 0 { - f.pane = l.pane + f.Detail = l.pane } return f } @@ -208,123 +214,100 @@ func (l listView) list(width, height int) []string { note = svWrap(l.Empty, max(1, width-3), height) } for i, line := range note { - note[i] = DefaultStyles.Faint.Render(" " + line) + note[i] = chrome.DefaultStyles.Faint.Render(" " + line) } return scrollWindow(note, -1, width, height) } - leadW, nameW, tagW, described := 0, 0, 0, false - for _, s := range l.shown { - r := l.rows[s.row] - leadW = max(leadW, ansi.StringWidth(r.lead)) - nameW = max(nameW, ansi.StringWidth(r.name)) - tagW = max(tagW, ansi.StringWidth(r.tag), ansi.StringWidth(r.selTag)) - described = described || r.desc != "" + layout := l.layout + if layout == nil { + layout = &listLayout{} } - if described { - nameW = min(nameW, max(12, width/3)) - } else { - nameW = min(nameW, width-leadW-6-tagW) + compact := height < 10 + if !layout.ready || width != layout.width || compact != layout.compact { + *layout = l.measureList(width, compact) } - - type line struct { - text string - shown int // the row it draws, or -1 for a heading or rule + lines := layout.index.Window(l.Cursor, height, chrome.DefaultStyles.Faint.Render(" ···"), func(i int, selected bool) string { + return l.row(l.shown[i], selected, width, layout.lead, layout.name) + }) + for i, line := range lines { + lines[i] = chrome.Fit(line, width) } - var all []line - selectedAt := -1 - for i, s := range l.shown { - r := l.rows[s.row] - var prev *listEntry - if i > 0 { - prev = &l.rows[l.shown[i-1].row] - } - newGroup := r.group != "" && (prev == nil || prev.group != r.group) - if newGroup { - // A group's heading has no rule of its own, so it keeps its gap. - if len(all) > 0 { - all = append(all, line{shown: -1}) - } - heading := groupHeading(r.group, width) + return lines +} + +type listLayout struct { + index terminalui.ListIndex + width, lead, name int + compact, ready bool +} + +// A new query or listing replaces this index; moving the cursor paints only +// the visible rows. Resizing updates column widths and section headings. +func (l listView) measureList(width int, compact bool) listLayout { + layout := listLayout{ready: true, width: width, compact: compact} + tag := 0 + described := false + for start := 0; start < len(l.shown); { + first := l.rows[l.shown[start].row] + newGroup := start == 0 || first.group != l.rows[l.shown[start-1].row].group + if newGroup && first.group != "" { + layout.index.Gap() + heading := chrome.GroupHeading if l.groupTitle != nil { - heading = l.groupTitle(r.group, width) + heading = l.groupTitle } - if heading != "" { - all = append(all, line{text: heading, shown: -1}) + if title := heading(first.group, width); title != "" { + layout.index.Heading(title) } } - if r.section != "" && (prev == nil || prev.group != r.group || prev.section != r.section) { - var keys, parents []string - for _, s := range l.shown[i:] { - next := l.rows[s.row] - if next.group != r.group || next.section != r.section { - break - } - if next.parent == "" { - keys = append(keys, next.key) - } else { - parents = append(parents, next.parent) - } + end := start + parents := map[string]struct{}{} + roots := 0 + for end < len(l.shown) { + r := l.rows[l.shown[end].row] + if r.group != first.group || r.section != first.section { + break } - run := len(keys) - slices.Sort(parents) - for _, parent := range slices.Compact(parents) { - if !slices.Contains(keys, parent) { - run++ - } + if r.parent != "" { + parents[r.parent] = struct{}{} + } else { + roots++ } - if !newGroup && len(all) > 0 && height >= 10 { - all = append(all, line{shown: -1}) + layout.lead = max(layout.lead, ansi.StringWidth(r.lead)) + layout.name = max(layout.name, ansi.StringWidth(r.name)) + tag = max(tag, ansi.StringWidth(r.selTag), ansi.StringWidth(r.tag)) + described = described || r.desc != "" + end++ + } + if first.section != "" { + if !compact && (!newGroup || first.group == "") { + layout.index.Gap() } - rule := sectionRule(r.section, run, width) + var title string if l.sectionTitle != nil { - rule = l.sectionTitle(r.section, width) + title = l.sectionTitle(first.section, width) + } else { + for _, item := range l.shown[start:end] { + r := l.rows[item.row] + if r.parent == "" { + delete(parents, r.key) + } + } + title = chrome.SectionRule(first.section, roots+len(parents), width) } - all = append(all, line{text: rule, shown: -1}) - } - if i == l.Cursor { - selectedAt = len(all) - } - all = append(all, line{shown: i}) - } - // A window never ends on a heading with none of its rows under it, and - // one that starts inside a group shows that group's heading on top. - start, cut := windowStart(len(all), selectedAt, height), len(all) > height && height >= 3 - headingAt := func(at int) bool { - if all[at].shown < 0 { - return true + layout.index.Heading(title) } - r := l.rows[l.shown[all[at].shown].row] - if !r.heading || at+1 >= len(all) || all[at+1].shown < 0 { - return false + for _, item := range l.shown[start:end] { + layout.index.Item(l.rows[item.row].heading) } - return l.rows[l.shown[all[at+1].shown].row].group == r.group - } - orphan := func() bool { return cut && start < len(all)-height && headingAt(start+height-2) } - for orphan() && start > 0 && selectedAt < start+height-3 { - start-- + start = end } - for orphan() && selectedAt > start+1 { - start++ - } - out := drawFrom(len(all), func(i int) string { - if all[i].shown < 0 { - return all[i].text - } - return l.row(l.shown[all[i].shown], all[i].shown == l.Cursor, width, leadW, nameW) - }, start, width, height) - if cut && start > 0 && all[start+1].shown >= 0 { - for i := start; i >= 0; i-- { - if all[i].shown >= 0 && l.rows[l.shown[all[i].shown].row].heading { - out[0] = svFit(l.row(l.shown[all[i].shown], false, width, leadW, nameW), width) - break - } - if all[i].shown < 0 && all[i].text != "" { - out[0] = svFit(all[i].text, width) - break - } - } + if described { + layout.name = min(layout.name, max(12, width/3)) + } else { + layout.name = min(layout.name, max(1, width-layout.lead-6-tag)) } - return out + return layout } func (l listView) row(s listShown, selected bool, width, leadW, nameW int) string { @@ -332,23 +315,23 @@ func (l listView) row(s listShown, selected bool, width, leadW, nameW int) strin if r.draw != nil { bar := " " if selected { - bar = selectBar() + bar = chrome.SelectBar() } line := bar + " " + r.draw(max(1, width-3), s.hits) if selected { - return selectedLine(line, width) + return chrome.SelectedLine(line, width) } return line } bar, nameStyle, tag := " ", lipgloss.NewStyle(), r.tag switch { case selected: - bar, nameStyle = selectBar(), DefaultStyles.Bold + bar, nameStyle = chrome.SelectBar(), chrome.DefaultStyles.Bold if r.selTag != "" { tag = r.selTag } case r.faint: - nameStyle = DefaultStyles.Faint + nameStyle = chrome.DefaultStyles.Faint } line := bar + " " if leadW > 0 { @@ -360,13 +343,13 @@ func (l listView) row(s listShown, selected bool, width, leadW, nameW int) strin room -= ansi.StringWidth(tag) + 2 } if r.desc != "" && room >= 4 { - line += DefaultStyles.Faint.Render(" " + ansi.Truncate(r.desc, room, "…")) + line += chrome.DefaultStyles.Faint.Render(" " + ansi.Truncate(r.desc, room, "…")) } if tag != "" { line += strings.Repeat(" ", max(2, width-ansi.StringWidth(line)-ansi.StringWidth(tag)-1)) + tag } if selected { - return selectedLine(line, width) + return chrome.SelectedLine(line, width) } return line } @@ -392,14 +375,14 @@ func detailPane(detail func(width int) []string) func(width, height int) []strin func paneTitle(name, description string, width int) []string { var lines []string for _, l := range svWrap(name, width, 2) { - lines = append(lines, DefaultStyles.Bold.Render(l)) + lines = append(lines, chrome.DefaultStyles.Bold.Render(l)) } for _, l := range svWrap(description, width, 3) { if l != "" { - lines = append(lines, DefaultStyles.Muted.Render(l)) + lines = append(lines, chrome.DefaultStyles.Muted.Render(l)) } } - return append(lines, DefaultStyles.Decor.Render(strings.Repeat("─", width))) + return append(lines, chrome.DefaultStyles.Decor.Render(strings.Repeat("─", width))) } // factLabelW is the label column of a detail pane's facts. @@ -412,7 +395,7 @@ func factRows(label, value string, width int) []string { for i, l := range svWrap(value, max(1, width-factLabelW), 4) { cell := strings.Repeat(" ", factLabelW) if i == 0 { - cell = DefaultStyles.Muted.Render(svCell(label, factLabelW, false)) + cell = chrome.DefaultStyles.Muted.Render(chrome.Cell(label, factLabelW, false)) } lines = append(lines, cell+l) } @@ -423,7 +406,7 @@ func factRows(label, value string, width int) []string { func paneNote(text string, width int) []string { var lines []string for _, l := range svWrap(text, width, 6) { - lines = append(lines, DefaultStyles.Faint.Render(l)) + lines = append(lines, chrome.DefaultStyles.Faint.Render(l)) } return lines } diff --git a/cli/internal/tui/location.go b/cli/internal/tui/location.go index c86845293..bc2c1bc72 100644 --- a/cli/internal/tui/location.go +++ b/cli/internal/tui/location.go @@ -6,6 +6,7 @@ import ( "strings" "albedo/cli/internal/daemon" + "albedo/cli/internal/tui/chrome" ) // sessionHost is how a session's host reads: the daemon's label, which @@ -28,11 +29,11 @@ func placeText(workspace, label, home string) string { host, p := daemon.SplitLocation(workspace) switch { case host != "": - return cmp.Or(label, host) + ":" + scpRelative(underHome(p, home)) + return cmp.Or(label, host) + ":" + chrome.ScpRelative(chrome.UnderHome(p, home)) case home == "": - return homePath(workspace) + return chrome.HomePath(workspace) } - return underHome(workspace, home) + return chrome.UnderHome(workspace, home) } // sessionPlace is where a session works, as placeText shows it. diff --git a/cli/internal/tui/login.go b/cli/internal/tui/login.go index 00dbc7137..87a1291b2 100644 --- a/cli/internal/tui/login.go +++ b/cli/internal/tui/login.go @@ -12,6 +12,8 @@ import ( "strings" "time" + "albedo/cli/internal/tui/chrome" + "charm.land/bubbles/v2/textinput" tea "charm.land/bubbletea/v2" ) @@ -59,10 +61,16 @@ type removal struct { } type LoginModel struct { - readCtx context.Context - cancelReads context.CancelFunc - Conn *daemon.Connection - openBrowser func(url string) + termsLogin daemon.SignIn + readCtx context.Context + cancelReads context.CancelFunc + Conn *daemon.Connection + openBrowser func(url string) + LoginValues map[string]json.RawMessage + SelectedAccount *daemon.Account + CredentialTicks map[string]bool + // terms warns before a sign-in in termsLogin starts. + terms *termsBox Removing removal Profiles config.Profiles Hint string @@ -70,29 +78,12 @@ type LoginModel struct { Provider string // sign-in provider in flight, or just finished LoginETag string LoginFlow, LoginInstructions string - LoginFields []daemon.FormField - LoginFieldIndex int - LoginValues map[string]json.RawMessage - SelectedAccount *daemon.Account LoginID string // daemon id of the sign-in in flight SignInURL string Status string // daemon progress line while a sign-in runs CatalogNote string Error string - Draft config.Settings - SignIns []daemon.SignIn - Accounts []daemon.Account - Catalog []string - TextInput textinput.Model - ChoosePicker loginPick - CredentialTicks map[string]bool - ProtocolPicker loginPick - ModelPicker loginPick - confirm - // terms warns before a sign-in in termsLogin starts. - terms *termsBox - termsLogin daemon.SignIn - RenameAccountID string + RenameAccountID string // reSignIn is the account an inline sign-in signs in again. reSignIn string // focus is the row the next rebuild of the accounts list highlights. @@ -100,6 +91,17 @@ type LoginModel struct { // listBusy is what the accounts list says while a change it made is // saved; rotationNote is what it says once that change is saved. listBusy, rotationNote string + confirm chrome.Confirm + LoginFields []daemon.FormField + SignIns []daemon.SignIn + Accounts []daemon.Account + Catalog []string + TextInput textinput.Model + Draft config.Settings + ChoosePicker loginPick + ProtocolPicker loginPick + ModelPicker loginPick + LoginFieldIndex int Generation int Width int Height int @@ -136,7 +138,7 @@ func NewLoginModel(conn *daemon.Connection, nameHint string, openBrowser func(st Profiles: profiles, Hint: strings.TrimSpace(nameHint), Draft: config.Settings{Extension: "openai", BaseURL: "https://api.openai.com/v1", Protocol: "responses"}, - TextInput: newField(), + TextInput: chrome.NewField(), openBrowser: openBrowser, } m.buildChoosePicker() @@ -206,7 +208,7 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { m.LoginID = msg.ID m.LoginETag = msg.ETag if msg.Err != nil { - m.Error = operationError(msg.Err, "", "Sign-in may have started; check your accounts before starting another. Its outcome cannot be confirmed from this response.") + m.Error = chrome.OperationError(msg.Err, "", "Sign-in may have started; check your accounts before starting another. Its outcome cannot be confirmed from this response.") if m.inline { m.buildChoosePicker() } diff --git a/cli/internal/tui/login_accounts.go b/cli/internal/tui/login_accounts.go index 5ec89aee9..efd4da825 100644 --- a/cli/internal/tui/login_accounts.go +++ b/cli/internal/tui/login_accounts.go @@ -13,6 +13,8 @@ import ( "strings" "time" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" ) @@ -75,7 +77,7 @@ func (m *LoginModel) buildAdvancedPicker() { note: "enter makes this the one new sessions use", } if name == m.Profiles.Active { - item.tag = DefaultStyles.Muted.Render("active") + item.tag = chrome.DefaultStyles.Muted.Render("active") item.note = "this is the one new sessions use" } items = append(items, item) @@ -117,7 +119,7 @@ func (m *LoginModel) buildAdvancedPicker() { detail := cmp.Or(login.Detail, "sign in") items = append(items, loginItem{ ID: "signin:" + login.Provider, Label: login.Label, Detail: detail, section: sectionNew, - lead: DefaultStyles.Muted.Render("+"), + lead: chrome.DefaultStyles.Muted.Render("+"), facts: append(signInFacts(login, accounts), loginFact{"auth", "one signed-in account, or a rotation of them"}), note: "enter names a new setup, then picks the account it signs in with", }) @@ -125,7 +127,7 @@ func (m *LoginModel) buildAdvancedPicker() { for _, p := range customProviders { items = append(items, loginItem{ ID: p.ID, Label: p.Label, Detail: p.Detail, section: sectionNew, - lead: DefaultStyles.Muted.Render("+"), + lead: chrome.DefaultStyles.Muted.Render("+"), facts: p.facts(), note: "enter names a new setup, or updates the one you name", }) @@ -209,13 +211,14 @@ func (m LoginModel) accountLabel(id string) string { // for tools rather than sessions, and whatever the daemon says about it. func accountDetail(account daemon.Account) string { parts := []string{account.Provider} - if account.Kind == "key" { + switch account.Kind { + case "key": host := account.Detail parts = []string{"key"} if host != "" { parts = append(parts, host) } - } else if account.Kind == "service" { + case "service": parts = append(parts, "service") } if account.Source == "env" { @@ -307,22 +310,22 @@ func (m *LoginModel) confirmRemoval(target removal) tea.Cmd { if account, ok := m.accountByID(target.ID); ok { consequence = m.signOutConsequence(account) } - m.confirm.ask("sign out", target.ID, "sign out", consequence) + m.confirm.Ask("sign out", target.ID, "sign out", consequence) return nil } - m.confirm.ask("remove", target.ID, "remove", "This removes the setup and its saved key; accounts stay signed in. Remove setup "+target.Label+"?") + m.confirm.Ask("remove", target.ID, "remove", "This removes the setup and its saved key; accounts stay signed in. Remove setup "+target.Label+"?") return nil } // confirmKey settles a key on the removal question: enter removes, esc keeps // what is there, and any other key is ignored. func (m *LoginModel) confirmKey(msg tea.KeyPressMsg) tea.Cmd { - if m.confirm.key(msg) { - m.confirm.dismiss() + if m.confirm.Key(msg) { + m.confirm.Dismiss() m.Step = StepSaving return m.removeCmd(m.Removing) } - if m.confirm.asking() { + if m.confirm.Asking() { return nil } return m.backToChoose() @@ -385,9 +388,9 @@ func (m *LoginModel) chooseAccount(account daemon.Account) tea.Cmd { } switch { case settings.AccountID != nil && *settings.AccountID == account.ID: - item.tag = DefaultStyles.Muted.Render("uses it") + item.tag = chrome.DefaultStyles.Muted.Render("uses it") case name == m.Profiles.Active: - item.tag = DefaultStyles.Muted.Render("active") + item.tag = chrome.DefaultStyles.Muted.Render("active") } if initial == newProfileRow { initial = item.ID @@ -398,7 +401,7 @@ func (m *LoginModel) chooseAccount(account daemon.Account) tea.Cmd { ID: newProfileRow, Label: "new profile", Detail: "a new " + account.Provider + " profile", - lead: DefaultStyles.Muted.Render("+"), + lead: chrome.DefaultStyles.Muted.Render("+"), facts: []loginFact{{"account", account.Label}}, note: "enter names a new profile that signs in as " + account.Label, }) @@ -678,17 +681,17 @@ func accountLimit(a daemon.Account) string { func accountLead(a daemon.Account) string { if a.NeedsSignIn { - return DefaultStyles.Error.Render("✕") + return chrome.DefaultStyles.Error.Render("✕") } if accountLimit(a) != "" { - return DefaultStyles.Warning.Render("!") + return chrome.DefaultStyles.Warning.Render("!") } - return DefaultStyles.Success.Render("●") + return chrome.DefaultStyles.Success.Render("●") } func accountTag(a daemon.Account) string { if a.NeedsSignIn { - return DefaultStyles.Error.Render("needs sign-in") + return chrome.DefaultStyles.Error.Render("needs sign-in") } - return DefaultStyles.Warning.Render(accountLimit(a)) + return chrome.DefaultStyles.Warning.Render(accountLimit(a)) } diff --git a/cli/internal/tui/login_profile.go b/cli/internal/tui/login_profile.go index 6dc0a456d..03d9b5cd6 100644 --- a/cli/internal/tui/login_profile.go +++ b/cli/internal/tui/login_profile.go @@ -10,6 +10,8 @@ import ( "strconv" "strings" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" ) @@ -147,7 +149,7 @@ func (m *LoginModel) chooseCredential() tea.Cmd { item := loginItem{ID: accountRowStart + account.ID, Label: account.Label, Detail: accountDetail(account), lead: accountLead(account), tag: accountTag(account), facts: m.accountFacts(account)} if m.CredentialTicks[item.ID] { - item.lead = DefaultStyles.Success.Render("✓") + item.lead = chrome.DefaultStyles.Success.Render("✓") } switch len(ids) { case 0: @@ -164,7 +166,7 @@ func (m *LoginModel) chooseCredential() tea.Cmd { label, detail = "another key", "enter an API key for this endpoint" } items = append(items, loginItem{ID: anotherAccount, Label: label, Detail: detail, - lead: DefaultStyles.Muted.Render("+"), note: "enter adds a credential; a rotation asks before adding it"}) + lead: chrome.DefaultStyles.Muted.Render("+"), note: "enter adds a credential; a rotation asks before adding it"}) initial := "" if m.Draft.AccountID != nil { initial = accountRowStart + *m.Draft.AccountID @@ -249,7 +251,7 @@ func (m *LoginModel) addedCredential(account daemon.Account) tea.Cmd { if len(m.Draft.AccountIDs) > 0 { m.SelectedAccount = &account m.Step = StepRotationPrompt - m.confirm.ask("rotate", account.ID, "continue", "add "+account.Label+" to "+m.Name+"'s rotation?") + m.confirm.Ask("rotate", account.ID, "continue", "add "+account.Label+" to "+m.Name+"'s rotation?") m.ChoosePicker = newLoginPick("add to rotation?", []loginItem{ {ID: "no", Label: "no", Detail: "keep the rotation unchanged"}, {ID: "yes", Label: "yes", Detail: "add " + account.Label}, @@ -265,7 +267,7 @@ func (m *LoginModel) rotationAnswer(add bool) tea.Cmd { m.Draft.AccountIDs = append(slices.Clone(m.Draft.AccountIDs), m.SelectedAccount.ID) } m.SelectedAccount = nil - m.confirm.dismiss() + m.confirm.Dismiss() return m.credentialChosen() } diff --git a/cli/internal/tui/login_test.go b/cli/internal/tui/login_test.go index 25145da5f..3f4b62edc 100644 --- a/cli/internal/tui/login_test.go +++ b/cli/internal/tui/login_test.go @@ -125,7 +125,7 @@ func TestAccountsSignOutSaysWhatKeepsRunningAndAsksEvenWhenPinned(t *testing.T) if !strings.Contains(plainView(m), "ChatGPT models stop working until you sign in again. Sessions keep their history.") { t.Fatalf("the last account's question does not warn:\n%s", plainView(m)) } - if m, _ = m.Update(tea.KeyPressMsg{Code: tea.KeyEscape}); m.Step != StepChoose || m.asking() { + if m, _ = m.Update(tea.KeyPressMsg{Code: tea.KeyEscape}); m.Step != StepChoose || m.confirm.Asking() { t.Fatalf("esc did not keep the account: step %v", m.Step) } } diff --git a/cli/internal/tui/login_view.go b/cli/internal/tui/login_view.go index 9ef883bcd..b6fa7f685 100644 --- a/cli/internal/tui/login_view.go +++ b/cli/internal/tui/login_view.go @@ -2,9 +2,12 @@ package tui import ( "albedo/cli/internal/config" + "albedo/cli/internal/terminalui" "cmp" "strings" + "albedo/cli/internal/tui/chrome" + tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -20,7 +23,7 @@ func linkRows(url string, width int) []string { id := "id=albedo-link" out := make([]string, len(rows)) for i, row := range rows { - out[i] = ansi.SetHyperlink(url, id) + DefaultStyles.Faint.Render(row) + ansi.ResetHyperlink() + out[i] = ansi.SetHyperlink(url, id) + chrome.DefaultStyles.Faint.Render(row) + ansi.ResetHyperlink() } return out } @@ -81,8 +84,7 @@ func (m *LoginModel) SetSize(width, height int) { // question's input in the search line for a text step, and the step's text // above it. Errors and progress sit in the footer. A terms warning sits over // all of it. -func (m LoginModel) View() string { - screen := m.screen() +func (m LoginModel) overlay(screen string) string { if m.terms != nil { width, height := cmp.Or(m.Width, 80), cmp.Or(m.Height, 24) return overlay(screen, m.terms.view(width, height), width, height) @@ -90,64 +92,64 @@ func (m LoginModel) View() string { return screen } -func (m LoginModel) screen() string { +func (m LoginModel) Page() terminalui.Page { width := cmp.Or(m.Width, 80) - title := brand("albedo") + " " + DefaultStyles.Muted.Render("/accounts") + title := chrome.Brand("albedo") + " " + chrome.DefaultStyles.Muted.Render("/accounts") if m.advanced { - title += DefaultStyles.Faint.Render(" › ") + DefaultStyles.Muted.Render("advanced") + title += chrome.DefaultStyles.Faint.Render(" › ") + chrome.DefaultStyles.Muted.Render("advanced") } right := m.Name onList := m.Step == StepChoose || m.Step == StepAdvanced || m.Step == StepAddKey || m.Step == StepRemove || m.Step == StepRotationPrompt || m.signingInline() || (m.Step == StepSaving && m.listBusy != "") if onList { - right = homePath(config.HomeDir()) + right = chrome.HomePath(config.HomeDir()) } if m.Step == StepChoose && m.accountsEmpty() { right = "no accounts yet" } if right != "" { - right = DefaultStyles.Faint.Render(right) + right = chrome.DefaultStyles.Faint.Render(right) } footer := m.footer(width) if m.Step == StepChoose && m.accountsEmpty() { - return listFrame{title: title, right: right, list: m.firstRunList, footer: footer}.view(m.Width, m.Height) + return terminalui.Page{Title: title, Meta: right, List: m.firstRunList, Footer: footer} } if m.signingInline() { f := m.accountsFrame(title, right, footer) if !m.signInOver() { - f.filter = promptLead() + DefaultStyles.Muted.Render(m.fieldLabel()+" ") + m.TextInput.View() + f.Filter = chrome.PromptLead() + chrome.DefaultStyles.Muted.Render(m.fieldLabel()+" ") + m.TextInput.View() } else { - f.filter = promptLead() + DefaultStyles.Faint.Render("the sign-in did not finish") + f.Filter = chrome.PromptLead() + chrome.DefaultStyles.Faint.Render("the sign-in did not finish") } - return f.view(m.Width, m.Height) + return f } if m.Step == StepSaving && m.listBusy != "" { - return m.accountsFrame(title, right, footer).view(m.Width, m.Height) + return m.accountsFrame(title, right, footer) } // A removal question keeps the list it asks about on screen, the way every // other confirm does. if m.listing() || (m.Step == StepRemove || m.Step == StepRotationPrompt) { if !m.advanced && (m.Step == StepChoose || m.Step == StepRemove) { - return m.accountsFrame(title, right, footer).view(m.Width, m.Height) + return m.accountsFrame(title, right, footer) } lv := m.pickerFor().listView lv.Empty = cmp.Or(lv.Empty, "nothing to choose") - return lv.frame(title, right, footer).view(m.Width, m.Height) + return lv.frame(title, right, footer) } - f := listFrame{ - title: title, - right: right, - filter: m.filterLine(), - list: m.bodyList, - footer: footer, + f := terminalui.Page{ + Title: title, + Meta: right, + Filter: m.filterLine(), + List: m.bodyList, + Footer: footer, } - return f.view(m.Width, m.Height) + return f } // accountsFrame is the accounts list in the frame, with a pane wide enough // for an account's facts on one row each. -func (m LoginModel) accountsFrame(title, right, footer string) listFrame { +func (m LoginModel) accountsFrame(title, right, footer string) terminalui.Page { f := m.ChoosePicker.frame(title, right, footer) - f.paneWidth = func(width int) int { return min(max(width*38/100, 36), 48) } + f.DetailWidth = func(width int) int { return min(max(width*38/100, 36), 48) } return f } @@ -157,7 +159,7 @@ func (m LoginModel) filterLine() string { if m.Step == StepSaving || m.signInOver() { return "" } - return promptLead() + DefaultStyles.Muted.Render(m.fieldLabel()+" ") + m.TextInput.View() + return chrome.PromptLead() + chrome.DefaultStyles.Muted.Render(m.fieldLabel()+" ") + m.TextInput.View() } // bodyList is the body in the list's place, on the frame's gutter. @@ -177,12 +179,12 @@ func (m LoginModel) body(width int) []string { case m.Editing: state = "saving " + m.Name + "…" } - return []string{DefaultStyles.Faint.Render(state)} + return []string{chrome.DefaultStyles.Faint.Render(state)} case StepOAuth: if m.signInOver() { - return []string{DefaultStyles.Muted.Render("The sign-in did not finish; the reason is in the footer.")} + return []string{chrome.DefaultStyles.Muted.Render("The sign-in did not finish; the reason is in the footer.")} } - lines := []string{DefaultStyles.Muted.Render(cmp.Or(m.Status, "starting sign-in…"))} + lines := []string{chrome.DefaultStyles.Muted.Render(cmp.Or(m.Status, "starting sign-in…"))} if m.LoginInstructions != "" { lines = append(lines, paneNote(m.LoginInstructions, width)...) } @@ -193,7 +195,7 @@ func (m LoginModel) body(width int) []string { lines = append(lines, "") return append(lines, paneNote(m.signInHint(), width)...) case StepModels, StepOAuthModels: - return []string{DefaultStyles.Faint.Render("loading models…")} + return []string{chrome.DefaultStyles.Faint.Render("loading models…")} } _, notes := m.question() var lines []string @@ -249,52 +251,52 @@ func (m LoginModel) question() (string, []string) { } // hints are the keys for the step, most important first. -func (m LoginModel) hints() []hint { +func (m LoginModel) hints() []chrome.Hint { switch { case m.Step == StepSaving: return nil case (m.Step == StepModels || m.Step == StepOAuthModels) && !m.listing(): - return []hint{{"esc", "back"}} + return []chrome.Hint{{Key: "esc", Does: "back"}} case m.Step == StepCredential: - return []hint{{"space", "tick"}, {"enter", m.enterVerb()}, {"↑↓", "move"}, {"esc", "back"}} + return []chrome.Hint{{Key: "space", Does: "tick"}, {Key: "enter", Does: m.enterVerb()}, {Key: "↑↓", Does: "move"}, {Key: "esc", Does: "back"}} case m.listing(): - hints := []hint{{"↑↓", "move"}} + hints := []chrome.Hint{{Key: "↑↓", Does: "move"}} if verb := m.enterVerb(); verb != "" { - hints = append(hints, hint{"enter", verb}) + hints = append(hints, chrome.Hint{Key: "enter", Does: verb}) } if item, ok := m.ChoosePicker.Highlighted(); ok && m.Step == StepAdvanced { if name, ok := m.highlightedProfile(); ok { if m.editable(name) { - hints = append(hints, hint{"ctrl+e", "edit"}) + hints = append(hints, chrome.Hint{Key: "ctrl+e", Does: "edit"}) } - hints = append(hints, hint{"ctrl+r", "rename"}) + hints = append(hints, chrome.Hint{Key: "ctrl+r", Does: "rename"}) } account, isAccount := m.accountAt(item.ID) external := isAccount && account.Source == "env" if isAccount && !external { - hints = append(hints, hint{"ctrl+r", "rename"}) + hints = append(hints, chrome.Hint{Key: "ctrl+r", Does: "rename"}) } if _, removable := m.removalFor(item.ID); removable && !external { verb := "remove" if isAccount { verb = "sign out" } - hints = append(hints, hint{"ctrl+x", verb}) + hints = append(hints, chrome.Hint{Key: "ctrl+x", Does: verb}) } } - return append(hints, hint{"esc", "back"}) + return append(hints, chrome.Hint{Key: "esc", Does: "back"}) case m.signInOver(): - return []hint{{"enter", "try again"}, {"esc", "cancel"}} + return []chrome.Hint{{Key: "enter", Does: "try again"}, {Key: "esc", Does: "cancel"}} case m.Step == StepOAuth: - return []hint{{"enter", "submit code"}, {"esc", "cancel"}} + return []chrome.Hint{{Key: "enter", Does: "submit code"}, {Key: "esc", Does: "cancel"}} case m.Step == StepAPIKey && m.Draft.APIKey != "": - return []hint{{"enter", "keeps the saved key"}, {"esc", "cancel"}} + return []chrome.Hint{{Key: "enter", Does: "keeps the saved key"}, {Key: "esc", Does: "cancel"}} case m.Step == StepRename: - return []hint{{"enter", "rename"}, {"esc", "back"}} + return []chrome.Hint{{Key: "enter", Does: "rename"}, {Key: "esc", Does: "back"}} case m.Step == StepProfileName: - return []hint{{"enter", "continue"}, {"esc", "back"}} + return []chrome.Hint{{Key: "enter", Does: "continue"}, {Key: "esc", Does: "back"}} } - return []hint{{"enter", "continue"}, {"esc", "cancel"}} + return []chrome.Hint{{Key: "enter", Does: "continue"}, {Key: "esc", Does: "cancel"}} } // enterVerb says what enter does on the list the step shows, naming the @@ -397,19 +399,19 @@ func (m LoginModel) footer(width int) string { return m.signOutFooter(width) } if m.Step == StepRotationPrompt { - return footerLine(width, []hint{{"↑↓", "choose"}, {"enter", "continue"}, {"esc", "no"}}, DefaultStyles.Warning.Render(m.confirm.prompt), true) + return chrome.FooterLine(width, []chrome.Hint{{Key: "↑↓", Does: "choose"}, {Key: "enter", Does: "continue"}, {Key: "esc", Does: "no"}}, chrome.DefaultStyles.Warning.Render(m.confirm.Prompt), true) } if m.Step == StepRemove { - return m.confirm.footer(width, m.Error) + return m.confirm.Footer(width, m.Error) } if m.Error != "" { - return footerLine(width, m.hints(), DefaultStyles.Error.Render(m.Error), true) + return chrome.FooterLine(width, m.hints(), chrome.DefaultStyles.Error.Render(m.Error), true) } status := "" if m.CatalogNote != "" && (m.Step == StepModels || m.Step == StepOAuthModels) { - status = DefaultStyles.Faint.Render(m.CatalogNote) + status = chrome.DefaultStyles.Faint.Render(m.CatalogNote) } else if m.Status != "" && (m.Step == StepChoose || m.Step == StepAdvanced) { - status = DefaultStyles.Faint.Render(m.Status) + status = chrome.DefaultStyles.Faint.Render(m.Status) } - return footerLine(width, m.hints(), status, m.Status != "" && (m.Step == StepChoose || m.Step == StepAdvanced)) + return chrome.FooterLine(width, m.hints(), status, m.Status != "" && (m.Step == StepChoose || m.Step == StepAdvanced)) } diff --git a/cli/internal/tui/markdown.go b/cli/internal/tui/markdown.go index ce21f53b5..3645e4cea 100644 --- a/cli/internal/tui/markdown.go +++ b/cli/internal/tui/markdown.go @@ -8,6 +8,8 @@ import ( "strings" "sync" + "albedo/cli/internal/tui/chrome" + "charm.land/glamour/v2" "charm.land/glamour/v2/ansi" "charm.land/glamour/v2/styles" @@ -25,7 +27,7 @@ func HighlightLines(lines []string, lexer chroma.Lexer, cache *highlightCache) [ if lexer == nil || len(lines) == 0 { return lines } - style := codeStyle(transcriptInk) + style := codeStyle(chrome.CurrentInk) key := func(line string) highlightKey { return highlightKey{lexer.Config().Name, style.Name, line} } @@ -76,9 +78,9 @@ type highlightKey struct{ lexer, theme, line string } // starts over: toggling diffs re-renders every diff in the transcript, and // lexing is most of that work. It goes with the chat that owns it. type highlightCache struct { - mu sync.Mutex lines map[highlightKey]string bytes int + mu sync.Mutex } const highlightBudget = 4 << 20 @@ -119,8 +121,8 @@ const ( // codeFence is a code block's frame row in Decor, and quoteBar leads each // quoted row. Both are decoration, which a copy does not carry. -func codeFence(mark string) string { return decorInk() + mark + ansiReset } -func quoteBar() string { return decorInk() + "│ " + ansiReset } +func codeFence(mark string) string { return chrome.DecorInk() + mark + chrome.AnsiReset } +func quoteBar() string { return chrome.DecorInk() + "│ " + chrome.AnsiReset } // codeStyles builds each palette's theme once: parsing style entries into a // chroma theme is most of a highlighting pass. @@ -130,21 +132,21 @@ var codeStyles sync.Map // bundled themes come from a stylesheet, and a terminal's palette, made legible // against its own background, is what this one follows. Each palette gets its // own name, so a theme change cannot reuse the previous palette's colors. -func codeStyle(colors ink) *chroma.Style { +func codeStyle(colors chrome.Ink) *chroma.Style { if cached, ok := codeStyles.Load(colors); ok { return cached.(*chroma.Style) } style := chromastyles.Get("monokai") - if colors.code != "" { - palette := colors.code + colors.secondary + colors.brandFrom + colors.brandTo + if colors.Code != "" { + palette := colors.Code + colors.Secondary + colors.BrandFrom + colors.BrandTo hash := sha256.Sum256([]byte(palette)) style = chroma.MustNewStyle(fmt.Sprintf("albedo-%x", hash[:6]), chroma.StyleEntries{ - chroma.Text: colors.code, - chroma.Comment: colors.secondary + " italic", - chroma.Keyword: colors.brandFrom, - chroma.NameFunction: colors.brandTo, - chroma.LiteralString: colors.brandTo, - chroma.LiteralNumber: colors.brandFrom, + chroma.Text: colors.Code, + chroma.Comment: colors.Secondary + " italic", + chroma.Keyword: colors.BrandFrom, + chroma.NameFunction: colors.BrandTo, + chroma.LiteralString: colors.BrandTo, + chroma.LiteralNumber: colors.BrandFrom, }) } codeStyles.Store(colors, style) @@ -153,7 +155,7 @@ func codeStyle(colors ink) *chroma.Style { // codeTheme names the palette's theme in chroma's registry: glamour looks a // code block's theme up by name, not by value. -func codeTheme(colors ink) string { +func codeTheme(colors chrome.Ink) string { style := codeStyle(colors) markdownThemes.Lock() defer markdownThemes.Unlock() @@ -176,12 +178,12 @@ func markdownStyle() ansi.StyleConfig { for _, heading := range []*ansi.StyleBlock{&style.H1, &style.H2, &style.H3, &style.H4, &style.H5, &style.H6} { heading.Prefix = "" heading.Bold = &bold - heading.Color = accent(transcriptInk.heading, "5") + heading.Color = accent(chrome.CurrentInk.Heading, "5") } - style.Strong = ansi.StylePrimitive{Bold: &bold, Color: accent(transcriptInk.strong, "3")} + style.Strong = ansi.StylePrimitive{Bold: &bold, Color: accent(chrome.CurrentInk.Strong, "3")} style.Emph = ansi.StylePrimitive{Italic: &bold} - style.Code = ansi.StyleBlock{StylePrimitive: ansi.StylePrimitive{Color: accent(transcriptInk.inlineCode, "2")}} - style.LinkText = ansi.StylePrimitive{Color: accent(transcriptInk.link, "4")} + style.Code = ansi.StyleBlock{Color: accent(chrome.CurrentInk.InlineCode, "2")} + style.LinkText = ansi.StylePrimitive{Color: accent(chrome.CurrentInk.Link, "4")} style.List.LevelIndent = 0 style.Table.Margin = &zero style.BlockQuote.IndentToken = new(quoteBar()) @@ -189,10 +191,10 @@ func markdownStyle() ansi.StyleConfig { style.CodeBlock.BlockPrefix = codeFence(fenceOpen) + "\n" style.CodeBlock.BlockSuffix = codeFence(fenceClose) style.HorizontalRule.Format = "\n────────────\n" - if transcriptInk.decor != "" { - style.HorizontalRule.Color = &transcriptInk.decor + if chrome.CurrentInk.Decor != "" { + style.HorizontalRule.Color = &chrome.CurrentInk.Decor } - style.CodeBlock.Theme = codeTheme(transcriptInk) + style.CodeBlock.Theme = codeTheme(chrome.CurrentInk) return style } @@ -236,17 +238,17 @@ func renderBlocks(text string, width int, whole bool) string { // reply. A whole rendering stays equal to a stepwise one: both are the same // pieces in the same order. type growingMarkdown struct { - // width is what the pieces were rendered at: text rendered at another one - // cannot extend them. - width int // text is the text scanned so far and scanned is how far into it the scan // went, with fence and blank the state there; blockStart is where the // block still growing begins, and prev the finished block it follows. - text string + text string + fence string + prev string + // width is what the pieces were rendered at: text rendered at another one + // cannot extend them. + width int scanned, blockStart int - fence string blank bool - prev string // started is whether a block has finished: the piece that finishes first // carries the rendering's start, which a whole rendering trims. started bool @@ -279,8 +281,8 @@ func (g *growingMarkdown) grow(text string, width int, cacheTail bool) (finished } for _, start := range starts { block := text[g.blockStart:start] - piece, ok := markdownPiece(g.prev, block, width, true) - if !ok { + piece, fits := markdownPiece(g.prev, block, width, true) + if !fits { g.unsplit = true return nil, "", false } @@ -370,7 +372,7 @@ func markdownPiece(prev, block string, width int, finished bool) (string, bool) // rendererKey is what a glamour renderer is built for. type rendererKey struct { - ink ink + ink chrome.Ink width int } @@ -378,18 +380,18 @@ type rendererKey struct { // costs more than most renders it does. A resize adds a width, so the map is // emptied once it holds a handful. var renderers = struct { - sync.Mutex byKey map[rendererKey]*glamour.TermRenderer + sync.Mutex }{byKey: map[rendererKey]*glamour.TermRenderer{}} func markdownRenderer(width int) (*glamour.TermRenderer, error) { - key := rendererKey{ink: transcriptInk, width: width} + key := rendererKey{ink: chrome.CurrentInk, width: width} if renderer, ok := renderers.byKey[key]; ok { return renderer, nil } renderer, err := glamour.NewTermRenderer( glamour.WithStyles(markdownStyle()), glamour.WithWordWrap(width), glamour.WithPreservedNewLines(), - mathOptions(accent(transcriptInk.math, "6")), + mathOptions(accent(chrome.CurrentInk.Math, "6")), ) if err != nil { return nil, err @@ -449,23 +451,6 @@ var ( spansBlocks = regexp.MustCompile(`(?i)^ {0,3}(\[[^\]]+\]:|<(pre|script|style|textarea)\b|