From 6d54740133e2a8577b7dffec401df2897667e0bd Mon Sep 17 00:00:00 2001 From: dawn <90008@klbr.net> Date: Wed, 23 Sep 2026 17:58:43 +0300 Subject: [PATCH] add go tui port with charm --- .gitignore | 1 + README.md | 82 +- cli/UPSTREAM.md | 12 +- cli/bin/albedo.mjs | 16 +- cli/cmd/albedo/main.go | 408 +++++ cli/cmd/albedo/main_test.go | 169 ++ cli/go.mod | 28 + cli/go.sum | 41 + cli/internal/config/codex.go | 583 +++++++ cli/internal/config/codex_test.go | 179 +++ cli/internal/config/config.go | 304 ++++ cli/internal/config/config_test.go | 122 ++ cli/internal/daemon/client.go | 843 ++++++++++ cli/internal/daemon/client_test.go | 773 ++++++++++ cli/internal/daemon/commands.go | 122 ++ cli/internal/daemon/commands_test.go | 40 + cli/internal/daemon/events.go | 164 ++ cli/internal/daemon/image.go | 91 ++ cli/internal/daemon/image_test.go | 71 + cli/internal/daemon/lifecycle.go | 365 +++++ cli/internal/daemon/lifecycle_test.go | 147 ++ cli/internal/daemon/progress.go | 319 ++++ cli/internal/daemon/progress_test.go | 64 + cli/internal/daemon/sessions_test.go | 78 + cli/internal/tui/app.go | 1036 +++++++++++++ cli/internal/tui/bounded_history.go | 166 ++ cli/internal/tui/bounded_history_test.go | 85 + cli/internal/tui/chat.go | 1792 ++++++++++++++++++++++ cli/internal/tui/clipboard.go | 244 +++ cli/internal/tui/commands.go | 156 ++ cli/internal/tui/context_inspector.go | 460 ++++++ cli/internal/tui/extension_picker.go | 330 ++++ cli/internal/tui/login.go | 822 ++++++++++ cli/internal/tui/markdown.go | 287 ++++ cli/internal/tui/memory_profile_test.go | 299 ++++ cli/internal/tui/model_picker.go | 397 +++++ cli/internal/tui/page_view.go | 641 ++++++++ cli/internal/tui/picker.go | 220 +++ cli/internal/tui/scroll_perf_test.go | 930 +++++++++++ cli/internal/tui/selection.go | 91 ++ cli/internal/tui/styles.go | 63 + cli/internal/tui/transcript.go | 365 +++++ cli/internal/tui/tree_picker.go | 308 ++++ cli/package-lock.json | 2 - cli/test/manual/VISUAL_PARITY.md | 25 + cli/test/manual/chat-clipboard.tsx | 23 + cli/test/manual/codex-driver/main.go | 53 + cli/test/manual/visual_codex_preload.mjs | 11 + cli/test/manual/visual_contact.py | 41 + cli/test/manual/visual_image_driver.go | 46 + cli/test/manual/visual_index.py | 96 ++ cli/test/manual/visual_parity.py | 258 ++++ cli/test/manual/visual_terminal.mjs | 18 + default.nix | 71 + flake.lock | 27 + flake.nix | 24 + result | 1 + test.sh | 6 + test/daemon/integration.py | 4 +- test/manual/go_memory_profile.py | 339 ++++ test/manual/go_port_smoke.py | 770 ++++++++++ test/manual/go_scroll_perf.py | 453 ++++++ test/manual/nix_package_smoke.py | 29 + 63 files changed, 15999 insertions(+), 12 deletions(-) create mode 100644 cli/cmd/albedo/main.go create mode 100644 cli/cmd/albedo/main_test.go create mode 100644 cli/go.mod create mode 100644 cli/go.sum create mode 100644 cli/internal/config/codex.go create mode 100644 cli/internal/config/codex_test.go create mode 100644 cli/internal/config/config.go create mode 100644 cli/internal/config/config_test.go create mode 100644 cli/internal/daemon/client.go create mode 100644 cli/internal/daemon/client_test.go create mode 100644 cli/internal/daemon/commands.go create mode 100644 cli/internal/daemon/commands_test.go create mode 100644 cli/internal/daemon/events.go create mode 100644 cli/internal/daemon/image.go create mode 100644 cli/internal/daemon/image_test.go create mode 100644 cli/internal/daemon/lifecycle.go create mode 100644 cli/internal/daemon/lifecycle_test.go create mode 100644 cli/internal/daemon/progress.go create mode 100644 cli/internal/daemon/progress_test.go create mode 100644 cli/internal/daemon/sessions_test.go create mode 100644 cli/internal/tui/app.go create mode 100644 cli/internal/tui/bounded_history.go create mode 100644 cli/internal/tui/bounded_history_test.go create mode 100644 cli/internal/tui/chat.go create mode 100644 cli/internal/tui/clipboard.go create mode 100644 cli/internal/tui/commands.go create mode 100644 cli/internal/tui/context_inspector.go create mode 100644 cli/internal/tui/extension_picker.go create mode 100644 cli/internal/tui/login.go create mode 100644 cli/internal/tui/markdown.go create mode 100644 cli/internal/tui/memory_profile_test.go create mode 100644 cli/internal/tui/model_picker.go create mode 100644 cli/internal/tui/page_view.go create mode 100644 cli/internal/tui/picker.go create mode 100644 cli/internal/tui/scroll_perf_test.go create mode 100644 cli/internal/tui/selection.go create mode 100644 cli/internal/tui/styles.go create mode 100644 cli/internal/tui/transcript.go create mode 100644 cli/internal/tui/tree_picker.go create mode 100644 cli/test/manual/VISUAL_PARITY.md create mode 100644 cli/test/manual/chat-clipboard.tsx create mode 100644 cli/test/manual/codex-driver/main.go create mode 100644 cli/test/manual/visual_codex_preload.mjs create mode 100644 cli/test/manual/visual_contact.py create mode 100644 cli/test/manual/visual_image_driver.go create mode 100644 cli/test/manual/visual_index.py create mode 100644 cli/test/manual/visual_parity.py create mode 100644 cli/test/manual/visual_terminal.mjs create mode 100644 default.nix create mode 100644 flake.lock create mode 100644 flake.nix create mode 120000 result create mode 100755 test/manual/go_memory_profile.py create mode 100755 test/manual/go_port_smoke.py create mode 100755 test/manual/go_scroll_perf.py create mode 100644 test/manual/nix_package_smoke.py diff --git a/.gitignore b/.gitignore index db3238853..f1ef04d1e 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ __pycache__/ /native/render/target/ /priv/bin/ +/cli/bin/albedo diff --git a/README.md b/README.md index 64b5efe26..2524a5353 100644 --- a/README.md +++ b/README.md @@ -3,16 +3,54 @@ small gleam coding and (not yet) persistent agent daemon with a detachable cli - python repl and bash. -- cli for now is ink based +- native go cli using charm (bubbletea, lipgloss, bubbles) ```sh -npm --prefix cli install -node cli/bin/albedo.mjs +# build native go cli +go -C cli build -o bin/albedo ./cmd/albedo +./cli/bin/albedo # or to install it globally +go -C cli install ./cmd/albedo +albedo +``` + +when installed globally outside the checkout, set `ALBEDO_ROOT` to the absolute repo path if the daemon needs to be started: +```sh +ALBEDO_ROOT=/path/to/albedo albedo +``` +`ALBEDO_ROOT` is only needed when the installed binary needs to launch the daemon from outside the repo tree; the local binary (`./cli/bin/albedo`) discovers the repo root automatically from its file path. you can also embed the root at build/install time if preferred: +```sh +go -C cli install -ldflags "-X main.buildRoot=$(pwd)" ./cmd/albedo +``` + +nix package (includes the compiled daemon and python runtime): + +```sh +nix build .#albedo +nix run . -- --help +# package checks, with a local mock provider (no model credentials): +python3 test/manual/nix_package_smoke.py "$PWD/result/bin/albedo" +ALBEDO_NO_BROWSER=1 ALBEDO_TEST_BINARY="$PWD/result/bin/albedo" python3 test/daemon/integration.py +``` + +while the nix files are untracked, use `nix build path:.#albedo` and +`nix run path:. -- --help` so nix includes them. + +`default.nix` is also available through `pkgs.callPackage ./default.nix { }`. +no checkout or gleam compiler is needed at runtime. `ALBEDO_DAEMON` can override +the packaged daemon with an absolute executable path. + +legacy typescript reference (kept for parity testing): +```sh +npm --prefix cli install +# ALBEDO_USE_TS=1 forces the launcher to use the TypeScript reference instead of native binary +ALBEDO_USE_TS=1 node cli/bin/albedo.mjs + +# or to install it globally via npm npm install -g ./cli -albedo +ALBEDO_USE_TS=1 albedo ``` optional: `view`, which lets the model see its changes and code as highlighted @@ -25,13 +63,45 @@ native/render/install.sh # then enable `view` in /extensions tests ```sh -./test.sh # gleam, cli, and daemon suites -gleam test # gleam suite plus the python harnesses that hold no build lock +./test.sh # gleam, native go cli, and daemon suites +go -C cli test ./... # native go cli tests +go -C cli vet ./... # native go cli vet +gleam test # gleam suite plus the python harnesses that hold no build lock ``` +manual comparisons and performance tools: + `test/manual` is opt-in: those benchmarks need a provider, a PTY, or artifacts from an earlier run. +ui checks are manual: real terminal screenshots and interaction walkthroughs, +not ui unit or golden tests. the capture tool uses isolated fake providers and +writes PNGs, terminal recordings, and capture metadata under +`/tmp/albedo-visual-parity/atlas`. + +```sh +# paired TS/Go screenshots (Pillow via uv; npm dependencies from cli) +uv run --no-project --script cli/test/manual/visual_parity.py --help + +# standalone PTY smoke and parity verification +ALBEDO_NO_BROWSER=1 python3 test/manual/go_port_smoke.py + +# 120Hz scrollback performance and timing evaluation +ALBEDO_NO_BROWSER=1 python3 test/manual/go_scroll_perf.py + +# native heap and runtime memory attribution profile +ALBEDO_NO_BROWSER=1 python3 test/manual/go_memory_profile.py +``` + +### memory policy & bounds + +the native go cli bounds transcript and scrollback memory (process RSS and go runtime allocations are not hard-capped; history accounting measures payload bytes and excludes runtime/object overhead): +- **raw history retention**: capped at 500 entries or 2 MiB payload bytes. +- **rendered scrollback**: capped at 1,000 lines or 256 KiB in terminal memory. +- **scrollback trimming**: older visible lines are trimmed with a notice banner (`[X scrollback lines truncated]`); daemon durable history remains completely intact in SQLite. +- **live streaming segmentation**: active text chunks segment at 64 KiB (`MaxLiveStreamBytes`) before settling into history blocks to avoid unbounded live chunk buffers. +- **renderer scheduling**: Bubble Tea runs with `tea.WithFPS(120)` render scheduling budget; this represents the engine frame budget and is distinct from physical display refresh rate. + todo - [] flesh out plugin system more - [] sdk and -p, command to print out most recent assistant message from session diff --git a/cli/UPSTREAM.md b/cli/UPSTREAM.md index acc17799e..2338d9c22 100644 --- a/cli/UPSTREAM.md +++ b/cli/UPSTREAM.md @@ -1,7 +1,15 @@ # upstream ui terminal rendering, transcript layout, input, markdown, live python-code views, -and the ink patch are copied from niri. they are adapted here at -the client boundary, not replaced with a new visual design. +and the original ink patch were adapted from niri at the client boundary, +not replaced with a new visual design. source: https://tangled.org/okami.mom/niri + +## go port + +the cli was ported from the typescript/ink reference to native go using the +charm stack (`bubbletea`, `lipgloss`, `bubbles`). the port preserves the +transcript layout, interactive keybindings, slash-command popovers, diff rendering, +and virtual scrolling while providing a standalone executable with bounded +memory and streaming event processing. diff --git a/cli/bin/albedo.mjs b/cli/bin/albedo.mjs index 56094c5d3..cd03ba56e 100755 --- a/cli/bin/albedo.mjs +++ b/cli/bin/albedo.mjs @@ -1,6 +1,20 @@ #!/usr/bin/env node -import { register } from "tsx/esm/api" +import { existsSync } from "node:fs" import { fileURLToPath } from "node:url" +import { dirname, join } from "node:path" +import { spawnSync } from "node:child_process" + +const dir = dirname(fileURLToPath(import.meta.url)) +const goBinary = join(dir, "albedo") + +const isTsTest = process.env.ALBEDO_USE_TS === "1" || process.execArgv.some(arg => arg.includes("terminal.mjs")) + +if (existsSync(goBinary) && !isTsTest) { + const result = spawnSync(goBinary, process.argv.slice(2), { stdio: "inherit" }) + process.exit(result.status ?? 0) +} + +import { register } from "tsx/esm/api" register({ tsconfig: fileURLToPath(new URL("../tsconfig.json", import.meta.url)) }) // Load React's production renderer without changing the environment inherited by // the daemon or tools. NODE_ENV=development remains an explicit debugging option. diff --git a/cli/cmd/albedo/main.go b/cli/cmd/albedo/main.go new file mode 100644 index 000000000..b03ce6fc1 --- /dev/null +++ b/cli/cmd/albedo/main.go @@ -0,0 +1,408 @@ +package main + +import ( + "albedo/cli/internal/config" + "albedo/cli/internal/daemon" + "albedo/cli/internal/tui" + "context" + "encoding/json" + "errors" + "fmt" + "net/url" + "os" + "path/filepath" + "strings" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/mattn/go-isatty" +) + +var buildRoot string // Embedded at build time via -ldflags "-X main.buildRoot=..." + +func isAlbedoRoot(dir string) bool { + if dir == "" { + return false + } + if _, err := os.Stat(filepath.Join(dir, "gleam.toml")); err == nil { + if _, err := os.Stat(filepath.Join(dir, "src", "albedo.gleam")); err == nil { + return true + } + } + return false +} + +func findProjectRoot() string { + if env := os.Getenv("ALBEDO_ROOT"); env != "" && isAlbedoRoot(env) { + return env + } + if exe, err := os.Executable(); err == nil { + if resolved, err := filepath.EvalSymlinks(exe); err == nil { + exe = resolved + } + // Check exe/../.. (e.g. repo/cli/bin/albedo -> repo) + parent2 := filepath.Dir(filepath.Dir(exe)) + if isAlbedoRoot(parent2) { + return parent2 + } + parent3 := filepath.Dir(parent2) + if isAlbedoRoot(parent3) { + return parent3 + } + } + if buildRoot != "" && isAlbedoRoot(buildRoot) { + return buildRoot + } + if cwd, err := os.Getwd(); err == nil { + cur := cwd + for { + if isAlbedoRoot(cur) { + return cur + } + parent := filepath.Dir(cur) + if parent == cur { + break + } + cur = parent + } + } + if buildRoot != "" { + return buildRoot + } + cwd, _ := os.Getwd() + return cwd +} + +func isTTY() bool { + return isatty.IsTerminal(os.Stdin.Fd()) && isatty.IsTerminal(os.Stdout.Fd()) +} + +const helpText = `Usage: albedo [options] [command] + +persistent coding sessions + +Options: + -h, --help display help for command + +Commands: + new [workspace] start a fresh session in the given workspace (defaults to current directory) + resume resume a session by id or prefix + sessions [options] list active sessions + send send a prompt turn to a session + stop interrupt an active session + daemon [options] inspect or manage daemon lifecycle + login [name] configure an API provider in terminal +` + +func open(id, workspace string, fresh bool) error { + ctx := context.Background() + homeDir := config.HomeDir() + projectRoot := findProjectRoot() + + absWorkspace, err := filepath.Abs(workspace) + if err != nil { + absWorkspace = workspace + } + + conn, err := daemon.Ensure(homeDir, projectRoot) + if err != nil { + return err + } + + sessions, err := daemon.Request[[]daemon.Session](ctx, conn, "/sessions", nil) + if err != nil { + return err + } + + var selected *daemon.Session + if id != "" { + var matches []daemon.Session + for _, s := range sessions { + if s.ID == id || strings.HasPrefix(s.ID, id) { + matches = append(matches, s) + } + } + hasExact := false + for _, s := range matches { + if s.ID == id { + hasExact = true + break + } + } + if len(matches) > 1 && !hasExact { + return errors.New("session prefix is ambiguous") + } + if len(matches) == 0 { + return errors.New("session not found") + } + for _, s := range matches { + if s.ID == id { + session := s + selected = &session + break + } + } + if selected == nil && len(matches) > 0 { + session := matches[0] + selected = &session + } + } + + profs, err := config.LoadProfiles(homeDir) + if err != nil { + return err + } + configured := profs.Active != "" + + if !configured && !isTTY() { + return errors.New("run albedo login in a terminal to save a provider") + } + + var initial *daemon.Session + if selected != nil { + initial = selected + } else if configured && (fresh || len(sessions) == 0) { + created, err := daemon.Request[daemon.Session](ctx, conn, "/sessions", map[string]string{"workspace": absWorkspace}) + if err != nil { + return err + } + initial = &created + } + + if !isTTY() { + type NonTTYOutput struct { + Session *string `json:"session,omitempty"` + Sessions []daemon.Session `json:"sessions"` + } + var sessID *string + if initial != nil { + sessID = &initial.ID + } + if sessions == nil { + sessions = []daemon.Session{} + } + out := NonTTYOutput{ + Session: sessID, + Sessions: sessions, + } + data, err := json.Marshal(out) + if err != nil { + return err + } + fmt.Println(string(data)) + return nil + } + + appModel := tui.NewAppModel(conn, profs, initial, absWorkspace, !configured) + if os.Getenv("ALBEDO_NO_BROWSER") == "" { + appModel.BrowserOpener = config.OpenBrowser + appModel.Login.BrowserOpener = config.OpenBrowser + } + p := tea.NewProgram(appModel, tea.WithFPS(120)) + _, err = p.Run() + return err +} + +func main() { + if err := run(os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run(args []string) error { + cwd, err := os.Getwd() + if err != nil { + cwd = "." + } + + if len(args) == 0 { + return open("", cwd, false) + } + + cmd := args[0] + subArgs := args[1:] + + switch cmd { + case "-h", "--help", "help": + fmt.Print(helpText) + return nil + + case "new": + workspace := cwd + for i := 0; i < len(subArgs); i++ { + if subArgs[i] == "-h" || subArgs[i] == "--help" { + fmt.Println("Usage: albedo new [workspace]") + return nil + } + if !strings.HasPrefix(subArgs[i], "-") { + workspace = subArgs[i] + break + } + } + return open("", workspace, true) + + case "resume": + if len(subArgs) == 0 || subArgs[0] == "-h" || subArgs[0] == "--help" { + if len(subArgs) > 0 && (subArgs[0] == "-h" || subArgs[0] == "--help") { + fmt.Println("Usage: albedo resume ") + return nil + } + return errors.New("resume requires argument") + } + return open(subArgs[0], cwd, false) + + case "sessions": + asJSON := false + for _, a := range subArgs { + if a == "-h" || a == "--help" { + fmt.Println("Usage: albedo sessions [--json]") + return nil + } + if a == "--json" { + asJSON = true + } + } + homeDir := config.HomeDir() + projectRoot := findProjectRoot() + conn, err := daemon.Ensure(homeDir, projectRoot) + if err != nil { + return err + } + sessions, err := daemon.Request[[]daemon.Session](context.Background(), conn, "/sessions", nil) + if err != nil { + return err + } + if asJSON { + data, err := json.MarshalIndent(sessions, "", " ") + if err != nil { + return err + } + fmt.Println(string(data)) + } else { + fmt.Println(daemon.SessionListing(sessions, time.Now())) + } + return nil + + case "send": + if len(subArgs) > 0 && (subArgs[0] == "-h" || subArgs[0] == "--help") { + fmt.Println("Usage: albedo send ") + return nil + } + if len(subArgs) < 2 { + return errors.New("send requires and arguments") + } + sessID := subArgs[0] + prompt := subArgs[1] + homeDir := config.HomeDir() + projectRoot := findProjectRoot() + conn, err := daemon.Ensure(homeDir, projectRoot) + if err != nil { + return err + } + path := fmt.Sprintf("/sessions/%s/events", url.PathEscape(sessID)) + res, err := daemon.Request[any](context.Background(), conn, path, map[string]string{"content": prompt}) + if err != nil { + return err + } + data, _ := json.Marshal(res) + fmt.Println(string(data)) + return nil + + case "stop": + if len(subArgs) > 0 && (subArgs[0] == "-h" || subArgs[0] == "--help") { + fmt.Println("Usage: albedo stop ") + return nil + } + if len(subArgs) < 1 { + return errors.New("stop requires argument") + } + sessID := subArgs[0] + homeDir := config.HomeDir() + projectRoot := findProjectRoot() + conn, err := daemon.Ensure(homeDir, projectRoot) + if err != nil { + return err + } + path := fmt.Sprintf("/sessions/%s/interrupt", url.PathEscape(sessID)) + res, err := daemon.Request[any](context.Background(), conn, path, map[string]any{}) + if err != nil { + return err + } + data, _ := json.Marshal(res) + fmt.Println(string(data)) + return nil + + case "daemon": + stop := false + for _, a := range subArgs { + if a == "-h" || a == "--help" { + fmt.Println("Usage: albedo daemon [--stop]") + return nil + } + if a == "--stop" { + stop = true + } + } + homeDir := config.HomeDir() + if stop { + current, err := daemon.Existing(homeDir) + if err != nil { + return err + } + if current != nil { + _, err = daemon.Request[any](context.Background(), current, "/shutdown", map[string]any{}) + return err + } + return nil + } + projectRoot := findProjectRoot() + current, err := daemon.Ensure(homeDir, projectRoot) + if err != nil { + return err + } + fmt.Printf("albedo daemon running on 127.0.0.1:%d\n", current.Port) + return nil + + case "login": + if len(subArgs) > 0 && (subArgs[0] == "-h" || subArgs[0] == "--help") { + fmt.Println("Usage: albedo login [name]") + return nil + } + if !isTTY() { + return errors.New("login requires a terminal; keys are entered with hidden input") + } + providerName := "" + if len(subArgs) > 0 { + providerName = subArgs[0] + } + homeDir := config.HomeDir() + projectRoot := findProjectRoot() + conn, err := daemon.Ensure(homeDir, projectRoot) + if err != nil { + return err + } + profs, err := config.LoadProfiles(homeDir) + if err != nil { + return err + } + appModel := tui.NewAppModel(conn, profs, nil, cwd, true) + appModel.StandaloneLogin = true + if os.Getenv("ALBEDO_NO_BROWSER") == "" { + appModel.BrowserOpener = config.OpenBrowser + appModel.Login.BrowserOpener = config.OpenBrowser + } + if providerName != "" { + appModel.Login = tui.NewLoginModel(conn, providerName) + if os.Getenv("ALBEDO_NO_BROWSER") == "" { + appModel.Login.BrowserOpener = config.OpenBrowser + } + } + p := tea.NewProgram(appModel, tea.WithFPS(120)) + _, err = p.Run() + return err + + default: + return fmt.Errorf("unknown command %q", cmd) + } +} diff --git a/cli/cmd/albedo/main_test.go b/cli/cmd/albedo/main_test.go new file mode 100644 index 000000000..8b1325111 --- /dev/null +++ b/cli/cmd/albedo/main_test.go @@ -0,0 +1,169 @@ +package main + +import ( + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestIsAlbedoRoot(t *testing.T) { + tempDir := t.TempDir() + if isAlbedoRoot(tempDir) { + t.Errorf("empty dir should not be albedo root") + } + + // Add gleam.toml only + _ = os.WriteFile(filepath.Join(tempDir, "gleam.toml"), []byte(`name = "test"`), 0644) + if isAlbedoRoot(tempDir) { + t.Errorf("dir with only gleam.toml should not be albedo root") + } + + // Add src/albedo.gleam + _ = os.MkdirAll(filepath.Join(tempDir, "src"), 0755) + _ = os.WriteFile(filepath.Join(tempDir, "src", "albedo.gleam"), []byte("// test"), 0644) + if !isAlbedoRoot(tempDir) { + t.Errorf("dir with gleam.toml and src/albedo.gleam must be recognized as albedo root") + } +} + +func TestFindProjectRoot_EnvOverride(t *testing.T) { + tempDir := t.TempDir() + _ = os.WriteFile(filepath.Join(tempDir, "gleam.toml"), []byte(`name = "test"`), 0644) + _ = os.MkdirAll(filepath.Join(tempDir, "src"), 0755) + _ = os.WriteFile(filepath.Join(tempDir, "src", "albedo.gleam"), []byte("// test"), 0644) + + t.Setenv("ALBEDO_ROOT", tempDir) + root := findProjectRoot() + if root != tempDir { + t.Errorf("expected ALBEDO_ROOT=%s, got %s", tempDir, root) + } +} + +func TestRun_HelpCommands(t *testing.T) { + for _, cmd := range [][]string{{"-h"}, {"--help"}, {"help"}} { + err := run(cmd) + if err != nil { + t.Errorf("run(%v) failed: %v", cmd, err) + } + } + + for _, sub := range []string{"new", "resume", "sessions", "send", "stop", "daemon", "login"} { + err := run([]string{sub, "--help"}) + if err != nil { + t.Errorf("run([%s, --help]) failed: %v", sub, err) + } + } +} + +func TestRun_UnknownCommand(t *testing.T) { + err := run([]string{"nonexistent-subcommand"}) + if err == nil || !strings.Contains(err.Error(), "unknown command") { + t.Errorf("expected unknown command error, got: %v", err) + } +} + +func TestRun_MissingArguments(t *testing.T) { + if err := run([]string{"resume"}); err == nil || !strings.Contains(err.Error(), "resume requires") { + t.Errorf("expected resume requires argument error, got: %v", err) + } + if err := run([]string{"send"}); err == nil || !strings.Contains(err.Error(), "send requires") { + t.Errorf("expected send requires argument error, got: %v", err) + } + if err := run([]string{"send", "session1"}); err == nil || !strings.Contains(err.Error(), "send requires") { + t.Errorf("expected send requires 2 args error, got: %v", err) + } + if err := run([]string{"stop"}); err == nil || !strings.Contains(err.Error(), "stop requires") { + t.Errorf("expected stop requires argument error, got: %v", err) + } +} + +func TestRun_LoginNonTTYRejection(t *testing.T) { + err := run([]string{"login"}) + if err == nil || !strings.Contains(err.Error(), "login requires a terminal") { + t.Errorf("expected login non-TTY error, got: %v", err) + } +} + +func TestNonTTYSessionJSONOmitempty(t *testing.T) { + type NonTTYOutput struct { + Session *string `json:"session,omitempty"` + Sessions []string `json:"sessions"` + } + + // Without initial session: session key must be omitted + out1 := NonTTYOutput{Session: nil, Sessions: []string{"s1"}} + data1, _ := json.Marshal(out1) + if strings.Contains(string(data1), `"session":`) { + t.Errorf("expected session key omitted when nil, got: %s", string(data1)) + } + + // With initial session: session key must be present + id := "abc12345" + out2 := NonTTYOutput{Session: &id, Sessions: []string{"s1"}} + data2, _ := json.Marshal(out2) + if !strings.Contains(string(data2), `"session":"abc12345"`) { + t.Errorf("expected session key present, got: %s", string(data2)) + } +} + +func TestRun_SessionsWithMockDaemon(t *testing.T) { + homeDir := t.TempDir() + t.Setenv("ALBEDO_HOME", homeDir) + + sessions := []map[string]any{ + { + "id": "deadbeef12345678", + "title": "Test Session", + "workspace": "/tmp", + "model": "fixture", + "protocol": "responses", + "provider": "openai", + }, + } + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer test-token" { + w.WriteHeader(http.StatusUnauthorized) + return + } + if r.URL.Path == "/health" { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "version": 2}) + return + } + if r.URL.Path == "/sessions" { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(sessions) + return + } + w.WriteHeader(http.StatusNotFound) + })) + defer server.Close() + + port := server.Listener.Addr().(*net.TCPAddr).Port + daemonJSON := map[string]any{ + "port": port, + "token": "test-token", + "pid": os.Getpid(), + "version": 2, + } + data, _ := json.Marshal(daemonJSON) + _ = os.WriteFile(filepath.Join(homeDir, "daemon.json"), data, 0600) + + // Test sessions --json + err := run([]string{"sessions", "--json"}) + if err != nil { + t.Fatalf("sessions --json failed: %v", err) + } + + // Test sessions (plain text) + err = run([]string{"sessions"}) + if err != nil { + t.Fatalf("sessions plain failed: %v", err) + } +} diff --git a/cli/go.mod b/cli/go.mod new file mode 100644 index 000000000..2658e55fe --- /dev/null +++ b/cli/go.mod @@ -0,0 +1,28 @@ +module albedo/cli + +go 1.26.7 + +require ( + github.com/atotto/clipboard v0.1.4 + github.com/charmbracelet/bubbles v0.20.0 + github.com/charmbracelet/bubbletea v1.3.4 + github.com/charmbracelet/lipgloss v1.0.0 + github.com/charmbracelet/x/ansi v0.8.0 + github.com/mattn/go-isatty v0.0.20 + github.com/rivo/uniseg v0.4.7 + golang.org/x/text v0.3.8 +) + +require ( + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/charmbracelet/x/term v0.2.1 // indirect + github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-localereader v0.0.1 // indirect + github.com/mattn/go-runewidth v0.0.16 // indirect + github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/muesli/termenv v0.15.2 // indirect + golang.org/x/sync v0.11.0 // indirect + golang.org/x/sys v0.30.0 // indirect +) diff --git a/cli/go.sum b/cli/go.sum new file mode 100644 index 000000000..386e628c7 --- /dev/null +++ b/cli/go.sum @@ -0,0 +1,41 @@ +github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= +github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/charmbracelet/bubbles v0.20.0 h1:jSZu6qD8cRQ6k9OMfR1WlM+ruM8fkPWkHvQWD9LIutE= +github.com/charmbracelet/bubbles v0.20.0/go.mod h1:39slydyswPy+uVOHZ5x/GjwVAFkCsV8IIVy+4MhzwwU= +github.com/charmbracelet/bubbletea v1.3.4 h1:kCg7B+jSCFPLYRA52SDZjr51kG/fMUEoPoZrkaDHyoI= +github.com/charmbracelet/bubbletea v1.3.4/go.mod h1:dtcUCyCGEX3g9tosuYiut3MXgY/Jsv9nKVdibKKRRXo= +github.com/charmbracelet/lipgloss v1.0.0 h1:O7VkGDvqEdGi93X+DeqsQ7PKHDgtQfF8j8/O2qFMQNg= +github.com/charmbracelet/lipgloss v1.0.0/go.mod h1:U5fy9Z+C38obMs+T+tJqst9VGzlOYGj4ri9reL3qUlo= +github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE= +github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q= +github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= +github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= +github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= +github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= +github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= +github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= +github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo= +github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= +golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= +golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= diff --git a/cli/internal/config/codex.go b/cli/internal/config/codex.go new file mode 100644 index 000000000..93d96f786 --- /dev/null +++ b/cli/internal/config/codex.go @@ -0,0 +1,583 @@ +package config + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "time" +) + +const ( + CodexClientID = "app_EMoamEEZ73f0CkXaXp7hrann" + CodexAuthorizeURL = "https://auth.openai.com/oauth/authorize" + CodexTokenURL = "https://auth.openai.com/oauth/token" + CodexRedirectURI = "http://localhost:1455/auth/callback" + CodexScope = "openid profile email offline_access api.connectors.read api.connectors.invoke" + CodexAuthClaim = "https://api.openai.com/auth" + CodexProfileClaim = "https://api.openai.com/profile" +) + +// CodexCredential holds OAuth credentials for OpenAI Codex. +type CodexCredential struct { + Type string `json:"type"` + Access string `json:"access"` + Refresh string `json:"refresh"` + Expires int64 `json:"expires"` + AccountID string `json:"accountId"` + AccountUserID *string `json:"accountUserId,omitempty"` + Email *string `json:"email,omitempty"` +} + +// CredentialIdentity returns the canonical identity string for a credential. +func CredentialIdentity(cred CodexCredential) string { + if cred.AccountUserID != nil && *cred.AccountUserID != "" { + return "account-user:" + *cred.AccountUserID + } + if cred.AccountID != "" { + return "account:" + cred.AccountID + } + if cred.Email != nil && *cred.Email != "" { + return "email:" + strings.ToLower(*cred.Email) + } + h := sha256.Sum256([]byte(cred.Refresh)) + return "refresh:" + hex.EncodeToString(h[:])[:16] +} + +func parseJWT(token string) (map[string]any, error) { + parts := strings.Split(token, ".") + if len(parts) != 3 { + return nil, errors.New("invalid jwt") + } + seg := parts[1] + if l := len(seg) % 4; l > 0 { + seg += strings.Repeat("=", 4-l) + } + data, err := base64.URLEncoding.DecodeString(seg) + if err != nil { + return nil, err + } + var claims map[string]any + if err := json.Unmarshal(data, &claims); err != nil { + return nil, err + } + return claims, nil +} + +func asMap(val any) map[string]any { + if m, ok := val.(map[string]any); ok { + return m + } + return nil +} + +func extractTokenIdentity(access string, idToken *string) (accountID string, accountUserID, email *string, err error) { + accessClaims, _ := parseJWT(access) + var idClaims map[string]any + if idToken != nil && *idToken != "" { + idClaims, _ = parseJWT(*idToken) + } + + auth := asMap(accessClaims[CodexAuthClaim]) + if auth == nil && idClaims != nil { + auth = asMap(idClaims[CodexAuthClaim]) + } + + profile := asMap(accessClaims[CodexProfileClaim]) + if profile == nil && idClaims != nil { + profile = asMap(idClaims[CodexProfileClaim]) + } + + if auth != nil { + if rawID, ok := auth["chatgpt_account_id"].(string); ok && rawID != "" { + accountID = rawID + } + if rawUID, ok := auth["chatgpt_account_user_id"].(string); ok && rawUID != "" { + accountUserID = &rawUID + } + } + if accountID == "" { + return "", nil, nil, errors.New("codex token has no ChatGPT account id") + } + + if profile != nil { + if rawEmail, ok := profile["email"].(string); ok { + trimmed := strings.ToLower(strings.TrimSpace(rawEmail)) + if trimmed != "" { + email = &trimmed + } + } + } + + return accountID, accountUserID, email, nil +} + +// ParseAuthorizationInput extracts code and state from user input (URL or raw code). +func ParseAuthorizationInput(input string) (code, state string) { + val := strings.TrimSpace(input) + if val == "" { + return "", "" + } + if u, err := url.Parse(val); err == nil && u.Scheme != "" && u.Host != "" { + return u.Query().Get("code"), u.Query().Get("state") + } + if strings.Contains(val, "#") { + parts := strings.SplitN(val, "#", 2) + return parts[0], parts[1] + } + if strings.Contains(val, "code=") { + values, err := url.ParseQuery(val) + if err == nil { + return values.Get("code"), values.Get("state") + } + } + return val, "" +} + +// CreateAuthorization generates PKCE parameters and authorization URL. +func CreateAuthorization() (verifier, state, urlStr string) { + rawVerifier := make([]byte, 96) + _, _ = rand.Read(rawVerifier) + verifier = base64.RawURLEncoding.EncodeToString(rawVerifier) + + hash := sha256.Sum256([]byte(verifier)) + challenge := base64.RawURLEncoding.EncodeToString(hash[:]) + + rawState := make([]byte, 16) + _, _ = rand.Read(rawState) + state = hex.EncodeToString(rawState) + + u, _ := url.Parse(CodexAuthorizeURL) + q := u.Query() + q.Set("response_type", "code") + q.Set("client_id", CodexClientID) + q.Set("redirect_uri", CodexRedirectURI) + q.Set("scope", CodexScope) + q.Set("code_challenge", challenge) + q.Set("code_challenge_method", "S256") + q.Set("state", state) + q.Set("id_token_add_organizations", "true") + q.Set("codex_cli_simplified_flow", "true") + q.Set("originator", "albedo") + u.RawQuery = q.Encode() + + return verifier, state, u.String() +} + +// ExchangeCodexCode performs OAuth token exchange. +func ExchangeCodexCode(ctx context.Context, client *http.Client, code, verifier string) (*CodexCredential, error) { + if client == nil { + client = http.DefaultClient + } + + form := url.Values{} + form.Set("grant_type", "authorization_code") + form.Set("client_id", CodexClientID) + form.Set("code", code) + form.Set("code_verifier", verifier) + form.Set("redirect_uri", CodexRedirectURI) + + reqCtx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + + req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, CodexTokenURL, strings.NewReader(form.Encode())) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + res, err := client.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + + body, err := io.ReadAll(io.LimitReader(res.Body, 64*1024+1)) + if err != nil { + return nil, err + } + if len(body) > 64*1024 { + return nil, errors.New("codex token exchange response exceeded 64KB") + } + + if res.StatusCode < 200 || res.StatusCode >= 300 { + bodyStr := strings.TrimSpace(string(body)) + if bodyStr != "" { + return nil, fmt.Errorf("codex token exchange failed (%d): %s", res.StatusCode, bodyStr) + } + return nil, fmt.Errorf("codex token exchange failed (%d)", res.StatusCode) + } + + var resp struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + ExpiresIn float64 `json:"expires_in"` + IDToken *string `json:"id_token"` + } + if err := json.Unmarshal(body, &resp); err != nil { + return nil, errors.New("codex token exchange response is incomplete") + } + + if resp.AccessToken == "" || resp.RefreshToken == "" || resp.ExpiresIn <= 0 { + return nil, errors.New("codex token exchange response is incomplete") + } + + accountID, accountUserID, email, err := extractTokenIdentity(resp.AccessToken, resp.IDToken) + if err != nil { + return nil, err + } + + nowMs := time.Now().UnixMilli() + return &CodexCredential{ + Type: "oauth", + Access: resp.AccessToken, + Refresh: resp.RefreshToken, + Expires: nowMs + int64(resp.ExpiresIn*1000), + AccountID: accountID, + AccountUserID: accountUserID, + Email: email, + }, nil +} + +func readAuthData(directory string) (map[string]any, error) { + authPath := filepath.Join(directory, "auth.json") + fi, err := os.Stat(authPath) + if err != nil { + if os.IsNotExist(err) { + return make(map[string]any), nil + } + return nil, errors.New("invalid credential store in auth.json; repair it before logging in") + } + if fi.Size() > 5*1024*1024 { + return nil, errors.New("invalid credential store in auth.json; repair it before logging in") + } + data, err := os.ReadFile(authPath) + if err != nil { + if os.IsNotExist(err) { + return make(map[string]any), nil + } + return nil, errors.New("invalid credential store in auth.json; repair it before logging in") + } + var res map[string]any + if err := json.Unmarshal(data, &res); err != nil { + return nil, errors.New("invalid credential store in auth.json; repair it before logging in") + } + return res, nil +} + +func parseCredentialList(entry any) ([]CodexCredential, error) { + if entry == nil { + return []CodexCredential{}, nil + } + + var items []any + if slice, ok := entry.([]any); ok { + items = slice + } else { + items = []any{entry} + } + + results := make([]CodexCredential, 0, len(items)) + for _, item := range items { + m, ok := item.(map[string]any) + if !ok { + return nil, errors.New("invalid openai-codex credentials in auth.json; repair them before logging in") + } + t, _ := m["type"].(string) + access, _ := m["access"].(string) + refresh, _ := m["refresh"].(string) + accountID, _ := m["accountId"].(string) + + var expires int64 + switch v := m["expires"].(type) { + case float64: + expires = int64(v) + case int64: + expires = v + default: + return nil, errors.New("invalid openai-codex credentials in auth.json; repair them before logging in") + } + + if t != "oauth" || access == "" || refresh == "" || accountID == "" || expires <= 0 { + return nil, errors.New("invalid openai-codex credentials in auth.json; repair them before logging in") + } + + var accountUserID *string + if u, ok := m["accountUserId"].(string); ok && u != "" { + accountUserID = &u + } + var email *string + if em, ok := m["email"].(string); ok && em != "" { + email = &em + } + + results = append(results, CodexCredential{ + Type: t, + Access: access, + Refresh: refresh, + Expires: expires, + AccountID: accountID, + AccountUserID: accountUserID, + Email: email, + }) + } + return results, nil +} + +// LoadCodexAccounts reads and validates codex credentials from auth.json. +func LoadCodexAccounts(directory string) ([]CodexCredential, error) { + data, err := readAuthData(directory) + if err != nil { + return nil, err + } + return parseCredentialList(data["openai-codex"]) +} + +// SaveCodexAccount saves or updates a codex credential in auth.json. +func SaveCodexAccount(directory string, cred CodexCredential) error { + if err := os.MkdirAll(directory, 0700); err != nil { + return err + } + _ = os.Chmod(directory, 0700) + + lockPath := filepath.Join(directory, "auth.lock") + var lockFile *os.File + var err error + for attempt := 0; attempt < 100; attempt++ { + lockFile, err = os.OpenFile(lockPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err == nil { + break + } + if !os.IsExist(err) { + return err + } + time.Sleep(20 * time.Millisecond) + } + if err != nil { + return err + } + defer func() { + _ = lockFile.Close() + _ = os.Remove(lockPath) + }() + + data, err := readAuthData(directory) + if err != nil { + return err + } + + accounts, err := parseCredentialList(data["openai-codex"]) + if err != nil { + return err + } + + identity := CredentialIdentity(cred) + found := false + for i, acct := range accounts { + if CredentialIdentity(acct) == identity { + accounts[i] = cred + found = true + break + } + } + if !found { + accounts = append(accounts, cred) + } + + if len(accounts) == 1 { + data["openai-codex"] = accounts[0] + } else { + data["openai-codex"] = accounts + } + + randomBytes := make([]byte, 16) + _, _ = rand.Read(randomBytes) + tempPath := filepath.Join(directory, fmt.Sprintf("auth.%s.tmp", hex.EncodeToString(randomBytes))) + + encoded, err := json.MarshalIndent(data, "", " ") + if err != nil { + return err + } + encoded = append(encoded, '\n') + + tempFile, err := os.OpenFile(tempPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err != nil { + return err + } + defer func() { + _ = tempFile.Close() + _ = os.Remove(tempPath) + }() + + if _, err := tempFile.Write(encoded); err != nil { + return err + } + if err := tempFile.Sync(); err != nil { + return err + } + if err := tempFile.Close(); err != nil { + return err + } + + authPath := filepath.Join(directory, "auth.json") + return os.Rename(tempPath, authPath) +} + +// OpenBrowser opens a URL in the system's default browser. +func OpenBrowser(urlStr string) { + if flag.Lookup("test.v") != nil || os.Getenv("ALBEDO_NO_BROWSER") != "" { + return + } + var cmd *exec.Cmd + switch runtime.GOOS { + case "darwin": + cmd = exec.Command("open", urlStr) + case "windows": + cmd = exec.Command("cmd", "/c", "start", "", urlStr) + default: + cmd = exec.Command("xdg-open", urlStr) + } + _ = cmd.Start() +} + +// StartCallbackServer starts the local OAuth redirect receiver on port 1455. +func StartCallbackServer(ctx context.Context, state string) (net.Listener, <-chan string, <-chan error, func()) { + codeChan := make(chan string, 1) + errChan := make(chan error, 1) + + mux := http.NewServeMux() + server := &http.Server{ + Handler: mux, + } + + listener, err := net.Listen("tcp", "127.0.0.1:1455") + if err != nil { + errChan <- err + return nil, codeChan, errChan, func() {} + } + + mux.HandleFunc("/auth/callback", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if r.URL.Path != "/auth/callback" { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte("callback route not found")) + return + } + if r.URL.Query().Get("state") != state { + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte("state mismatch")) + return + } + code := r.URL.Query().Get("code") + if code == "" { + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte("missing authorization code")) + return + } + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("OpenAI authentication completed. You can close this window.")) + select { + case codeChan <- code: + default: + } + }) + + go func() { + if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) { + select { + case errChan <- err: + default: + } + } + }() + + closeFn := func() { + _ = server.Close() + _ = listener.Close() + } + + return listener, codeChan, errChan, closeFn +} + +type CodexLoginOptions struct { + OnAuth func(url string) + OnProgress func(message string) + OnManualCodeInput func() (string, error) + OpenBrowser bool + HTTPClient *http.Client +} + +// LoginCodex orchestrates PKCE login flow. +func LoginCodex(ctx context.Context, opts CodexLoginOptions) (*CodexCredential, error) { + verifier, state, authURL := CreateAuthorization() + listener, codeChan, errChan, closeServer := StartCallbackServer(ctx, state) + if listener == nil { + return nil, <-errChan + } + defer closeServer() + + if opts.OnAuth != nil { + opts.OnAuth(authURL) + } + if opts.OnProgress != nil { + opts.OnProgress("waiting for browser authorization") + } + if opts.OpenBrowser { + OpenBrowser(authURL) + } + + manualChan := make(chan string, 1) + manualErrChan := make(chan error, 1) + if opts.OnManualCodeInput != nil { + go func() { + val, err := opts.OnManualCodeInput() + if err != nil { + manualErrChan <- err + return + } + code, parsedState := ParseAuthorizationInput(val) + if parsedState != "" && parsedState != state { + manualErrChan <- errors.New("oauth state mismatch") + return + } + if code == "" { + manualErrChan <- errors.New("missing authorization code") + return + } + manualChan <- code + }() + } + + var code string + select { + case <-ctx.Done(): + return nil, ctx.Err() + case err := <-errChan: + return nil, err + case code = <-codeChan: + case code = <-manualChan: + case err := <-manualErrChan: + return nil, err + } + + if opts.OnProgress != nil { + opts.OnProgress("exchanging authorization code") + } + + return ExchangeCodexCode(ctx, opts.HTTPClient, code, verifier) +} diff --git a/cli/internal/config/codex_test.go b/cli/internal/config/codex_test.go new file mode 100644 index 000000000..e73f7941c --- /dev/null +++ b/cli/internal/config/codex_test.go @@ -0,0 +1,179 @@ +package config + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func makeAccessToken(accountID, accountUserID, email, marker string) string { + payload := map[string]any{ + "https://api.openai.com/auth": map[string]any{ + "chatgpt_account_id": accountID, + "chatgpt_account_user_id": accountUserID, + }, + "https://api.openai.com/profile": map[string]any{ + "email": email, + }, + "marker": marker, + } + data, _ := json.Marshal(payload) + b64 := base64.RawURLEncoding.EncodeToString(data) + return fmt.Sprintf("header.%s.signature", b64) +} + +func makeCredential(accountID, accountUserID, marker string) CodexCredential { + email := "ana@example.test" + uid := accountUserID + return CodexCredential{ + Type: "oauth", + Access: makeAccessToken(accountID, accountUserID, email, marker), + Refresh: fmt.Sprintf("refresh-%s-%s", accountUserID, marker), + Expires: time.Now().UnixMilli() + 3600000, + AccountID: accountID, + AccountUserID: &uid, + Email: &email, + } +} + +func TestCodexAuthorizationParameters(t *testing.T) { + verifier, state, authURL := CreateAuthorization() + u, err := url.Parse(authURL) + if err != nil { + t.Fatal(err) + } + + if u.Scheme+"://"+u.Host+u.Path != "https://auth.openai.com/oauth/authorize" { + t.Fatalf("unexpected authorize URL: %s", authURL) + } + q := u.Query() + if q.Get("client_id") != CodexClientID { + t.Fatalf("unexpected client_id: %s", q.Get("client_id")) + } + if q.Get("redirect_uri") != CodexRedirectURI { + t.Fatalf("unexpected redirect_uri: %s", q.Get("redirect_uri")) + } + if q.Get("code_challenge_method") != "S256" { + t.Fatalf("unexpected code_challenge_method: %s", q.Get("code_challenge_method")) + } + if q.Get("state") != state { + t.Fatalf("state mismatch in url: %s vs %s", q.Get("state"), state) + } + if q.Get("id_token_add_organizations") != "true" { + t.Fatalf("unexpected id_token_add_organizations: %s", q.Get("id_token_add_organizations")) + } + if q.Get("codex_cli_simplified_flow") != "true" { + t.Fatalf("unexpected codex_cli_simplified_flow: %s", q.Get("codex_cli_simplified_flow")) + } + if q.Get("originator") != "albedo" { + t.Fatalf("unexpected originator: %s", q.Get("originator")) + } + if !strings.Contains(q.Get("scope"), "offline_access") || !strings.Contains(q.Get("scope"), "api.connectors.invoke") { + t.Fatalf("unexpected scope: %s", q.Get("scope")) + } + + if len(verifier) != 128 { + t.Fatalf("expected verifier length 128, got %d", len(verifier)) + } + if len(state) != 32 { + t.Fatalf("expected state length 32, got %d", len(state)) + } +} + +func TestParseAuthorizationInput(t *testing.T) { + code, state := ParseAuthorizationInput("http://localhost:1455/auth/callback?code=foo&state=bar") + if code != "foo" || state != "bar" { + t.Fatalf("expected foo / bar, got: %s / %s", code, state) + } + + code, state = ParseAuthorizationInput("foo#bar") + if code != "foo" || state != "bar" { + t.Fatalf("expected foo / bar, got: %s / %s", code, state) + } + + code, state = ParseAuthorizationInput("code=baz&state=qux") + if code != "baz" || state != "qux" { + t.Fatalf("expected baz / qux, got: %s / %s", code, state) + } + + code, state = ParseAuthorizationInput("just-a-code") + if code != "just-a-code" || state != "" { + t.Fatalf("expected just-a-code / empty, got: %s / %s", code, state) + } +} + +func TestCodexAccountsPersistence(t *testing.T) { + tempDir, err := os.MkdirTemp("", "albedo-codex-") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(tempDir) + + accounts, err := LoadCodexAccounts(tempDir) + if err != nil { + t.Fatal(err) + } + if len(accounts) != 0 { + t.Fatalf("expected 0 accounts, got %d", len(accounts)) + } + + c1 := makeCredential("acct-1", "user-1", "v1") + if err := SaveCodexAccount(tempDir, c1); err != nil { + t.Fatal(err) + } + + accounts, err = LoadCodexAccounts(tempDir) + if err != nil { + t.Fatal(err) + } + if len(accounts) != 1 { + t.Fatalf("expected 1 account, got %d", len(accounts)) + } + if accounts[0].AccountID != "acct-1" { + t.Fatalf("expected acct-1, got %s", accounts[0].AccountID) + } + + // Update existing account (matching user identity) + c1Updated := makeCredential("acct-1", "user-1", "v2") + if err := SaveCodexAccount(tempDir, c1Updated); err != nil { + t.Fatal(err) + } + accounts, err = LoadCodexAccounts(tempDir) + if err != nil { + t.Fatal(err) + } + if len(accounts) != 1 { + t.Fatalf("expected 1 account after update, got %d", len(accounts)) + } + if accounts[0].Refresh != c1Updated.Refresh { + t.Fatalf("expected updated refresh token %s, got %s", c1Updated.Refresh, accounts[0].Refresh) + } + + // Add second account + c2 := makeCredential("acct-2", "user-2", "v1") + if err := SaveCodexAccount(tempDir, c2); err != nil { + t.Fatal(err) + } + accounts, err = LoadCodexAccounts(tempDir) + if err != nil { + t.Fatal(err) + } + if len(accounts) != 2 { + t.Fatalf("expected 2 accounts, got %d", len(accounts)) + } + + // Check file permissions + fileInfo, err := os.Stat(filepath.Join(tempDir, "auth.json")) + if err != nil { + t.Fatal(err) + } + if perm := fileInfo.Mode().Perm(); perm != 0600 { + t.Fatalf("expected file mode 0600, got %o", perm) + } +} diff --git a/cli/internal/config/config.go b/cli/internal/config/config.go new file mode 100644 index 000000000..22e329794 --- /dev/null +++ b/cli/internal/config/config.go @@ -0,0 +1,304 @@ +package config + +import ( + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/url" + "os" + "path/filepath" + "regexp" + "strings" + "unicode" +) + +var ( + providerNameRegex = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$`) +) + +// HomeDir returns the albedo configuration directory. +func HomeDir() string { + if env := os.Getenv("ALBEDO_HOME"); env != "" { + abs, err := filepath.Abs(env) + if err == nil { + return abs + } + return env + } + home, err := os.UserHomeDir() + if err != nil { + return ".albedo" + } + return filepath.Join(home, ".albedo") +} + +// Settings represents provider configuration for either OpenAI or Codex. +type Settings struct { + Extension string `json:"extension,omitempty"` + BaseURL string `json:"baseUrl,omitempty"` + APIKey string `json:"apiKey,omitempty"` + Model string `json:"model"` + Protocol string `json:"protocol"` +} + +func (s Settings) IsCodex() bool { + return s.Extension == "codex" +} + +func validateModel(value string) (string, error) { + trimmed := strings.TrimSpace(value) + if trimmed == "" || len(trimmed) > 512 { + return "", errors.New("provider needs a model id of 1–512 characters") + } + for _, r := range trimmed { + if r < 0x20 || r == 0x7f { + return "", errors.New("provider needs a model id of 1–512 characters") + } + } + return trimmed, nil +} + +// Validate checks whether the Settings instance is valid. +func (s Settings) Validate() (Settings, error) { + if s.Extension == "codex" { + if s.Protocol != "responses" { + return s, errors.New("codex requires the responses protocol") + } + model, err := validateModel(s.Model) + if err != nil { + return s, err + } + return Settings{ + Extension: "codex", + Model: model, + Protocol: "responses", + }, nil + } + + if s.Extension != "" && s.Extension != "openai" { + return s, errors.New("openai provider needs an endpoint, api key, model and valid protocol") + } + + if s.APIKey == "" { + return s, errors.New("openai provider needs an endpoint, api key, model and valid protocol") + } + for _, r := range s.APIKey { + if unicode.IsSpace(r) || r < 0x20 || r == 0x7f { + return s, errors.New("openai provider needs an endpoint, api key, model and valid protocol") + } + } + + if s.Protocol != "responses" && s.Protocol != "chat_completions" { + return s, errors.New("openai provider needs an endpoint, api key, model and valid protocol") + } + + endpoint, err := ValidateEndpoint(s.BaseURL) + if err != nil { + return s, err + } + + model, err := validateModel(s.Model) + if err != nil { + return s, err + } + + return Settings{ + Extension: "openai", + BaseURL: endpoint, + APIKey: s.APIKey, + Model: model, + Protocol: s.Protocol, + }, nil +} + +// ValidateProviderName validates a profile name. +func ValidateProviderName(value string) (string, error) { + name := strings.TrimSpace(value) + if !providerNameRegex.MatchString(name) { + return "", errors.New("name must be 1–64 letters, numbers, dots, underscores or hyphens") + } + return name, nil +} + +// ValidateEndpoint parses and validates an HTTP/HTTPS API endpoint without query, credentials, or fragment. +func ValidateEndpoint(value string) (string, error) { + u, err := url.Parse(strings.TrimSpace(value)) + if err != nil || u.Scheme == "" || u.Host == "" { + return "", errors.New("enter an http or https api base url") + } + if u.Scheme != "http" && u.Scheme != "https" { + return "", errors.New("enter an http or https api base url") + } + if u.User != nil || u.RawQuery != "" || u.Fragment != "" { + return "", errors.New("use an http or https base url without credentials, query or fragment") + } + res := u.String() + for strings.HasSuffix(res, "/") { + res = strings.TrimSuffix(res, "/") + } + return res, nil +} + +// Profiles represents the stored provider configuration. +type Profiles struct { + Active string `json:"active,omitempty"` + Providers map[string]Settings `json:"providers"` +} + +type rawConfigFile struct { + Active *string `json:"active,omitempty"` + Providers map[string]Settings `json:"providers,omitempty"` + Extension string `json:"extension,omitempty"` + BaseURL string `json:"baseUrl,omitempty"` + APIKey string `json:"apiKey,omitempty"` + Model string `json:"model,omitempty"` + Protocol string `json:"protocol,omitempty"` +} + +// LoadProfiles reads and validates configuration from config.json in the specified directory. +func LoadProfiles(directory string) (Profiles, error) { + configPath := filepath.Join(directory, "config.json") + fi, err := os.Stat(configPath) + if err != nil { + if os.IsNotExist(err) { + return Profiles{Providers: make(map[string]Settings)}, nil + } + return Profiles{}, err + } + if fi.Size() > 2*1024*1024 { + return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + } + data, err := os.ReadFile(configPath) + if err != nil { + if os.IsNotExist(err) { + return Profiles{Providers: make(map[string]Settings)}, nil + } + return Profiles{}, err + } + + var rawMap map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMap); err != nil { + return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + } + + if _, hasProviders := rawMap["providers"]; !hasProviders { + var single Settings + if err := json.Unmarshal(data, &single); err != nil { + return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + } + validated, err := single.Validate() + if err != nil { + return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + } + return Profiles{ + Active: "default", + Providers: map[string]Settings{"default": validated}, + }, nil + } + + var cfg rawConfigFile + if err := json.Unmarshal(data, &cfg); err != nil { + return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + } + + providers := make(map[string]Settings) + for k, v := range cfg.Providers { + name, err := ValidateProviderName(k) + if err != nil { + return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + } + validated, err := v.Validate() + if err != nil { + return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + } + providers[name] = validated + } + + var active string + if cfg.Active != nil { + active = *cfg.Active + if _, ok := providers[active]; !ok { + return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + } + } + + return Profiles{ + Active: active, + Providers: providers, + }, nil +} + +// SaveProvider stores a named provider configuration in config.json. +func SaveProvider(directory, name string, s Settings) error { + validatedName, err := ValidateProviderName(name) + if err != nil { + return err + } + validatedSettings, err := s.Validate() + if err != nil { + return err + } + + if err := os.MkdirAll(directory, 0700); err != nil { + return err + } + _ = os.Chmod(directory, 0700) + + lockPath := filepath.Join(directory, "config.lock") + lockFile, err := os.OpenFile(lockPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err != nil { + if os.IsExist(err) { + return errors.New("another login is saving; retry, or remove config.lock if that process has stopped") + } + return err + } + defer func() { + _ = lockFile.Close() + _ = os.Remove(lockPath) + }() + + saved, err := LoadProfiles(directory) + if err != nil { + return err + } + + if saved.Providers == nil { + saved.Providers = make(map[string]Settings) + } + saved.Active = validatedName + saved.Providers[validatedName] = validatedSettings + + randomBytes := make([]byte, 16) + _, _ = rand.Read(randomBytes) + tempPath := filepath.Join(directory, fmt.Sprintf("config.%s.tmp", hex.EncodeToString(randomBytes))) + + encoded, err := json.MarshalIndent(saved, "", " ") + if err != nil { + return err + } + encoded = append(encoded, '\n') + + tempFile, err := os.OpenFile(tempPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err != nil { + return err + } + defer func() { + _ = tempFile.Close() + _ = os.Remove(tempPath) + }() + + if _, err := tempFile.Write(encoded); err != nil { + return err + } + if err := tempFile.Sync(); err != nil { + return err + } + if err := tempFile.Close(); err != nil { + return err + } + + configPath := filepath.Join(directory, "config.json") + return os.Rename(tempPath, configPath) +} diff --git a/cli/internal/config/config_test.go b/cli/internal/config/config_test.go new file mode 100644 index 000000000..c87e5b560 --- /dev/null +++ b/cli/internal/config/config_test.go @@ -0,0 +1,122 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestProfilesPersistenceAndMigration(t *testing.T) { + tempDir, err := os.MkdirTemp("", "albedo-profiles-") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(tempDir) + + profs, err := LoadProfiles(tempDir) + if err != nil { + t.Fatalf("expected nil error on empty dir, got: %v", err) + } + if len(profs.Providers) != 0 { + t.Fatalf("expected 0 providers, got %d", len(profs.Providers)) + } + + // Write single-provider legacy config + fixture := `{"baseUrl": "https://example.test/v1", "apiKey": "fixture-secret", "model": "test-model", "protocol": "responses"}` + if err := os.WriteFile(filepath.Join(tempDir, "config.json"), []byte(fixture), 0600); err != nil { + t.Fatal(err) + } + + profs, err = LoadProfiles(tempDir) + if err != nil { + t.Fatalf("failed to load legacy config: %v", err) + } + if profs.Providers["default"].APIKey != "fixture-secret" { + t.Fatalf("expected fixture-secret, got: %s", profs.Providers["default"].APIKey) + } + + // Save named provider + localSettings := Settings{ + Extension: "openai", + BaseURL: "https://example.test/v1", + APIKey: "fixture-secret", + Model: "local-model", + Protocol: "responses", + } + if err := SaveProvider(tempDir, "local", localSettings); err != nil { + t.Fatalf("failed to save provider: %v", err) + } + + profs, err = LoadProfiles(tempDir) + if err != nil { + t.Fatal(err) + } + if profs.Active != "local" { + t.Fatalf("expected active local, got: %s", profs.Active) + } + if profs.Providers["default"].Model != "test-model" { + t.Fatalf("expected default model test-model, got: %s", profs.Providers["default"].Model) + } + if profs.Providers["local"].Model != "local-model" { + t.Fatalf("expected local model local-model, got: %s", profs.Providers["local"].Model) + } + + // Rotate key + localSettings.APIKey = "rotated-key" + if err := SaveProvider(tempDir, "local", localSettings); err != nil { + t.Fatal(err) + } + profs, err = LoadProfiles(tempDir) + if err != nil { + t.Fatal(err) + } + if profs.Providers["local"].APIKey != "rotated-key" { + t.Fatalf("expected rotated-key, got: %s", profs.Providers["local"].APIKey) + } + + // Check file permissions + dirInfo, err := os.Stat(tempDir) + if err != nil { + t.Fatal(err) + } + if perm := dirInfo.Mode().Perm(); perm != 0700 { + t.Fatalf("expected dir mode 0700, got %o", perm) + } + + fileInfo, err := os.Stat(filepath.Join(tempDir, "config.json")) + if err != nil { + t.Fatal(err) + } + if perm := fileInfo.Mode().Perm(); perm != 0600 { + t.Fatalf("expected file mode 0600, got %o", perm) + } + + // Invalid provider name + if err := SaveProvider(tempDir, "bad name", localSettings); err == nil { + t.Fatal("expected error on bad provider name") + } + + // Invalid endpoint + badEndpoint := localSettings + badEndpoint.BaseURL = "https://secret@example.test/v1" + if err := SaveProvider(tempDir, "bad", badEndpoint); err == nil { + t.Fatal("expected error on credentials in endpoint") + } + + // Corrupt config file + brokenContent := "broken private config" + if err := os.WriteFile(filepath.Join(tempDir, "config.json"), []byte(brokenContent), 0600); err != nil { + t.Fatal(err) + } + if err := SaveProvider(tempDir, "new", localSettings); err == nil { + t.Fatal("expected error on corrupt config.json") + } else if !strings.Contains(err.Error(), "invalid provider configuration") { + t.Fatalf("unexpected error message: %v", err) + } + + currentContent, _ := os.ReadFile(filepath.Join(tempDir, "config.json")) + if string(currentContent) != brokenContent { + t.Fatalf("expected corrupt file to remain untouched, got: %s", string(currentContent)) + } +} diff --git a/cli/internal/daemon/client.go b/cli/internal/daemon/client.go new file mode 100644 index 000000000..0c4934fdf --- /dev/null +++ b/cli/internal/daemon/client.go @@ -0,0 +1,843 @@ +package daemon + +import ( + "bufio" + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + "time" +) + +type AgentPhase string + +const ( + PhaseResting AgentPhase = "resting" + PhasePreparing AgentPhase = "preparing" + PhaseReasoning AgentPhase = "reasoning" + PhaseTool AgentPhase = "tool" + PhaseWaiting AgentPhase = "waiting" + PhaseCompacting AgentPhase = "compacting" +) + +var validAgentPhases = map[AgentPhase]bool{ + PhaseResting: true, + PhasePreparing: true, + PhaseReasoning: true, + PhaseTool: true, + PhaseWaiting: true, + PhaseCompacting: true, +} + +type AgentStatus struct { + Running bool `json:"running"` + Idle bool `json:"idle"` + Phase *AgentPhase `json:"phase,omitempty"` +} + +type WorkspaceUpdate struct { + Workspace string `json:"workspace"` +} + +type WorkspaceMissingError struct { + Workspace string +} + +func (e *WorkspaceMissingError) Error() string { + return "workspace not found: " + e.Workspace +} + +type SendResult struct { + OK bool `json:"ok"` + Queued bool `json:"queued,omitempty"` +} + +type ChatClientOptions struct { + BaseURL string + Token string + AgentID string + ClientID string + HTTPClient *http.Client +} + +type ChatClient struct { + baseURL string + token string + agentID string + clientID string + httpClient *http.Client + mu sync.Mutex + afterSeq int + argumentsByCall map[string]string +} + +func readBounded(r io.Reader, limit int64) ([]byte, error) { + data, err := io.ReadAll(io.LimitReader(r, limit+1)) + if err != nil { + return nil, err + } + if int64(len(data)) > limit { + return nil, fmt.Errorf("response body exceeded limit of %d bytes", limit) + } + return data, nil +} + +func NewChatClient(opts ChatClientOptions) *ChatClient { + baseURL := strings.TrimRight(opts.BaseURL, "/") + clientID := opts.ClientID + if clientID == "" { + b := make([]byte, 16) + _, _ = rand.Read(b) + clientID = "cli-" + hex.EncodeToString(b) + } + httpClient := opts.HTTPClient + if httpClient == nil { + httpClient = &http.Client{ + CheckRedirect: func(req *http.Request, via []*http.Request) error { + return http.ErrUseLastResponse + }, + } + } + return &ChatClient{ + baseURL: baseURL, + token: opts.Token, + agentID: strings.TrimSpace(opts.AgentID), + clientID: clientID, + httpClient: httpClient, + afterSeq: -1, + argumentsByCall: make(map[string]string), + } +} + +func (c *ChatClient) ClientID() string { + return c.clientID +} + +func (c *ChatClient) agentURL(path string) string { + if c.agentID != "" { + return fmt.Sprintf("%s/sessions/%s%s", c.baseURL, url.PathEscape(c.agentID), path) + } + return c.baseURL + path +} + +func (c *ChatClient) parseResponseError(res *http.Response) error { + body, err := readBounded(res.Body, 64*1024) + if err != nil { + return fmt.Errorf("%d %s: %w", res.StatusCode, res.Status, err) + } + + var data struct { + Code string `json:"code"` + Error string `json:"error"` + Workspace string `json:"workspace"` + } + if err := json.Unmarshal(body, &data); err == nil { + if data.Code == "workspace_missing" && data.Workspace != "" { + return &WorkspaceMissingError{Workspace: data.Workspace} + } + if data.Error != "" { + return errors.New(data.Error) + } + } + + fallback := strings.TrimSpace(fmt.Sprintf("%d %s", res.StatusCode, res.Status)) + if fallback == "" { + fallback = "request failed" + } + return errors.New(fallback) +} + +func (c *ChatClient) Send(ctx context.Context, content string, image *ImageAttachment) (*SendResult, error) { + reqCtx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + + payload := map[string]any{ + "content": content, + } + if image != nil { + payload["image"] = image + } + if c.clientID != "" { + payload["clientId"] = c.clientID + } + + bodyData, err := json.Marshal(payload) + if err != nil { + return nil, err + } + + route := "/trigger/chat" + if c.agentID != "" { + route = "/events" + } + + req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, c.agentURL(route), bytes.NewReader(bodyData)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + + res, err := c.httpClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + + if res.StatusCode < 200 || res.StatusCode >= 300 { + return nil, c.parseResponseError(res) + } + + body, err := readBounded(res.Body, 64*1024) + if err != nil { + return nil, err + } + + var data struct { + OK bool `json:"ok"` + Queued bool `json:"queued"` + } + _ = json.Unmarshal(body, &data) + + return &SendResult{ + OK: true, + Queued: data.Queued, + }, nil +} + +func (c *ChatClient) ReplaceWorkspace(ctx context.Context, workspace string) (*WorkspaceUpdate, error) { + if c.agentID == "" { + return nil, errors.New("cannot replace workspace without agent ID") + } + + reqCtx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + + healthReq, err := http.NewRequestWithContext(reqCtx, http.MethodGet, c.baseURL+"/health", nil) + if err != nil { + return nil, err + } + if c.token != "" { + healthReq.Header.Set("Authorization", "Bearer "+c.token) + } + + healthRes, err := c.httpClient.Do(healthReq) + if err != nil { + return nil, err + } + defer healthRes.Body.Close() + + if healthRes.StatusCode != http.StatusOK { + return nil, c.parseResponseError(healthRes) + } + + healthBody, err := readBounded(healthRes.Body, 64*1024) + if err != nil { + return nil, err + } + + var health struct { + Capabilities []string `json:"capabilities"` + } + if err := json.Unmarshal(healthBody, &health); err != nil { + return nil, errors.New("daemon returned invalid session metadata") + } + + hasWorkspaceCap := false + for _, cap := range health.Capabilities { + if cap == "session_workspace" { + hasWorkspaceCap = true + break + } + } + if !hasWorkspaceCap { + return nil, errors.New("daemon upgrade needed to change this workspace; when ready, run albedo daemon --stop, then albedo (this clears python variables)") + } + + payload := map[string]string{ + "workspace": workspace, + } + bodyData, err := json.Marshal(payload) + if err != nil { + return nil, err + } + + req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, c.agentURL("/workspace"), bytes.NewReader(bodyData)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + + res, err := c.httpClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + return nil, c.parseResponseError(res) + } + + wsBody, err := readBounded(res.Body, 64*1024) + if err != nil { + return nil, err + } + + var data struct { + Workspace string `json:"workspace"` + } + if err := json.Unmarshal(wsBody, &data); err != nil || data.Workspace == "" { + return nil, errors.New("daemon returned invalid session metadata") + } + + return &WorkspaceUpdate{Workspace: data.Workspace}, nil +} + +func (c *ChatClient) Interrupt(ctx context.Context) (bool, error) { + reqCtx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + + route := "/awp/interrupt" + if c.agentID != "" { + route = "/interrupt" + } + + req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, c.agentURL(route), bytes.NewReader([]byte("{}"))) + if err != nil { + return false, err + } + req.Header.Set("Content-Type", "application/json") + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + + res, err := c.httpClient.Do(req) + if err != nil { + return false, err + } + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + return false, c.parseResponseError(res) + } + + body, err := readBounded(res.Body, 64*1024) + if err != nil { + return false, err + } + + var data struct { + Interrupted bool `json:"interrupted"` + } + _ = json.Unmarshal(body, &data) + return data.Interrupted, nil +} + +func (c *ChatClient) GetStatus(ctx context.Context) (*AgentStatus, error) { + reqCtx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + + req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, c.agentURL("/status"), nil) + if err != nil { + return nil, err + } + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + + res, err := c.httpClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + return nil, c.parseResponseError(res) + } + + body, err := readBounded(res.Body, 64*1024) + if err != nil { + return nil, err + } + + var data struct { + Running bool `json:"running"` + Idle bool `json:"idle"` + Phase *string `json:"phase"` + } + if err := json.Unmarshal(body, &data); err != nil { + return nil, err + } + + var phase *AgentPhase + if data.Phase != nil { + p := AgentPhase(*data.Phase) + if validAgentPhases[p] { + phase = &p + } + } + + return &AgentStatus{ + Running: data.Running, + Idle: data.Idle, + Phase: phase, + }, nil +} + +func parseStreamEvent(raw map[string]any) *StreamEvent { + typ, _ := raw["type"].(string) + if typ == "" { + if txt, ok := raw["text"].(string); ok { + return &StreamEvent{Type: EventText, Text: txt} + } + return nil + } + + var timestamp *int64 + if ts, ok := raw["timestamp"].(float64); ok && ts >= 0 { + t := int64(ts) + timestamp = &t + } + + switch typ { + case "tool_progress": + progVal := raw["progress"] + if progVal == nil { + return &StreamEvent{Type: EventToolProgress, Progress: nil} + } + progMap, ok := progVal.(map[string]any) + if !ok { + return nil + } + callID, _ := progMap["callId"].(string) + name, _ := progMap["name"].(string) + phase, _ := progMap["phase"].(string) + if len(callID) > 200 || len(name) > 100 || (phase != "generating" && phase != "running") { + return nil + } + + var intent *ToolIntent + if im, ok := progMap["intent"].(map[string]any); ok { + k, _ := im["kind"].(string) + t, _ := im["target"].(string) + if (k == "write" || k == "edit" || k == "read" || k == "run") && len(t) <= 300 { + intent = &ToolIntent{Kind: k, Target: t} + } + } + + var code *ToolCodePreview + if cm, ok := progMap["code"].(map[string]any); ok && phase == "generating" { + off, hasOff := cm["offset"].(float64) + txt, hasTxt := cm["text"].(string) + if hasOff && hasTxt && off >= 0 && len(txt) <= 512 { + code = &ToolCodePreview{Offset: int(off), Text: txt} + } + } + + return &StreamEvent{ + Type: EventToolProgress, + Progress: &ToolProgress{ + CallID: callID, + Name: cleanLabel(name), + Phase: phase, + Intent: intent, + Code: code, + }, + } + + case "message": + txt, _ := raw["text"].(string) + return &StreamEvent{ + Type: EventMessage, + Role: "assistant", + Text: txt, + Timestamp: timestamp, + } + + case "interrupted": + return &StreamEvent{Type: EventInterrupted} + + case "retry": + return &StreamEvent{Type: EventRetry} + + case "reset": + return &StreamEvent{Type: EventReset} + + case "note": + txt, _ := raw["text"].(string) + return &StreamEvent{Type: EventNote, Text: txt} + + case "user": + txt, _ := raw["text"].(string) + source, _ := raw["source"].(string) + trig, _ := raw["triggeredAt"].(string) + clientID, _ := raw["clientId"].(string) + img := ParseImageMetadata(raw["image"]) + return &StreamEvent{ + Type: EventUser, + Text: txt, + Source: source, + TriggeredAt: trig, + ClientID: clientID, + Timestamp: timestamp, + Image: img, + } + + case "thinking": + txt, _ := raw["text"].(string) + return &StreamEvent{Type: EventThinking, Text: txt} + + case "error": + txt, _ := raw["text"].(string) + return &StreamEvent{Type: EventError, Text: txt} + + case "tool": + name, _ := raw["name"].(string) + result, _ := raw["result"].(string) + args, _ := raw["args"].(map[string]any) + trace := ParseToolTrace(raw["trace"]) + return &StreamEvent{ + Type: EventTool, + ToolName: name, + ToolArgs: args, + ToolResult: result, + ToolTrace: trace, + } + + case "usage": + model, _ := raw["model"].(string) + var recordedAt *int64 + if ra, ok := raw["recordedAt"].(float64); ok { + r := int64(ra) + recordedAt = &r + } + getInt := func(k string) *int { + if v, ok := raw[k].(float64); ok { + i := int(v) + return &i + } + return nil + } + getFloat := func(k string) *float64 { + if v, ok := raw[k].(float64); ok { + return &v + } + return nil + } + return &StreamEvent{ + Type: EventUsage, + Usage: &Usage{ + Model: model, + RecordedAt: recordedAt, + PromptTokens: getInt("promptTokens"), + CachedPromptTokens: getInt("cachedPromptTokens"), + CacheWriteTokens: getInt("cacheWriteTokens"), + CompletionTokens: getInt("completionTokens"), + TotalTokens: getInt("totalTokens"), + ElapsedMs: getFloat("elapsedMs"), + TokensPerSecond: getFloat("tokensPerSecond"), + }, + } + + case "compacted": + evicted, hasEv := raw["evicted"].(float64) + summary, hasSum := raw["summary"].(string) + if hasEv && hasSum && evicted >= 0 && evicted <= 1000000 && len(summary) <= 60000 { + return &StreamEvent{ + Type: EventCompacted, + Evicted: int(evicted), + Summary: summary, + } + } + return nil + + default: + if txt, ok := raw["text"].(string); ok { + return &StreamEvent{Type: EventText, Text: txt} + } + return nil + } +} + +func (c *ChatClient) Stream(ctx context.Context, onOpen func(), onEvent func(StreamEvent) error) error { + c.mu.Lock() + afterSeq := c.afterSeq + c.mu.Unlock() + + var route string + if c.agentID != "" { + route = fmt.Sprintf("/stream?after_seq=%d", afterSeq) + } else { + if afterSeq > 0 { + route = fmt.Sprintf("/awp/stream?after_seq=%d", afterSeq) + } else { + route = "/awp/stream?tail=true" + } + } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.agentURL(route), nil) + if err != nil { + return err + } + req.Header.Set("Accept", "text/event-stream") + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + + res, err := c.httpClient.Do(req) + if err != nil { + return err + } + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + return c.parseResponseError(res) + } + + if onOpen != nil { + onOpen() + } + + reporter := NewToolProgressReporter(func(prog *ToolProgress) error { + return onEvent(StreamEvent{Type: EventToolProgress, Progress: prog}) + }) + + defer func() { + _ = reporter.Report(nil, "running") + if ctx.Err() != nil { + c.mu.Lock() + c.afterSeq = -1 + c.argumentsByCall = make(map[string]string) + c.mu.Unlock() + } + }() + + scanner := bufio.NewScanner(res.Body) + buf := make([]byte, 64*1024) + scanner.Buffer(buf, 10*1024*1024) + + var eventType string + eventSeq := afterSeq + + for scanner.Scan() { + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + + line := scanner.Text() + if line == "" { + eventType = "" + continue + } + + if strings.HasPrefix(line, "event:") { + eventType = strings.TrimSpace(line[6:]) + continue + } + if strings.HasPrefix(line, "id:") { + if seq, err := strconv.Atoi(strings.TrimSpace(line[3:])); err == nil && seq > 0 { + eventSeq = seq + } + continue + } + if !strings.HasPrefix(line, "data:") { + continue + } + + payload := strings.TrimSpace(line[5:]) + if payload == "" { + continue + } + + var raw any + if err := json.Unmarshal([]byte(payload), &raw); err != nil { + continue + } + + if eventType == "error" { + errStr := payload + if m, ok := raw.(map[string]any); ok { + if e, ok := m["error"].(string); ok { + errStr = e + } else if t, ok := m["text"].(string); ok { + errStr = t + } + } + return errors.New(errStr) + } + + rawMap, isMap := raw.(map[string]any) + if isMap { + if cursorVal, hasCursor := rawMap["cursor"]; hasCursor { + if cursorNum, ok := cursorVal.(float64); ok { + if eventsArr, ok := rawMap["events"].([]any); ok { + for _, evRaw := range eventsArr { + evMap, ok := evRaw.(map[string]any) + if !ok { + continue + } + itemType, _ := evMap["type"].(string) + switch itemType { + case "reset", "retry", "turn_started", "message", "interrupted", "error": + c.mu.Lock() + c.argumentsByCall = make(map[string]string) + c.mu.Unlock() + if err := reporter.Report(nil, "running"); err != nil { + return err + } + } + + if itemType == "reset" { + if err := onEvent(StreamEvent{Type: EventReset}); err != nil { + return err + } + continue + } + if itemType == "turn_started" { + continue + } + if itemType == "tool" { + if callID, ok := evMap["callId"].(string); ok { + c.mu.Lock() + delete(c.argumentsByCall, callID) + c.mu.Unlock() + } + if err := reporter.Report(nil, "running"); err != nil { + return err + } + } + if itemType == "tool_progress" { + if prog, ok := evMap["progress"].(map[string]any); ok { + ph, _ := prog["phase"].(string) + cid, _ := prog["callId"].(string) + if ph == "running" && cid != "" { + c.mu.Lock() + delete(c.argumentsByCall, cid) + c.mu.Unlock() + if err := reporter.Report(nil, "running"); err != nil { + return err + } + } + } + } + if itemType == "arguments_delta" { + callID, _ := evMap["callId"].(string) + text, _ := evMap["text"].(string) + if callID != "" && text != "" { + c.mu.Lock() + fresh := false + if _, exists := c.argumentsByCall[callID]; !exists { + fresh = true + } + + retained := 0 + for k, v := range c.argumentsByCall { + retained += len(k) + len(v) + } + + extraCallID := 0 + if fresh { + extraCallID = len(callID) + } + + if (fresh && len(c.argumentsByCall) >= 32) || retained+len(text)+extraCallID > 2000000 { + c.argumentsByCall = make(map[string]string) + c.afterSeq = -1 + c.mu.Unlock() + return errors.New("tool argument previews exceed client limit") + } + + args := c.argumentsByCall[callID] + text + c.argumentsByCall[callID] = args + c.mu.Unlock() + + call := &ToolCallAssembly{ + ID: callID, + } + call.Function.Name = "python" + call.Function.Arguments = args + if err := reporter.Report(call, "generating"); err != nil { + return err + } + continue + } + } + + if itemType == "tool" { + if strArgs, ok := evMap["args"].(string); ok { + var parsedArgs map[string]any + if err := json.Unmarshal([]byte(strArgs), &parsedArgs); err == nil { + evMap["args"] = parsedArgs + } else { + evMap["args"] = make(map[string]any) + } + } + } + + if ev := parseStreamEvent(evMap); ev != nil { + if err := onEvent(*ev); err != nil { + return err + } + } + } + + c.mu.Lock() + c.afterSeq = int(cursorNum) + c.mu.Unlock() + continue + } + } + } + + var targetMap map[string]any = rawMap + if envType, ok := rawMap["type"].(string); ok { + if envType == "stream.event" { + if pMap, ok := rawMap["payload"].(map[string]any); ok { + targetMap = pMap + } + } else if envType == "conversation.message" { + if pMap, ok := rawMap["payload"].(map[string]any); ok { + role, _ := pMap["role"].(string) + content, _ := pMap["content"].(string) + if role == "assistant" && strings.TrimSpace(content) != "" { + targetMap = map[string]any{ + "type": "message", + "role": "assistant", + "text": content, + } + } + } + } + } + + if ev := parseStreamEvent(targetMap); ev != nil { + if err := onEvent(*ev); err != nil { + return err + } + } + c.mu.Lock() + if eventSeq > c.afterSeq { + c.afterSeq = eventSeq + } + c.mu.Unlock() + } + } + + return scanner.Err() +} diff --git a/cli/internal/daemon/client_test.go b/cli/internal/daemon/client_test.go new file mode 100644 index 000000000..cadc631b7 --- /dev/null +++ b/cli/internal/daemon/client_test.go @@ -0,0 +1,773 @@ +package daemon + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" +) + +func formatPage(cursor int, events []any) string { + b, _ := json.Marshal(map[string]any{ + "cursor": cursor, + "events": events, + }) + return fmt.Sprintf("data: %s\n\n", string(b)) +} + +func TestSendQueuedState(t *testing.T) { + var callCount int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + count := atomic.AddInt32(&callCount, 1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusAccepted) + queued := count > 1 + _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "queued": queued}) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + res1, err := client.Send(context.Background(), "first", nil) + if err != nil { + t.Fatal(err) + } + if !res1.OK || res1.Queued { + t.Fatalf("expected ok=true, queued=false, got: %+v", res1) + } + + res2, err := client.Send(context.Background(), "steer", nil) + if err != nil { + t.Fatal(err) + } + if !res2.OK || !res2.Queued { + t.Fatalf("expected ok=true, queued=true, got: %+v", res2) + } +} + +func TestStreamCompacted(t *testing.T) { + page := formatPage(1, []any{ + map[string]any{"type": "compacted", "evicted": 12, "summary": "facts"}, + map[string]any{"type": "compacted", "evicted": -1, "summary": "no"}, + map[string]any{"type": "compacted", "evicted": 5, "summary": strings.Repeat("x", 60001)}, + }) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte(page)) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + var compacted []StreamEvent + err := client.Stream(context.Background(), nil, func(event StreamEvent) error { + if event.Type == EventCompacted { + compacted = append(compacted, event) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + + if len(compacted) != 1 { + t.Fatalf("expected 1 compacted event, got %d", len(compacted)) + } + if compacted[0].Evicted != 12 || compacted[0].Summary != "facts" { + t.Fatalf("unexpected compacted event: %+v", compacted[0]) + } +} + +func TestStreamThinkingDistinct(t *testing.T) { + page := formatPage(1, []any{ + map[string]any{"type": "thinking", "text": "weighing options"}, + map[string]any{"type": "text", "text": "answer"}, + map[string]any{"type": "message", "role": "assistant", "text": "answer"}, + }) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte(page)) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + var events []StreamEvent + err := client.Stream(context.Background(), nil, func(event StreamEvent) error { + events = append(events, event) + return nil + }) + if err != nil { + t.Fatal(err) + } + + if len(events) != 3 { + t.Fatalf("expected 3 events, got %d", len(events)) + } + if events[0].Type != EventThinking || events[0].Text != "weighing options" { + t.Fatalf("expected thinking event, got: %+v", events[0]) + } + if events[1].Type != EventText || events[1].Text != "answer" { + t.Fatalf("expected text event, got: %+v", events[1]) + } + if events[2].Type != EventMessage || events[2].Text != "answer" { + t.Fatalf("expected message event, got: %+v", events[2]) + } +} + +func TestStreamPagesLivePythonPreviewsTraces(t *testing.T) { + var requestedURLs []string + code := "from pathlib import Path\nPath('demo.py').write_text('hello')" + argsData, _ := json.Marshal(map[string]any{ + "code": code, + "timeout_ms": 1000, + }) + args := string(argsData) + + frames := formatPage(1, []any{ + map[string]any{"type": "reset"}, + map[string]any{"type": "user", "text": "work", "source": "chat", "triggeredAt": ""}, + }) + formatPage(2, []any{ + map[string]any{"type": "arguments_delta", "callId": "call", "text": args[:40]}, + }) + formatPage(3, []any{ + map[string]any{"type": "arguments_delta", "callId": "call", "text": args[40:]}, + }) + formatPage(4, []any{ + map[string]any{ + "type": "tool", + "name": "python", + "args": args, + "result": "ok", + "trace": map[string]any{ + "activities": []any{ + map[string]any{"kind": "read", "target": "demo.py"}, + }, + "changes": []any{}, + }, + }, + map[string]any{"type": "message", "role": "assistant", "text": "done"}, + }) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestedURLs = append(requestedURLs, r.URL.String()) + w.Header().Set("Content-Type", "text/event-stream") + if len(requestedURLs) == 1 { + _, _ = w.Write([]byte(frames)) + } else { + _, _ = w.Write([]byte(formatPage(4, []any{}))) + } + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + var events []StreamEvent + _ = client.Stream(context.Background(), nil, func(event StreamEvent) error { + events = append(events, event) + return nil + }) + _ = client.Stream(context.Background(), nil, func(event StreamEvent) error { + events = append(events, event) + return nil + }) + + if len(events) == 0 { + t.Fatal("expected events") + } + if events[0].Type != EventReset { + t.Fatalf("expected first event reset, got %s", events[0].Type) + } + + hasProgressDemo := false + for _, ev := range events { + if ev.Type == EventToolProgress && ev.Progress != nil && ev.Progress.Code != nil { + if strings.Contains(ev.Progress.Code.Text, "demo.py") { + hasProgressDemo = true + break + } + } + } + if !hasProgressDemo { + t.Fatal("expected tool progress preview with demo.py") + } + + var toolEvent *StreamEvent + for i := range events { + if events[i].Type == EventTool { + toolEvent = &events[i] + break + } + } + if toolEvent == nil { + t.Fatal("expected tool event") + } + if toolEvent.ToolArgs["code"] != code { + t.Fatalf("expected tool arg code %s, got %v", code, toolEvent.ToolArgs["code"]) + } + if toolEvent.ToolTrace == nil || len(toolEvent.ToolTrace.Activities) == 0 || toolEvent.ToolTrace.Activities[0].Target != "demo.py" { + t.Fatalf("unexpected trace in tool event: %+v", toolEvent.ToolTrace) + } + + last := events[len(events)-1] + if last.Type != EventMessage || last.Text != "done" { + t.Fatalf("expected last event message done, got %+v", last) + } + + if len(requestedURLs) < 2 || !strings.HasSuffix(requestedURLs[1], "after_seq=4") { + t.Fatalf("expected reconnect with after_seq=4, got: %+v", requestedURLs) + } +} + +func TestUsagePreservesOriginalRecordedAt(t *testing.T) { + recordedAt := int64(1700000000000) + page := formatPage(3, []any{ + map[string]any{"type": "reset"}, + map[string]any{ + "type": "usage", + "model": "gpt-5", + "promptTokens": 1000, + "completionTokens": 100, + "totalTokens": 1100, + "cachedPromptTokens": 800, + "recordedAt": float64(recordedAt), + }, + }) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte(page)) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + var usage *Usage + _ = client.Stream(context.Background(), nil, func(event StreamEvent) error { + if event.Type == EventUsage { + usage = event.Usage + } + return nil + }) + + if usage == nil { + t.Fatal("expected usage event") + } + if usage.Model != "gpt-5" || *usage.RecordedAt != recordedAt || *usage.CachedPromptTokens != 800 || *usage.PromptTokens != 1000 { + t.Fatalf("unexpected usage: %+v", usage) + } +} + +func TestSendMissingWorkspaceError(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusConflict) + _ = json.NewEncoder(w).Encode(map[string]any{ + "code": "workspace_missing", + "error": "workspace not found", + "workspace": "/gone", + }) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + _, err := client.Send(context.Background(), "continue", nil) + if err == nil { + t.Fatal("expected error") + } + + var wsErr *WorkspaceMissingError + if !strings.Contains(err.Error(), "/gone") { + t.Fatalf("expected /gone in error, got: %v", err) + } + _ = wsErr +} + +func TestWorkspaceReplacementCapability(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if strings.HasSuffix(r.URL.Path, "/health") { + _ = json.NewEncoder(w).Encode(map[string]any{ + "capabilities": []string{"session_workspace"}, + }) + return + } + if strings.HasSuffix(r.URL.Path, "/workspace") { + _ = json.NewEncoder(w).Encode(map[string]any{ + "workspace": "/actual/workspace", + "id": "session", + }) + return + } + w.WriteHeader(http.StatusNotFound) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + update, err := client.ReplaceWorkspace(context.Background(), "/requested/workspace") + if err != nil { + t.Fatal(err) + } + if update.Workspace != "/actual/workspace" { + t.Fatalf("expected /actual/workspace, got: %s", update.Workspace) + } +} + +func TestCompletedCallPreviewsReleaseState(t *testing.T) { + aData, _ := json.Marshal(map[string]any{"code": "read('first.py')"}) + bData, _ := json.Marshal(map[string]any{"code": "read('second.py')"}) + a := string(aData) + b := string(bData) + + var reqCount int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + count := atomic.AddInt32(&reqCount, 1) + w.Header().Set("Content-Type", "text/event-stream") + if count == 1 { + _, _ = w.Write([]byte(formatPage(1, []any{ + map[string]any{"type": "arguments_delta", "callId": "a", "text": a}, + map[string]any{"type": "arguments_delta", "callId": "b", "text": b[:15]}, + map[string]any{"type": "tool", "callId": "a", "name": "python", "args": a, "result": "done"}, + }))) + } else { + _, _ = w.Write([]byte(formatPage(2, []any{ + map[string]any{"type": "arguments_delta", "callId": "b", "text": b[15:]}, + map[string]any{"type": "tool_progress", "progress": map[string]any{"callId": "b", "name": "python", "phase": "running"}}, + map[string]any{"type": "tool", "callId": "b", "name": "python", "args": b, "result": "done"}, + }))) + } + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + var events []StreamEvent + _ = client.Stream(context.Background(), nil, func(event StreamEvent) error { + events = append(events, event) + return nil + }) + _ = client.Stream(context.Background(), nil, func(event StreamEvent) error { + events = append(events, event) + return nil + }) + + hasSecondPreview := false + for _, ev := range events { + if ev.Type == EventToolProgress && ev.Progress != nil && ev.Progress.Code != nil { + if ev.Progress.Code.Text == "read('second.py')" { + hasSecondPreview = true + break + } + } + } + if !hasSecondPreview { + t.Fatal("expected second.py progress preview") + } + + runningIdx := -1 + for i, ev := range events { + if ev.Type == EventToolProgress && ev.Progress != nil && ev.Progress.Phase == "running" { + runningIdx = i + break + } + } + if runningIdx <= 0 { + t.Fatal("expected running progress event preceded by clear") + } + if events[runningIdx-1].Type != EventToolProgress || events[runningIdx-1].Progress != nil { + t.Fatalf("expected nil progress before running, got: %+v", events[runningIdx-1]) + } + + if events[len(events)-1].Type != EventTool { + t.Fatalf("expected last event tool, got: %+v", events[len(events)-1]) + } +} + +func TestMessageTimestampsSurvive(t *testing.T) { + ts := int64(1700000000000) + page := formatPage(1, []any{ + map[string]any{"type": "user", "text": "question", "source": "chat", "triggeredAt": "", "clientId": "sender", "timestamp": float64(ts)}, + map[string]any{"type": "message", "role": "assistant", "text": "answer", "timestamp": float64(ts + 1000)}, + map[string]any{"type": "message", "role": "assistant", "text": "answer"}, + }) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte(page)) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + var events []StreamEvent + _ = client.Stream(context.Background(), nil, func(event StreamEvent) error { + events = append(events, event) + return nil + }) + + if len(events) != 3 { + t.Fatalf("expected 3 events, got %d", len(events)) + } + if events[0].Timestamp == nil || *events[0].Timestamp != ts { + t.Fatalf("expected user timestamp %d, got %v", ts, events[0].Timestamp) + } + if events[1].Timestamp == nil || *events[1].Timestamp != ts+1000 { + t.Fatalf("expected message timestamp %d, got %v", ts+1000, events[1].Timestamp) + } + if events[2].Timestamp != nil { + t.Fatalf("expected nil timestamp for event 2, got %v", events[2].Timestamp) + } +} + +func TestUnfinishedArgumentsBounded(t *testing.T) { + var requestedURLs []string + var serverCallCount int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestedURLs = append(requestedURLs, r.URL.String()) + count := atomic.AddInt32(&serverCallCount, 1) + w.Header().Set("Content-Type", "text/event-stream") + if count <= 33 { + _, _ = w.Write([]byte(formatPage(int(count), []any{ + map[string]any{"type": "arguments_delta", "callId": fmt.Sprintf("call-%d", count), "text": `{"code":"`}, + }))) + } else { + _, _ = w.Write([]byte(formatPage(int(count), []any{ + map[string]any{"type": "reset"}, + map[string]any{"type": "message", "role": "assistant", "text": "recovered"}, + }))) + } + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + for i := 1; i < 33; i++ { + _ = client.Stream(context.Background(), nil, func(event StreamEvent) error { return nil }) + } + + err := client.Stream(context.Background(), nil, func(event StreamEvent) error { return nil }) + if err == nil || !strings.Contains(err.Error(), "previews exceed client limit") { + t.Fatalf("expected error on call count limit, got: %v", err) + } + + var events []StreamEvent + _ = client.Stream(context.Background(), nil, func(event StreamEvent) error { + events = append(events, event) + return nil + }) + + lastURL := requestedURLs[len(requestedURLs)-1] + if !strings.HasSuffix(lastURL, "after_seq=-1") { + t.Fatalf("expected reconnect cursor reset to after_seq=-1, got: %s", lastURL) + } + if len(events) == 0 || events[len(events)-1].Text != "recovered" { + t.Fatalf("expected recovered event, got: %+v", events) + } +} + +func TestDetachingDropsArgumentPreviews(t *testing.T) { + var requestedURLs []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestedURLs = append(requestedURLs, r.URL.String()) + code := "old()" + if len(requestedURLs) > 1 { + code = "new()" + } + raw, _ := json.Marshal(map[string]any{"code": code}) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte(formatPage(len(requestedURLs), []any{ + map[string]any{"type": "arguments_delta", "callId": "same", "text": string(raw)}, + }))) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + ctx, cancel := context.WithCancel(context.Background()) + _ = client.Stream(ctx, nil, func(event StreamEvent) error { + if event.Type == EventToolProgress && event.Progress != nil { + cancel() + } + return nil + }) + + var events []StreamEvent + _ = client.Stream(context.Background(), nil, func(event StreamEvent) error { + events = append(events, event) + return nil + }) + + if len(requestedURLs) < 2 || !strings.HasSuffix(requestedURLs[1], "after_seq=-1") { + t.Fatalf("expected reconnect cursor reset to after_seq=-1, got: %+v", requestedURLs) + } + hasNew := false + for _, ev := range events { + if ev.Type == EventToolProgress && ev.Progress != nil && ev.Progress.Code != nil { + if ev.Progress.Code.Text == "new()" { + hasNew = true + break + } + } + } + if !hasNew { + t.Fatal("expected new() tool progress") + } +} + +func TestCancelingAbortsPendingSendAndStatus(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + time.Sleep(100 * time.Millisecond) + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("{}")) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + _, errSend := client.Send(ctx, "hello", nil) + if errSend == nil { + t.Fatal("expected error on cancelled send") + } + + _, errStatus := client.GetStatus(ctx) + if errStatus == nil { + t.Fatal("expected error on cancelled getStatus") + } +} + +func TestSendCarriesBoundedImageAttachment(t *testing.T) { + var receivedBody map[string]any + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewDecoder(r.Body).Decode(&receivedBody) + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"ok":true}`)) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + ClientID: "sender", + }) + + img := &ImageAttachment{ + ImageMetadata: ImageMetadata{ + MimeType: ImagePNG, + Width: 2, + Height: 3, + Bytes: 5, + }, + Data: "aGVsbG8=", + } + + _, err := client.Send(context.Background(), "describe", img) + if err != nil { + t.Fatal(err) + } + + if receivedBody["content"] != "describe" || receivedBody["clientId"] != "sender" { + t.Fatalf("unexpected body: %+v", receivedBody) + } + imgMap, ok := receivedBody["image"].(map[string]any) + if !ok || imgMap["data"] != "aGVsbG8=" { + t.Fatalf("unexpected image in body: %+v", receivedBody) + } +} + +func TestUserReplayAcceptsBoundedImageMetadata(t *testing.T) { + page := formatPage(1, []any{ + map[string]any{ + "type": "user", "text": "one", "source": "chat", "triggeredAt": "", + "image": map[string]any{"mimeType": "image/png", "width": 2, "height": 3, "bytes": 5}, + }, + map[string]any{ + "type": "user", "text": "two", "source": "chat", "triggeredAt": "", + "image": map[string]any{"mimeType": "image/gif", "width": 2, "height": 3, "bytes": 5, "data": "secret"}, + }, + }) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte(page)) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + var events []StreamEvent + _ = client.Stream(context.Background(), nil, func(event StreamEvent) error { + events = append(events, event) + return nil + }) + + if len(events) != 2 { + t.Fatalf("expected 2 events, got %d", len(events)) + } + if events[0].Image == nil || events[0].Image.MimeType != ImagePNG { + t.Fatalf("expected valid png image for event 0: %+v", events[0]) + } + if events[1].Image != nil { + t.Fatalf("expected nil image for event 1 (gif dropped): %+v", events[1]) + } +} + +func TestStreamEventNote(t *testing.T) { + page := formatPage(1, []any{ + map[string]any{"type": "note", "text": "kernel idle timeout released"}, + }) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte(page)) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + var events []StreamEvent + err := client.Stream(context.Background(), nil, func(event StreamEvent) error { + events = append(events, event) + return nil + }) + if err != nil { + t.Fatal(err) + } + + if len(events) != 1 { + t.Fatalf("expected 1 event, got %d", len(events)) + } + if events[0].Type != EventNote || events[0].Text != "kernel idle timeout released" { + t.Fatalf("expected EventNote, got %+v", events[0]) + } +} + +func TestStreamCallbackErrorBackpressure(t *testing.T) { + // Test onEvent error on reset + resetPage := formatPage(1, []any{ + map[string]any{"type": "reset"}, + map[string]any{"type": "text", "text": "should not be reached"}, + }) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte(resetPage)) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + expectedErr := errors.New("ui aborted on reset") + err := client.Stream(context.Background(), nil, func(event StreamEvent) error { + if event.Type == EventReset { + return expectedErr + } + return nil + }) + + if !errors.Is(err, expectedErr) { + t.Fatalf("expected %v, got %v", expectedErr, err) + } +} + +func TestBoundedResponseExceeded(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(strings.Repeat("x", 70*1024))) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + _, err := client.GetStatus(context.Background()) + if err == nil || !strings.Contains(err.Error(), "exceeded limit") { + t.Fatalf("expected limit exceeded error, got: %v", err) + } +} + +func TestStreamProgressCallbackErrorBackpressure(t *testing.T) { + deltaPage := formatPage(1, []any{ + map[string]any{"type": "arguments_delta", "callId": "call1", "text": `{"code":"read('foo')"`}, + }) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte(deltaPage)) + })) + defer server.Close() + + client := NewChatClient(ChatClientOptions{ + BaseURL: server.URL, + AgentID: "session", + }) + + expectedErr := errors.New("ui cancelled on progress") + err := client.Stream(context.Background(), nil, func(event StreamEvent) error { + if event.Type == EventToolProgress { + return expectedErr + } + return nil + }) + + if !errors.Is(err, expectedErr) { + t.Fatalf("expected %v, got %v", expectedErr, err) + } +} diff --git a/cli/internal/daemon/commands.go b/cli/internal/daemon/commands.go new file mode 100644 index 000000000..332f7d76e --- /dev/null +++ b/cli/internal/daemon/commands.go @@ -0,0 +1,122 @@ +package daemon + +import ( + "encoding/json" + "errors" + "fmt" + "regexp" + "strings" +) + +var ( + commandTokenPattern = regexp.MustCompile(`^/[^\s]+`) + commandExactPattern = regexp.MustCompile(`^/[^\s]+$`) + methodPattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) +) + +type CommandArgument struct { + Name string `json:"name"` + Description string `json:"description"` + Required bool `json:"required"` + Choices []string `json:"choices,omitempty"` +} + +type SessionCommand struct { + Name string `json:"name"` + Description string `json:"description"` + Method string `json:"method"` + Arguments []CommandArgument `json:"arguments"` + ModelCallable bool `json:"modelCallable"` + UserTurn bool `json:"userTurn"` + Page *bool `json:"page,omitempty"` +} + +type CommandMenuItem struct { + Name string + Description string +} + +// CommandMenuItems flattens command catalog into runnable menu entries. +func CommandMenuItems(catalog []SessionCommand) []CommandMenuItem { + var items []CommandMenuItem + for _, cmd := range catalog { + if len(cmd.Arguments) > 0 && cmd.Arguments[0].Required && len(cmd.Arguments[0].Choices) > 0 { + for _, choice := range cmd.Arguments[0].Choices { + items = append(items, CommandMenuItem{ + Name: fmt.Sprintf("%s %s", cmd.Name, choice), + Description: cmd.Arguments[0].Description, + }) + } + } else { + items = append(items, CommandMenuItem{ + Name: cmd.Name, + Description: cmd.Description, + }) + } + } + return items +} + +func isValidCommand(cmd SessionCommand) bool { + if !commandExactPattern.MatchString(cmd.Name) { + return false + } + if !methodPattern.MatchString(cmd.Method) { + return false + } + for _, arg := range cmd.Arguments { + if arg.Name == "" || arg.Description == "" { + return false + } + } + return true +} + +// ParseCommandCatalog validates command catalog JSON from daemon. +func ParseCommandCatalog(data []byte) ([]SessionCommand, error) { + var rawList []json.RawMessage + if err := json.Unmarshal(data, &rawList); err != nil { + return nil, errors.New("daemon returned invalid command catalog") + } + + commands := make([]SessionCommand, 0, len(rawList)) + for _, raw := range rawList { + var cmd SessionCommand + if err := json.Unmarshal(raw, &cmd); err == nil { + if isValidCommand(cmd) { + commands = append(commands, cmd) + } + } + } + + if len(rawList) > 0 && len(commands) == 0 { + return nil, errors.New("daemon returned invalid command metadata") + } + + return commands, nil +} + +// ParseCommandInvocation extracts matched command and arguments from user input. +func ParseCommandInvocation(value string, catalog []SessionCommand) (name, args string, ok bool) { + loc := commandTokenPattern.FindStringIndex(value) + if loc == nil { + return "", "", false + } + token := value[loc[0]:loc[1]] + var matched *SessionCommand + for i := range catalog { + if catalog[i].Name == token { + matched = &catalog[i] + break + } + } + if matched == nil { + return "", "", false + } + + rest := value[loc[1]:] + if strings.HasPrefix(rest, " ") { + rest = rest[1:] + } + return matched.Name, rest, true +} diff --git a/cli/internal/daemon/commands_test.go b/cli/internal/daemon/commands_test.go new file mode 100644 index 000000000..1d0c3696e --- /dev/null +++ b/cli/internal/daemon/commands_test.go @@ -0,0 +1,40 @@ +package daemon + +import ( + "testing" +) + +func TestParseCommandCatalog(t *testing.T) { + raw := []byte(`[ + {"name": "/help", "description": "show help", "method": "help", "arguments": [], "modelCallable": false, "userTurn": true}, + {"name": "/mode", "description": "switch mode", "method": "set_mode", "arguments": [ + {"name": "mode", "description": "target mode", "required": true, "choices": ["fast", "deep"]} + ], "modelCallable": true, "userTurn": true} + ]`) + + catalog, err := ParseCommandCatalog(raw) + if err != nil { + t.Fatal(err) + } + if len(catalog) != 2 { + t.Fatalf("expected 2 commands, got %d", len(catalog)) + } + + menuItems := CommandMenuItems(catalog) + if len(menuItems) != 3 { // /help, /mode fast, /mode deep + t.Fatalf("expected 3 menu items, got %d", len(menuItems)) + } + if menuItems[1].Name != "/mode fast" || menuItems[2].Name != "/mode deep" { + t.Fatalf("unexpected menu items: %+v", menuItems) + } + + name, args, ok := ParseCommandInvocation("/help", catalog) + if !ok || name != "/help" || args != "" { + t.Fatalf("unexpected invocation parse: %s, %s, %v", name, args, ok) + } + + name, args, ok = ParseCommandInvocation("/mode deep please", catalog) + if !ok || name != "/mode" || args != "deep please" { + t.Fatalf("unexpected invocation parse: %s, %s, %v", name, args, ok) + } +} diff --git a/cli/internal/daemon/events.go b/cli/internal/daemon/events.go new file mode 100644 index 000000000..3a11f0e5c --- /dev/null +++ b/cli/internal/daemon/events.go @@ -0,0 +1,164 @@ +package daemon + +import ( + "encoding/json" + "strings" + "unicode" +) + +// Display-only execution evidence, never appended to the model's tool output. +type ToolActivity struct { + Kind string `json:"kind"` // "read" | "search" | "list" | "run" + Target string `json:"target"` + Failed bool `json:"failed,omitempty"` +} + +type FileChange struct { + Path string `json:"path"` + Kind string `json:"kind"` // "diff" | "unavailable" + Diff string `json:"diff,omitempty"` + Added int `json:"added,omitempty"` + Removed int `json:"removed,omitempty"` + Reason string `json:"reason,omitempty"` +} + +type ToolTrace struct { + Activities []ToolActivity `json:"activities"` + Changes []FileChange `json:"changes"` + Truncated bool `json:"truncated,omitempty"` +} + +func isSafeText(s string, limit int) bool { + return len(s) <= limit +} + +// ParseToolTrace validates and extracts a ToolTrace from untyped data. +func ParseToolTrace(raw any) *ToolTrace { + if raw == nil { + return nil + } + + data, err := json.Marshal(raw) + if err != nil { + return nil + } + + var trace ToolTrace + if err := json.Unmarshal(data, &trace); err != nil { + return nil + } + + if len(trace.Activities) > 64 || len(trace.Changes) > 16 { + return nil + } + + for _, act := range trace.Activities { + switch act.Kind { + case "read", "search", "list", "run": + default: + return nil + } + if !isSafeText(act.Target, 1000) { + return nil + } + } + + for _, ch := range trace.Changes { + if !isSafeText(ch.Path, 1000) { + return nil + } + if ch.Kind == "unavailable" { + if !isSafeText(ch.Reason, 1000) { + return nil + } + } else if ch.Kind == "diff" { + if !isSafeText(ch.Diff, 16000) || ch.Added < 0 || ch.Removed < 0 { + return nil + } + } else { + return nil + } + } + + return &trace +} + +// ToolIntent indicates inferred intent of a tool call. +type ToolIntent struct { + Kind string `json:"kind"` // "write" | "edit" | "read" | "run" + Target string `json:"target"` +} + +type ToolCodePreview struct { + Offset int `json:"offset"` + Text string `json:"text"` +} + +type ToolProgress struct { + CallID string `json:"callId"` + Name string `json:"name"` + Phase string `json:"phase"` // "generating" | "running" + Intent *ToolIntent `json:"intent,omitempty"` + Code *ToolCodePreview `json:"code,omitempty"` +} + +type EventType string + +const ( + EventReset EventType = "reset" + EventRetry EventType = "retry" + EventText EventType = "text" + EventError EventType = "error" + EventInterrupted EventType = "interrupted" + EventMessage EventType = "message" + EventUser EventType = "user" + EventThinking EventType = "thinking" + EventNote EventType = "note" + EventCompacted EventType = "compacted" + EventToolProgress EventType = "tool_progress" + EventTool EventType = "tool" + EventUsage EventType = "usage" +) + +type Usage struct { + Model string `json:"model,omitempty"` + RecordedAt *int64 `json:"recordedAt,omitempty"` + PromptTokens *int `json:"promptTokens,omitempty"` + CachedPromptTokens *int `json:"cachedPromptTokens,omitempty"` + CacheWriteTokens *int `json:"cacheWriteTokens,omitempty"` + CompletionTokens *int `json:"completionTokens,omitempty"` + TotalTokens *int `json:"totalTokens,omitempty"` + ElapsedMs *float64 `json:"elapsedMs,omitempty"` + TokensPerSecond *float64 `json:"tokensPerSecond,omitempty"` +} + +type StreamEvent struct { + Type EventType `json:"type"` + Text string `json:"text,omitempty"` + Role string `json:"role,omitempty"` // "assistant" + Timestamp *int64 `json:"timestamp,omitempty"` + Source string `json:"source,omitempty"` + TriggeredAt string `json:"triggeredAt,omitempty"` + ClientID string `json:"clientId,omitempty"` + Image *ImageMetadata `json:"image,omitempty"` + Evicted int `json:"evicted,omitempty"` + Summary string `json:"summary,omitempty"` + Progress *ToolProgress `json:"progress,omitempty"` + ToolName string `json:"name,omitempty"` + ToolArgs map[string]any `json:"args,omitempty"` + ToolResult string `json:"result,omitempty"` + ToolTrace *ToolTrace `json:"trace,omitempty"` + Usage *Usage `json:"usage,omitempty"` +} + +func sanitizeControlRunes(s string) string { + var sb strings.Builder + for _, r := range s { + if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) { + sb.WriteRune(' ') + } else { + sb.WriteRune(r) + } + } + return sb.String() +} diff --git a/cli/internal/daemon/image.go b/cli/internal/daemon/image.go new file mode 100644 index 000000000..25349e72b --- /dev/null +++ b/cli/internal/daemon/image.go @@ -0,0 +1,91 @@ +package daemon + +import ( + "encoding/json" + "fmt" + "math" + "strings" +) + +type ImageMimeType string + +const ( + ImagePNG ImageMimeType = "image/png" + ImageJPEG ImageMimeType = "image/jpeg" + ImageWEBP ImageMimeType = "image/webp" +) + +type ImageMetadata struct { + MimeType ImageMimeType `json:"mimeType"` + Width int `json:"width"` + Height int `json:"height"` + Bytes int `json:"bytes"` +} + +type ImageAttachment struct { + ImageMetadata + Data string `json:"data"` +} + +var validMimeTypes = map[ImageMimeType]bool{ + ImagePNG: true, + ImageJPEG: true, + ImageWEBP: true, +} + +// ParseImageMetadata validates raw image metadata fields and returns nil if invalid. +func ParseImageMetadata(val any) *ImageMetadata { + if val == nil { + return nil + } + + data, err := json.Marshal(val) + if err != nil { + return nil + } + + var meta ImageMetadata + if err := json.Unmarshal(data, &meta); err != nil { + return nil + } + + if !validMimeTypes[meta.MimeType] { + return nil + } + + if meta.Width < 1 || meta.Width > 16384 { + return nil + } + if meta.Height < 1 || meta.Height > 16384 { + return nil + } + if int64(meta.Width)*int64(meta.Height) > 40_000_000 { + return nil + } + if meta.Bytes < 1 || meta.Bytes > 5*1024*1024 { + return nil + } + + return &meta +} + +// ImageLabel returns human-readable label for image metadata. +func ImageLabel(meta ImageMetadata) string { + var size string + if meta.Bytes >= 1024*1024 { + size = fmt.Sprintf("%.1f MB", float64(meta.Bytes)/1024.0/1024.0) + } else if meta.Bytes >= 1024 { + size = fmt.Sprintf("%d KB", int(math.Ceil(float64(meta.Bytes)/1024.0))) + } else { + size = fmt.Sprintf("%d B", meta.Bytes) + } + + prefix := "" + if strings.HasPrefix(string(meta.MimeType), "image/") { + prefix = strings.ToUpper(string(meta.MimeType)[6:]) + } else { + prefix = strings.ToUpper(string(meta.MimeType)) + } + + return fmt.Sprintf("%s %d×%d · %s", prefix, meta.Width, meta.Height, size) +} diff --git a/cli/internal/daemon/image_test.go b/cli/internal/daemon/image_test.go new file mode 100644 index 000000000..e6635a322 --- /dev/null +++ b/cli/internal/daemon/image_test.go @@ -0,0 +1,71 @@ +package daemon + +import ( + "testing" +) + +func TestParseImageMetadata(t *testing.T) { + valid := map[string]any{ + "mimeType": "image/png", + "width": 800, + "height": 600, + "bytes": 120000, + } + meta := ParseImageMetadata(valid) + if meta == nil { + t.Fatal("expected valid image metadata") + } + if meta.MimeType != ImagePNG || meta.Width != 800 || meta.Height != 600 || meta.Bytes != 120000 { + t.Fatalf("unexpected metadata values: %+v", meta) + } + + // Bad mimeType + badMime := map[string]any{ + "mimeType": "image/gif", + "width": 800, + "height": 600, + "bytes": 120000, + } + if ParseImageMetadata(badMime) != nil { + t.Fatal("expected nil for image/gif") + } + + // Too large dimensions + hugeDim := map[string]any{ + "mimeType": "image/jpeg", + "width": 10000, + "height": 10000, + "bytes": 120000, + } + if ParseImageMetadata(hugeDim) != nil { + t.Fatal("expected nil for dimension product > 40M") + } + + // Too many bytes + hugeBytes := map[string]any{ + "mimeType": "image/webp", + "width": 100, + "height": 100, + "bytes": 10 * 1024 * 1024, + } + if ParseImageMetadata(hugeBytes) != nil { + t.Fatal("expected nil for bytes > 5MB") + } +} + +func TestImageLabel(t *testing.T) { + cases := []struct { + meta ImageMetadata + expected string + }{ + {ImageMetadata{MimeType: ImagePNG, Width: 800, Height: 600, Bytes: 500}, "PNG 800×600 · 500 B"}, + {ImageMetadata{MimeType: ImageJPEG, Width: 1920, Height: 1080, Bytes: 150000}, "JPEG 1920×1080 · 147 KB"}, + {ImageMetadata{MimeType: ImageWEBP, Width: 2048, Height: 1536, Bytes: 2500000}, "WEBP 2048×1536 · 2.4 MB"}, + } + + for _, tc := range cases { + if res := ImageLabel(tc.meta); res != tc.expected { + t.Errorf("expected %s, got %s", tc.expected, res) + } + } +} diff --git a/cli/internal/daemon/lifecycle.go b/cli/internal/daemon/lifecycle.go new file mode 100644 index 000000000..64cc34eb8 --- /dev/null +++ b/cli/internal/daemon/lifecycle.go @@ -0,0 +1,365 @@ +package daemon + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "time" +) + +var sanitizerRegex = regexp.MustCompile(`[\p{Cc}\x{202a}-\x{202e}\x{2066}-\x{2069}]`) + +const ( + pollInterval = 100 * time.Millisecond + pollAttempts = 300 +) + +type Connection struct { + Port int `json:"port"` + Token string `json:"token"` + Pid int `json:"pid"` + Version int `json:"version"` +} + +type Session struct { + ID string `json:"id"` + Title string `json:"title,omitempty"` + LastAssistantAt *int64 `json:"last_assistant_at,omitempty"` + Workspace string `json:"workspace"` + Model string `json:"model"` + Protocol string `json:"protocol"` + Provider string `json:"provider"` +} + +func AssistantAge(timestamp *int64, now time.Time) string { + if timestamp == nil { + return "time unknown" + } + sec := now.Unix() - *timestamp + if sec < 0 { + sec = 0 + } + if sec < 60 { + return "just now" + } + if sec < 3600 { + return fmt.Sprintf("%dm ago", sec/60) + } + if sec < 86400 { + return fmt.Sprintf("%dh ago", sec/3600) + } + return fmt.Sprintf("%dd ago", sec/86400) +} + +func SessionListing(sessions []Session, now time.Time) string { + if len(sessions) == 0 { + return "no sessions" + } + + lines := make([]string, 0, len(sessions)) + for _, s := range sessions { + title := sanitizerRegex.ReplaceAllString(s.Title, " ") + title = strings.TrimSpace(title) + if title == "" { + title = "session name unavailable" + } + shortID := s.ID + if len(shortID) > 8 { + shortID = shortID[:8] + } + lines = append(lines, fmt.Sprintf("%s [%s]\n last assistant: %s", title, shortID, AssistantAge(s.LastAssistantAt, now))) + } + + return strings.Join(lines, "\n\n") +} + +func Existing(homeDir string) (*Connection, error) { + recordPath := filepath.Join(homeDir, "daemon.json") + fi, err := os.Stat(recordPath) + if err != nil || fi.Size() > 64*1024 { + return nil, nil + } + data, err := os.ReadFile(recordPath) + if err != nil { + return nil, nil + } + + var conn Connection + if err := json.Unmarshal(data, &conn); err != nil { + return nil, nil + } + + if conn.Port < 1 || conn.Port > 65535 || conn.Token == "" || (conn.Version != 1 && conn.Version != 2) { + return nil, nil + } + + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/health", conn.Port), nil) + if err != nil { + return nil, nil + } + req.Header.Set("Authorization", "Bearer "+conn.Token) + + client := &http.Client{ + CheckRedirect: func(req *http.Request, via []*http.Request) error { + return http.ErrUseLastResponse + }, + } + res, err := client.Do(req) + if err != nil { + return nil, nil + } + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + return nil, nil + } + + body, err := readBounded(res.Body, 64*1024) + if err != nil { + return nil, nil + } + + var health struct { + Version int `json:"version"` + } + if err := json.Unmarshal(body, &health); err != nil { + return nil, nil + } + + if health.Version == conn.Version { + return &conn, nil + } + + return nil, nil +} + +func checkCompatible(conn *Connection) (*Connection, error) { + if conn.Version != 2 { + return nil, errors.New("an older daemon is running; when its work is finished, run albedo daemon --stop, then start albedo again") + } + return conn, nil +} + +func resolveDaemonExecutable(path string) (string, error) { + if !filepath.IsAbs(path) { + return "", fmt.Errorf("ALBEDO_DAEMON must be an absolute executable path: %q", path) + } + resolved, err := exec.LookPath(path) + if err != nil { + return "", fmt.Errorf("invalid ALBEDO_DAEMON executable %q: %w", path, err) + } + fi, err := os.Stat(resolved) + if err != nil { + return "", fmt.Errorf("invalid ALBEDO_DAEMON executable %q: %w", path, err) + } + if fi.IsDir() { + return "", fmt.Errorf("invalid ALBEDO_DAEMON executable %q: is a directory", path) + } + return resolved, nil +} + +func buildDaemonEnv(homeDir, tokenHex string) []string { + var env []string + filteredVars := map[string]bool{ + "ALBEDO_API_KEY": true, + "ALBEDO_MODEL": true, + "ALBEDO_BASE_URL": true, + "ALBEDO_PROTOCOL": true, + } + for _, kv := range os.Environ() { + k := strings.SplitN(kv, "=", 2)[0] + if !filteredVars[k] { + env = append(env, kv) + } + } + return append(env, "ALBEDO_HOME="+homeDir, "ALBEDO_TOKEN="+tokenHex) +} + +func daemonCommand(daemonExe, projectRoot string, env []string) (*exec.Cmd, error) { + if daemonExe != "" { + resolved, err := resolveDaemonExecutable(daemonExe) + if err != nil { + return nil, err + } + cmd := exec.Command(resolved) + cmd.Dir = "" + cmd.Env = env + return cmd, nil + } + + cmd := exec.Command("gleam", "run") + cmd.Dir = projectRoot + cmd.Env = env + return cmd, nil +} + +func Ensure(homeDir, projectRoot string) (*Connection, error) { + current, err := Existing(homeDir) + if err != nil { + return nil, err + } + if current != nil { + return checkCompatible(current) + } + + daemonExe := os.Getenv("ALBEDO_DAEMON") + if daemonExe != "" { + if _, err := resolveDaemonExecutable(daemonExe); err != nil { + return nil, err + } + } + + if err := os.MkdirAll(homeDir, 0700); err != nil { + return nil, err + } + _ = os.Chmod(homeDir, 0700) + + lockPath := filepath.Join(homeDir, "starting.lock") + lockFile, err := os.OpenFile(lockPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err != nil { + if os.IsExist(err) { + for attempt := 0; attempt < pollAttempts; attempt++ { + running, err := Existing(homeDir) + if err != nil { + return nil, err + } + if running != nil { + return checkCompatible(running) + } + time.Sleep(pollInterval) + } + return nil, fmt.Errorf("daemon startup timed out; inspect %s/daemon.log; remove %s if its starter is no longer running", homeDir, lockPath) + } + return nil, err + } + defer func() { + _ = lockFile.Close() + _ = os.Remove(lockPath) + }() + + again, err := Existing(homeDir) + if err != nil { + return nil, err + } + if again != nil { + return checkCompatible(again) + } + + logPath := filepath.Join(homeDir, "daemon.log") + logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) + if err != nil { + return nil, err + } + + randomToken := make([]byte, 32) + _, _ = rand.Read(randomToken) + tokenHex := hex.EncodeToString(randomToken) + + env := buildDaemonEnv(homeDir, tokenHex) + cmd, err := daemonCommand(daemonExe, projectRoot, env) + if err != nil { + _ = logFile.Close() + return nil, err + } + cmd.Stdout = logFile + cmd.Stderr = logFile + + if err := cmd.Start(); err != nil { + _ = logFile.Close() + return nil, err + } + _ = logFile.Close() + + for attempt := 0; attempt < pollAttempts; attempt++ { + running, err := Existing(homeDir) + if err != nil { + return nil, err + } + if running != nil { + return checkCompatible(running) + } + time.Sleep(pollInterval) + } + + return nil, fmt.Errorf("daemon startup timed out; inspect %s/daemon.log", homeDir) +} + +func Request[T any](ctx context.Context, conn *Connection, path string, body any) (T, error) { + var zero T + if ctx == nil { + ctx = context.Background() + } + + reqCtx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + + method := http.MethodGet + var bodyReader io.Reader + if body != nil { + method = http.MethodPost + encoded, err := json.Marshal(body) + if err != nil { + return zero, err + } + bodyReader = bytes.NewReader(encoded) + } + + reqURL := fmt.Sprintf("http://127.0.0.1:%d%s", conn.Port, path) + req, err := http.NewRequestWithContext(reqCtx, method, reqURL, bodyReader) + if err != nil { + return zero, err + } + + req.Header.Set("Authorization", "Bearer "+conn.Token) + req.Header.Set("Content-Type", "application/json") + + client := &http.Client{ + CheckRedirect: func(req *http.Request, via []*http.Request) error { + return http.ErrUseLastResponse + }, + } + + res, err := client.Do(req) + if err != nil { + return zero, err + } + defer res.Body.Close() + + respData, err := readBounded(res.Body, 50*1024*1024) + if err != nil { + return zero, err + } + + if res.StatusCode < 200 || res.StatusCode >= 300 { + var errResp struct { + Error string `json:"error"` + } + _ = json.Unmarshal(respData, &errResp) + if errResp.Error != "" { + return zero, errors.New(errResp.Error) + } + return zero, fmt.Errorf("HTTP %d", res.StatusCode) + } + + var result T + if len(respData) > 0 { + if err := json.Unmarshal(respData, &result); err != nil { + return zero, err + } + } + return result, nil +} diff --git a/cli/internal/daemon/lifecycle_test.go b/cli/internal/daemon/lifecycle_test.go new file mode 100644 index 000000000..74962a295 --- /dev/null +++ b/cli/internal/daemon/lifecycle_test.go @@ -0,0 +1,147 @@ +package daemon + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "testing" +) + +func TestExistingAndRequest(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + auth := r.Header.Get("Authorization") + if auth != "Bearer test-token" { + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`{"error":"unauthorized"}`)) + return + } + + if r.URL.Path == "/health" { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"ok":true,"version":2}`)) + return + } + + if r.URL.Path == "/test" { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"status":"success"}`)) + return + } + + w.WriteHeader(http.StatusNotFound) + })) + defer ts.Close() + + parts := strings.Split(ts.URL, ":") + portStr := parts[len(parts)-1] + port, _ := strconv.Atoi(portStr) + + tempDir, err := os.MkdirTemp("", "albedo-lifecycle-") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(tempDir) + + connInfo := Connection{ + Port: port, + Token: "test-token", + Pid: 1234, + Version: 2, + } + data, _ := json.Marshal(connInfo) + _ = os.WriteFile(filepath.Join(tempDir, "daemon.json"), data, 0600) + + conn, err := Existing(tempDir) + if err != nil { + t.Fatal(err) + } + if conn == nil { + t.Fatal("expected active connection from Existing()") + } + if conn.Port != port || conn.Token != "test-token" { + t.Fatalf("unexpected conn info: %+v", conn) + } + + type TestResp struct { + Status string `json:"status"` + } + resp, err := Request[TestResp](context.Background(), conn, "/test", nil) + if err != nil { + t.Fatalf("request failed: %v", err) + } + if resp.Status != "success" { + t.Fatalf("expected success, got %s", resp.Status) + } +} + +func TestCheckCompatibleVersion(t *testing.T) { + conn1 := &Connection{Version: 1} + if _, err := checkCompatible(conn1); err == nil { + t.Fatal("expected error on version 1 daemon") + } + + conn2 := &Connection{Version: 2} + if _, err := checkCompatible(conn2); err != nil { + t.Fatalf("expected nil error on version 2 daemon, got: %v", err) + } +} + +func TestPackagedDaemonCommand(t *testing.T) { + path := filepath.Join(t.TempDir(), "daemon with spaces") + if err := os.WriteFile(path, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil { + t.Fatal(err) + } + env := []string{"ALBEDO_HOME=/tmp/fixture", "ALBEDO_TOKEN=fixture"} + cmd, err := daemonCommand(path, "/missing/source/tree", env) + if err != nil { + t.Fatal(err) + } + if cmd.Path != path || len(cmd.Args) != 1 || cmd.Args[0] != path || cmd.Dir != "" { + t.Fatalf("unexpected packaged command: %#v", cmd) + } + if strings.Join(cmd.Env, "\n") != strings.Join(env, "\n") { + t.Fatal("environment changed") + } + if err := cmd.Run(); err != nil { + t.Fatal(err) + } +} + +func TestDaemonOverrideValidation(t *testing.T) { + dir := t.TempDir() + nonExecutable := filepath.Join(dir, "not-executable") + if err := os.WriteFile(nonExecutable, nil, 0600); err != nil { + t.Fatal(err) + } + for _, path := range []string{"relative-daemon", dir, nonExecutable, filepath.Join(dir, "missing")} { + if _, err := daemonCommand(path, "unused", nil); err == nil { + t.Errorf("accepted invalid daemon %q", path) + } + } +} + +func TestDevelopmentDaemonCommand(t *testing.T) { + cmd, err := daemonCommand("", "/source/albedo", []string{"fixture=value"}) + if err != nil { + t.Fatal(err) + } + if strings.Join(cmd.Args, " ") != "gleam run" || cmd.Dir != "/source/albedo" { + t.Fatalf("unexpected development command: %#v", cmd) + } +} + +func TestDaemonEnvironment(t *testing.T) { + for _, key := range []string{"ALBEDO_API_KEY", "ALBEDO_MODEL", "ALBEDO_BASE_URL", "ALBEDO_PROTOCOL"} { + t.Setenv(key, "do-not-inherit") + } + t.Setenv("ALBEDO_DAEMON", "/nix/store/fixture/bin/daemon") + env := strings.Join(buildDaemonEnv("/tmp/home", "token"), "\n") + if strings.Contains(env, "do-not-inherit") || !strings.Contains(env, "ALBEDO_HOME=/tmp/home") || !strings.Contains(env, "ALBEDO_TOKEN=token") { + t.Fatal("incorrect daemon environment") + } +} diff --git a/cli/internal/daemon/progress.go b/cli/internal/daemon/progress.go new file mode 100644 index 000000000..69875d3bc --- /dev/null +++ b/cli/internal/daemon/progress.go @@ -0,0 +1,319 @@ +package daemon + +import ( + "math" + "regexp" + "strconv" + "strings" +) + +var ( + whitespaceRegex = regexp.MustCompile(`\s+`) + assignStrRegex = regexp.MustCompile(`^([a-zA-Z_]\w*)\s*=\s*[rR]?['"]([^'"]*)['"]`) + assignPathRegex = regexp.MustCompile(`^([a-zA-Z_]\w*)\s*=\s*(?:pathlib\.)?Path\(\s*[rR]?['"]([^'"]*)['"]\s*\)`) + pathMethodRegex = regexp.MustCompile(`(?:(?:pathlib\.)?Path\(\s*[rR]?['"]([^'"]*)['"]\s*\)|([a-zA-Z_]\w*))\.(write_text|write_bytes|read_text|read_bytes|open)\(\s*([^)]*)\)`) + funcCallRegex = regexp.MustCompile(`\b(edit|read|sh|open)\(\s*([^)]*)\)`) + argExtractRegex = regexp.MustCompile(`(?:(?:path|file|command)\s*=\s*)?(?:[rR]?['"]([^'"]*)['"]|([a-zA-Z_]\w*))`) + modeRegex = regexp.MustCompile(`['"]([rwaxbt+]+)['"]`) +) + +func cleanLabel(s string) string { + s = sanitizeControlRunes(s) + s = whitespaceRegex.ReplaceAllString(s, " ") + s = strings.TrimSpace(s) + if len(s) > 300 { + return s[:300] + } + return s +} + +func ParsePythonIntent(code string) *ToolIntent { + bindings := make(map[string]string) + var intents []ToolIntent + + lines := strings.Split(code, "\n") + for _, rawLine := range lines { + line := strings.TrimSpace(rawLine) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + + if m := assignStrRegex.FindStringSubmatch(line); m != nil { + bindings[m[1]] = m[2] + continue + } + + if m := assignPathRegex.FindStringSubmatch(line); m != nil { + bindings[m[1]] = m[2] + continue + } + + if m := pathMethodRegex.FindStringSubmatch(line); m != nil { + pLit := m[1] + pVar := m[2] + method := m[3] + args := m[4] + + target := pLit + if target == "" && pVar != "" { + target = bindings[pVar] + } + + if target != "" { + label := cleanLabel(target) + switch method { + case "write_text", "write_bytes": + intents = append(intents, ToolIntent{Kind: "write", Target: label}) + case "read_text", "read_bytes": + intents = append(intents, ToolIntent{Kind: "read", Target: label}) + case "open": + mode := "r" + if mm := modeRegex.FindStringSubmatch(args); mm != nil { + mode = mm[1] + } + kind := "read" + if strings.ContainsAny(mode, "wax+") { + kind = "write" + } + intents = append(intents, ToolIntent{Kind: kind, Target: label}) + } + continue + } + } + + if m := funcCallRegex.FindStringSubmatch(line); m != nil { + fnName := m[1] + args := m[2] + + if am := argExtractRegex.FindStringSubmatch(args); am != nil { + litVal := am[1] + varVal := am[2] + target := litVal + if target == "" && varVal != "" { + target = bindings[varVal] + } + + if target != "" { + label := cleanLabel(target) + switch fnName { + case "edit": + intents = append(intents, ToolIntent{Kind: "edit", Target: label}) + case "read": + intents = append(intents, ToolIntent{Kind: "read", Target: label}) + case "sh": + intents = append(intents, ToolIntent{Kind: "run", Target: label}) + case "open": + mode := "r" + if mm := modeRegex.FindStringSubmatch(args); mm != nil { + mode = mm[1] + } + kind := "read" + if strings.ContainsAny(mode, "wax+") { + kind = "write" + } + intents = append(intents, ToolIntent{Kind: kind, Target: label}) + } + } + } + } + } + + if len(intents) == 0 { + return nil + } + return &intents[len(intents)-1] +} + +func ExtractPartialJSONCode(s string) string { + idx := strings.Index(s, `"code"`) + if idx == -1 { + return "" + } + colon := strings.Index(s[idx+6:], ":") + if colon == -1 { + return "" + } + colon += idx + 6 + + quote := strings.Index(s[colon+1:], `"`) + if quote == -1 { + return "" + } + start := colon + 1 + quote + 1 + + var sb strings.Builder + bytes := []byte(s[start:]) + i := 0 + for i < len(bytes) { + b := bytes[i] + if b == '"' { + break + } + if b == '\\' { + if i+1 >= len(bytes) { + break + } + nxt := bytes[i+1] + switch nxt { + case 'n': + sb.WriteByte('\n') + i += 2 + case 'r': + sb.WriteByte('\r') + i += 2 + case 't': + sb.WriteByte('\t') + i += 2 + case '"': + sb.WriteByte('"') + i += 2 + case '\\': + sb.WriteByte('\\') + i += 2 + case 'u': + if i+5 < len(bytes) { + hexVal := string(bytes[i+2 : i+6]) + if cp, err := strconv.ParseInt(hexVal, 16, 32); err == nil { + sb.WriteRune(rune(cp)) + i += 6 + continue + } + } + sb.WriteByte(nxt) + i += 2 + default: + sb.WriteByte(nxt) + i += 2 + } + } else { + sb.WriteByte(b) + i++ + } + } + return sb.String() +} + +type ToolCallAssembly struct { + ID string + Function struct { + Name string + Arguments string + } +} + +type ToolProgressReporter struct { + publish func(*ToolProgress) error + previous *ToolProgress + raw string + code string +} + +func NewToolProgressReporter(publish func(*ToolProgress) error) *ToolProgressReporter { + return &ToolProgressReporter{ + publish: publish, + } +} + +func (r *ToolProgressReporter) Reset() { + r.raw = "" + r.code = "" +} + +func (r *ToolProgressReporter) Report(call *ToolCallAssembly, phase string) error { + if call == nil { + if r.previous != nil { + err := r.publish(nil) + r.previous = nil + r.Reset() + return err + } + r.Reset() + return nil + } + + name := cleanLabel(call.Function.Name) + if len(name) > 100 { + name = name[:100] + } + if name == "" { + return nil + } + + callID := call.ID + if len(callID) > 200 { + callID = callID[:200] + } + + args := call.Function.Arguments + sameCall := r.previous != nil && r.previous.CallID == callID && r.previous.Name == name + continued := sameCall && strings.HasPrefix(args, r.raw) + + if !continued { + r.Reset() + } + + if name == "python" && len(args) > len(r.raw) { + r.code = ExtractPartialJSONCode(args) + r.raw = args + } + + var intent *ToolIntent + if continued && r.previous != nil { + intent = r.previous.Intent + } + if parsed := ParsePythonIntent(r.code); parsed != nil { + intent = parsed + } + + var preview *ToolCodePreview + if phase == "generating" && len(r.code) > 0 { + codeRunes := []rune(r.code) + offset := int(math.Max(0, float64(len(codeRunes)-512))) + text := sanitizeControlRunes(string(codeRunes[offset:])) + preview = &ToolCodePreview{ + Offset: offset, + Text: text, + } + } + + next := &ToolProgress{ + CallID: callID, + Name: name, + Phase: phase, + Intent: intent, + Code: preview, + } + + if !toolProgressEqual(next, r.previous) { + if err := r.publish(next); err != nil { + return err + } + r.previous = next + } + return nil +} + +func toolProgressEqual(a, b *ToolProgress) bool { + if a == nil && b == nil { + return true + } + if a == nil || b == nil { + return false + } + if a.CallID != b.CallID || a.Name != b.Name || a.Phase != b.Phase { + return false + } + if (a.Intent == nil) != (b.Intent == nil) { + return false + } + if a.Intent != nil && *a.Intent != *b.Intent { + return false + } + if (a.Code == nil) != (b.Code == nil) { + return false + } + if a.Code != nil && *a.Code != *b.Code { + return false + } + return true +} diff --git a/cli/internal/daemon/progress_test.go b/cli/internal/daemon/progress_test.go new file mode 100644 index 000000000..6b6c48892 --- /dev/null +++ b/cli/internal/daemon/progress_test.go @@ -0,0 +1,64 @@ +package daemon + +import ( + "testing" +) + +func TestParsePythonIntent(t *testing.T) { + cases := []struct { + code string + expected *ToolIntent + }{ + { + code: "from pathlib import Path\nPath('demo.py').write_text('hello')", + expected: &ToolIntent{Kind: "write", Target: "demo.py"}, + }, + { + code: "read('second.py')", + expected: &ToolIntent{Kind: "read", Target: "second.py"}, + }, + { + code: "edit('main.go')", + expected: &ToolIntent{Kind: "edit", Target: "main.go"}, + }, + { + code: "sh('ls -la')", + expected: &ToolIntent{Kind: "run", Target: "ls -la"}, + }, + { + code: "open('test.txt', 'r')", + expected: &ToolIntent{Kind: "read", Target: "test.txt"}, + }, + { + code: "open('test.txt', 'w')", + expected: &ToolIntent{Kind: "write", Target: "test.txt"}, + }, + { + code: "p = Path('data.csv')\np.write_text('a,b,c')", + expected: &ToolIntent{Kind: "write", Target: "data.csv"}, + }, + } + + for _, tc := range cases { + intent := ParsePythonIntent(tc.code) + if intent == nil { + t.Fatalf("expected intent for %s, got nil", tc.code) + } + if intent.Kind != tc.expected.Kind || intent.Target != tc.expected.Target { + t.Fatalf("for %s: expected %+v, got %+v", tc.code, tc.expected, intent) + } + } +} + +func TestExtractPartialJSONCode(t *testing.T) { + code1 := ExtractPartialJSONCode(`{"code":"read('second.`) + if code1 != "read('second." { + t.Fatalf("expected read('second., got %s", code1) + } + + code2 := ExtractPartialJSONCode(`{"code":"from pathlib import Path\nPath('demo.py').write_text('hello')"}`) + expected2 := "from pathlib import Path\nPath('demo.py').write_text('hello')" + if code2 != expected2 { + t.Fatalf("expected %s, got %s", expected2, code2) + } +} diff --git a/cli/internal/daemon/sessions_test.go b/cli/internal/daemon/sessions_test.go new file mode 100644 index 000000000..b1b612dcf --- /dev/null +++ b/cli/internal/daemon/sessions_test.go @@ -0,0 +1,78 @@ +package daemon + +import ( + "strings" + "testing" + "time" +) + +func TestAssistantAge(t *testing.T) { + now := time.Unix(2000000000, 0) + + cases := []struct { + offset int64 + label string + }{ + {0, "just now"}, + {59, "just now"}, + {60, "1m ago"}, + {3599, "59m ago"}, + {3600, "1h ago"}, + {86400, "1d ago"}, + {-10, "just now"}, + } + + for _, tc := range cases { + ts := now.Unix() - tc.offset + if res := AssistantAge(&ts, now); res != tc.label { + t.Errorf("for offset %d: expected %s, got %s", tc.offset, tc.label, res) + } + } + + if res := AssistantAge(nil, now); res != "time unknown" { + t.Errorf("expected time unknown for nil, got %s", res) + } +} + +func TestSessionListing(t *testing.T) { + now := time.Unix(2000000000, 0) + ts := now.Unix() - 120 + + session := Session{ + ID: "deadbeef1234", + Title: "fix the session picker", + Workspace: "/tmp", + Model: "fixture", + Provider: "fixture", + Protocol: "responses", + LastAssistantAt: &ts, + } + + listing := SessionListing([]Session{session}, now) + expected := "fix the session picker [deadbeef]\n last assistant: 2m ago" + if listing != expected { + t.Fatalf("expected:\n%s\ngot:\n%s", expected, listing) + } + + if res := SessionListing(nil, now); res != "no sessions" { + t.Fatalf("expected no sessions, got %s", res) + } + + nilTsSession := session + nilTsSession.LastAssistantAt = nil + if !strings.Contains(SessionListing([]Session{nilTsSession}, now), "time unknown") { + t.Fatalf("expected time unknown in listing") + } + + dirtySession := session + dirtySession.Title = "line\nbreak\x1b" + if strings.Contains(SessionListing([]Session{dirtySession}, now), "\x1b") { + t.Fatalf("expected escape code to be stripped") + } + + unicodeSession := session + unicodeSession.Title = "fix 👩‍💻 unicode" + if !strings.Contains(SessionListing([]Session{unicodeSession}, now), "fix 👩‍💻 unicode") { + t.Fatalf("expected unicode to be preserved") + } +} diff --git a/cli/internal/tui/app.go b/cli/internal/tui/app.go new file mode 100644 index 000000000..7195d02b1 --- /dev/null +++ b/cli/internal/tui/app.go @@ -0,0 +1,1036 @@ +package tui + +import ( + "albedo/cli/internal/config" + "albedo/cli/internal/daemon" + "context" + "encoding/json" + "errors" + "fmt" + "net/url" + "strings" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +type AppState int + +const ( + AppStateChat AppState = iota + AppStateSessionPicker + AppStateModelPicker + AppStateExtensionPicker + AppStateTreePicker + AppStateContextInspector + AppStatePageView + AppStateLogin +) + +type sessionsLoadedMsg struct { + Sessions []daemon.Session + Err error + Gen int +} + +type sessionCreatedMsg struct { + Session daemon.Session + Err error + Gen int +} + +type commandCatalogLoadedMsg struct { + Commands []daemon.SessionCommand + Err error + Gen int +} + +type modelChangedMsg struct { + Model string + Provider string + Protocol string + Err error + Gen int +} + +type commandExecutedMsg struct { + Name string + Message string + Err error + Gen int +} + +type ChatWorkspaceChangedMsg struct { + SessionID string + Workspace string +} + +type glancesPolledMsg struct { + Glances []PageGlance + Err error + Gen int +} + +type glancePollTickMsg struct { + SessionID string + Gen int +} + +type profilesLoadedMsg struct { + Profiles config.Profiles + Provider string + Err error + Gen int +} + +type AppModel struct { + Conn *daemon.Connection + Profiles config.Profiles + State AppState + ActiveSession *daemon.Session + Sessions []daemon.Session + Workspace string + Width int + Height int + Notice string + Error string + CommandCatalog []daemon.SessionCommand + Glances []PageGlance + ExtensionRevision int + GlanceRevision int + StandaloneLogin bool + BrowserOpener func(url string) + + // Independent generation counters for concurrent async tasks + SessionGen int + CatalogGen int + ModelGen int + CommandGen int + GlanceGen int + ProfileGen int + + // Sub-models + Chat ChatModel + SessionPicker PickerModel + ModelPicker ModelPickerModel + ExtensionPicker ExtensionPickerModel + TreePicker TreePickerModel + ContextInspector ContextInspectorModel + PageView PageViewModel + Login LoginModel +} + +func (m AppModel) newChatClient(sessionID string) *daemon.ChatClient { + var baseURL, token string + if m.Conn != nil { + baseURL = fmt.Sprintf("http://127.0.0.1:%d", m.Conn.Port) + token = m.Conn.Token + } + return daemon.NewChatClient(daemon.ChatClientOptions{ + BaseURL: baseURL, + Token: token, + AgentID: sessionID, + }) +} + +func NewAppModel(conn *daemon.Connection, profiles config.Profiles, initialSession *daemon.Session, workspace string, needsLogin bool) AppModel { + m := AppModel{ + Conn: conn, + Profiles: profiles, + ActiveSession: initialSession, + Workspace: workspace, + } + + if needsLogin { + m.State = AppStateLogin + m.Login = NewLoginModel(conn, "") + m.Login.BrowserOpener = m.BrowserOpener + } else if initialSession != nil { + m.State = AppStateChat + m.Chat = NewChatModel(initialSession, m.newChatClient(initialSession.ID)) + } else { + m.State = AppStateSessionPicker + m.SessionPicker = NewPickerModel("albedo sessions", []PickerItem{ + {ID: "new", Label: "new coding session", Detail: workspace}, + {ID: "login", Label: "/login", Detail: "add or select an api provider"}, + }, true, "new") + } + + return m +} + +func (m AppModel) Init() tea.Cmd { + m.Login.BrowserOpener = m.BrowserOpener + switch m.State { + case AppStateChat: + return tea.Batch( + m.Chat.Init(), + m.loadCommandCatalogCmd(m.CatalogGen), + mouseModeCmd(AppStateChat), + ) + case AppStateLogin: + m.Login.BrowserOpener = m.BrowserOpener + if !m.StandaloneLogin && m.ActiveSession == nil { + return tea.Batch(m.Login.Init(), m.loadSessionsCmd(m.SessionGen)) + } + return m.Login.Init() + case AppStateSessionPicker: + return tea.Batch( + m.SessionPicker.Init(), + m.loadSessionsCmd(m.SessionGen), + ) + } + return nil +} + +func (m AppModel) loadSessionsCmd(gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil { + return sessionsLoadedMsg{Err: errors.New("daemon connection unavailable"), Gen: gen} + } + sessions, err := daemon.Request[[]daemon.Session](context.Background(), m.Conn, "/sessions", nil) + return sessionsLoadedMsg{Sessions: sessions, Err: err, Gen: gen} + } +} + +func (m AppModel) createSessionCmd(gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil { + return sessionCreatedMsg{Err: errors.New("daemon connection unavailable"), Gen: gen} + } + body := map[string]string{"workspace": m.Workspace} + s, err := daemon.Request[daemon.Session](context.Background(), m.Conn, "/sessions", body) + return sessionCreatedMsg{Session: s, Err: err, Gen: gen} + } +} + +func (m AppModel) loadProfilesCmd(provider string, gen int) tea.Cmd { + return func() tea.Msg { + home := config.HomeDir() + p, err := config.LoadProfiles(home) + return profilesLoadedMsg{ + Profiles: p, + Provider: provider, + Err: err, + Gen: gen, + } + } +} + +func (m AppModel) loadCommandCatalogCmd(gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil || m.ActiveSession == nil { + return commandCatalogLoadedMsg{Gen: gen} + } + + health, err := daemon.Request[struct { + Capabilities []string `json:"capabilities"` + }](context.Background(), m.Conn, "/health", nil) + if err == nil { + hasCap := false + for _, c := range health.Capabilities { + if c == "session_commands" { + hasCap = true + break + } + } + if !hasCap { + return commandCatalogLoadedMsg{ + Err: errors.New("daemon upgrade needed for the command menu; when ready, run albedo daemon --stop, then albedo (this clears python variables)"), + Gen: gen, + } + } + } + + path := fmt.Sprintf("/sessions/%s/commands", url.PathEscape(m.ActiveSession.ID)) + raw, err := daemon.Request[any](context.Background(), m.Conn, path, nil) + if err != nil { + return commandCatalogLoadedMsg{Err: err, Gen: gen} + } + + rawBytes, err := json.Marshal(raw) + if err != nil { + return commandCatalogLoadedMsg{Err: err, Gen: gen} + } + + cmds, err := daemon.ParseCommandCatalog(rawBytes) + return commandCatalogLoadedMsg{Commands: cmds, Err: err, Gen: gen} + } +} + +func (m AppModel) changeModelCmd(model, provider string, gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil || m.ActiveSession == nil { + return modelChangedMsg{Err: errors.New("no active session or connection"), Gen: gen} + } + + if provider != "" && provider != m.ActiveSession.Provider { + health, err := daemon.Request[struct { + Capabilities []string `json:"capabilities"` + }](context.Background(), m.Conn, "/health", nil) + if err == nil { + hasCap := false + for _, c := range health.Capabilities { + if c == "session_provider" { + hasCap = true + break + } + } + if !hasCap { + return modelChangedMsg{ + Err: errors.New("daemon upgrade needed to switch providers; when ready, run albedo daemon --stop, then albedo (this clears python variables)"), + Gen: gen, + } + } + } + } + + path := fmt.Sprintf("/sessions/%s/commands", url.PathEscape(m.ActiveSession.ID)) + args := map[string]string{"model": model} + if provider != "" { + args["provider"] = provider + } + body := map[string]any{ + "name": "/model", + "args": args, + } + + res, err := daemon.Request[map[string]any](context.Background(), m.Conn, path, body) + if err != nil { + return modelChangedMsg{Err: err, Gen: gen} + } + + newModel := model + newProvider := provider + var newProtocol string + + if r, ok := res["result"].(map[string]any); ok { + if mVal, ok := r["model"].(string); ok && mVal != "" { + newModel = mVal + } + if pVal, ok := r["provider"].(string); ok && pVal != "" { + newProvider = pVal + } + if protoVal, ok := r["protocol"].(string); ok && protoVal != "" { + newProtocol = protoVal + } + } + + return modelChangedMsg{ + Model: newModel, + Provider: newProvider, + Protocol: newProtocol, + Gen: gen, + } + } +} + +func (m AppModel) executeCommandCmd(name, args string, gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil || m.ActiveSession == nil { + return commandExecutedMsg{Name: name, Err: errors.New("no active session or connection"), Gen: gen} + } + + path := fmt.Sprintf("/sessions/%s/commands", url.PathEscape(m.ActiveSession.ID)) + body := map[string]any{ + "name": name, + } + if args != "" { + body["arguments"] = args + } + + res, err := daemon.Request[map[string]any](context.Background(), m.Conn, path, body) + if err != nil { + return commandExecutedMsg{Name: name, Err: err, Gen: gen} + } + + msg := fmt.Sprintf("%s done", name) + if res != nil { + if r, ok := res["result"].(map[string]any); ok { + if mStr, ok := r["message"].(string); ok && mStr != "" { + msg = mStr + } + } else if mStr, ok := res["message"].(string); ok && mStr != "" { + msg = mStr + } + } + + return commandExecutedMsg{Name: name, Message: msg, Gen: gen} + } +} + +func (m AppModel) hasPageCommands() bool { + for _, cmd := range m.CommandCatalog { + if cmd.Page != nil && *cmd.Page { + return true + } + } + return false +} + +func glancePollTickCmd(sessionID string, gen int) tea.Cmd { + return tea.Tick(3*time.Second, func(t time.Time) tea.Msg { + return glancePollTickMsg{ + SessionID: sessionID, + Gen: gen, + } + }) +} + +func (m AppModel) pollGlancesCmd(gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil || m.ActiveSession == nil { + return glancesPolledMsg{Gen: gen} + } + + var pageCmds []string + for _, cmd := range m.CommandCatalog { + if cmd.Page != nil && *cmd.Page { + pageCmds = append(pageCmds, cmd.Name) + } + } + if len(pageCmds) == 0 { + return glancesPolledMsg{Gen: gen} + } + + var glances []PageGlance + for _, name := range pageCmds { + path := fmt.Sprintf("/sessions/%s/commands", url.PathEscape(m.ActiveSession.ID)) + body := map[string]any{"name": name, "args": map[string]string{}} + res, err := daemon.Request[map[string]any](context.Background(), m.Conn, path, body) + if err == nil { + var target any = res + if r, ok := res["result"]; ok && r != nil { + target = r + } + doc, err := parsePageDocument(target) + if err == nil && doc != nil && doc.Glance != nil { + glances = append(glances, *doc.Glance) + } + } + } + + return glancesPolledMsg{Glances: glances, Gen: gen} + } +} + +func (m *AppModel) updateSessionPickerItems() { + var items []PickerItem + items = append(items, PickerItem{ID: "new", Label: "new coding session", Detail: m.Workspace}) + items = append(items, PickerItem{ID: "login", Label: "/login", Detail: "add or select an api provider"}) + + // Prepend active session if not in list + listed := m.Sessions + if m.ActiveSession != nil { + found := false + for _, s := range m.Sessions { + if s.ID == m.ActiveSession.ID { + found = true + break + } + } + if !found { + listed = append([]daemon.Session{*m.ActiveSession}, m.Sessions...) + } + } + + for _, s := range listed { + label := strings.TrimSpace(s.Title) + if label == "" { + label = "new session" + } + detail := fmt.Sprintf("%s · %s", s.Model, s.Workspace) + items = append(items, PickerItem{ + ID: s.ID, + Label: label, + Detail: detail, + }) + } + + curSel := "new" + if len(listed) > 0 { + curSel = listed[0].ID + } + if m.ActiveSession != nil { + curSel = m.ActiveSession.ID + } + m.SessionPicker = NewPickerModel("albedo sessions", items, true, curSel) + m.SessionPicker.SetSize(m.Width, m.Height) +} + +func mouseModeCmd(state AppState) tea.Cmd { + return func() tea.Msg { + if state == AppStateChat { + return tea.EnableMouseCellMotion() + } + return tea.DisableMouse() + } +} + +func (m *AppModel) syncChatNotices() { + if m.ActiveSession == nil || m.Chat.History == nil { + return + } + if m.Chat.ExternalNotice != m.Notice || m.Chat.ExternalError != m.Error { + m.Chat.ExternalNotice = m.Notice + m.Chat.ExternalError = m.Error + m.Chat.SetSize(m.Width, m.Height) + } +} + +func (m AppModel) Update(msg tea.Msg) (result tea.Model, command tea.Cmd) { + previous := m.State + defer func() { + updated, ok := result.(AppModel) + if !ok { + return + } + updated.syncChatNotices() + result = updated + if updated.State != previous { + command = tea.Batch(command, mouseModeCmd(updated.State)) + } + }() + // First: forward chat lifecycle messages even while a modal is open. + switch streamMsg := msg.(type) { + case ChatClearCopyStatusMsg: + var cmd tea.Cmd + if m.ActiveSession != nil && streamMsg.SessionID == m.ActiveSession.ID { + m.Chat, cmd = m.Chat.Update(msg) + } + return m, cmd + case ChatStatusPollMsg: + var cmd tea.Cmd + if m.ActiveSession != nil && streamMsg.SessionID == m.ActiveSession.ID { + m.Chat, cmd = m.Chat.Update(msg) + } + return m, cmd + case ChatStatusMsg: + var cmd tea.Cmd + if m.ActiveSession != nil && streamMsg.SessionID == m.ActiveSession.ID { + m.Chat, cmd = m.Chat.Update(msg) + } + return m, cmd + case ChatStreamEventMsg: + var cmd tea.Cmd + if m.ActiveSession != nil && streamMsg.SessionID == m.ActiveSession.ID { + m.Chat, cmd = m.Chat.Update(msg) + } + return m, cmd + case ChatStreamClosedMsg: + var cmd tea.Cmd + if m.ActiveSession != nil && streamMsg.SessionID == m.ActiveSession.ID { + m.Chat, cmd = m.Chat.Update(msg) + } + return m, cmd + case ChatTurnSentMsg: + var cmd tea.Cmd + if m.ActiveSession != nil && streamMsg.SessionID == m.ActiveSession.ID { + m.Chat, cmd = m.Chat.Update(msg) + } + return m, cmd + case ChatInterruptMsg: + var cmd tea.Cmd + if m.ActiveSession != nil && streamMsg.SessionID == m.ActiveSession.ID { + m.Chat, cmd = m.Chat.Update(msg) + } + return m, cmd + case ClipboardImagePastedMsg: + var cmd tea.Cmd + if m.ActiveSession != nil && streamMsg.SessionID == m.ActiveSession.ID { + m.Chat, cmd = m.Chat.Update(msg) + } + return m, 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.Login.SetSize(msg.Width, msg.Height) + return m, nil + + case ChatWorkspaceChangedMsg: + if m.ActiveSession != nil && (msg.SessionID == "" || msg.SessionID == m.ActiveSession.ID) { + m.ActiveSession.Workspace = msg.Workspace + m.Workspace = msg.Workspace + for i := range m.Sessions { + if m.Sessions[i].ID == m.ActiveSession.ID { + m.Sessions[i].Workspace = msg.Workspace + break + } + } + } + return m, nil + + case sessionsLoadedMsg: + if msg.Gen != m.SessionGen { + return m, nil + } + if msg.Err != nil { + m.Error = "Error: " + msg.Err.Error() + } else { + m.Sessions = msg.Sessions + m.Error = "" + m.updateSessionPickerItems() + } + return m, nil + + case sessionCreatedMsg: + if msg.Gen != m.SessionGen { + return m, nil + } + if msg.Err != nil { + m.Error = "Error: " + msg.Err.Error() + return m, nil + } + m.Chat.Close() + s := msg.Session + m.ActiveSession = &s + m.Sessions = append([]daemon.Session{s}, m.Sessions...) + m.Chat = NewChatModel(&s, m.newChatClient(s.ID)) + m.Chat.SetSize(m.Width, m.Height) + m.State = AppStateChat + m.Error = "" + m.CatalogGen++ + return m, tea.Batch( + m.Chat.Init(), + m.loadCommandCatalogCmd(m.CatalogGen), + ) + + case commandCatalogLoadedMsg: + if msg.Gen != m.CatalogGen { + return m, nil + } + if msg.Err != nil { + if strings.Contains(msg.Err.Error(), "daemon upgrade") { + m.Error = "Error: " + msg.Err.Error() + if m.ActiveSession != nil { + } + } + } else { + m.CommandCatalog = msg.Commands + m.Chat.CommandMenu.Catalog = msg.Commands + m.GlanceGen++ + var cmds []tea.Cmd + cmds = append(cmds, m.pollGlancesCmd(m.GlanceGen)) + if m.ActiveSession != nil && m.hasPageCommands() { + cmds = append(cmds, glancePollTickCmd(m.ActiveSession.ID, m.GlanceGen)) + } + return m, tea.Batch(cmds...) + } + return m, nil + + case glancePollTickMsg: + if m.ActiveSession == nil || msg.SessionID != m.ActiveSession.ID || msg.Gen != m.GlanceGen { + return m, nil // Obsolete tick dropped + } + if !m.hasPageCommands() { + return m, nil + } + return m, tea.Batch( + m.pollGlancesCmd(m.GlanceGen), + glancePollTickCmd(m.ActiveSession.ID, m.GlanceGen), + ) + + case modelChangedMsg: + if msg.Gen != m.ModelGen { + return m, nil + } + if msg.Err != nil { + if m.State == AppStateModelPicker { + m.ModelPicker.Saving = false + m.ModelPicker.Error = msg.Err.Error() + } else { + m.Error = "Error: " + msg.Err.Error() + } + return m, nil + } + if m.ActiveSession != nil { + if msg.Model != "" { + m.ActiveSession.Model = msg.Model + m.Chat.Model = msg.Model + } + if msg.Provider != "" { + m.ActiveSession.Provider = msg.Provider + m.Chat.Provider = msg.Provider + } + if msg.Protocol != "" { + m.ActiveSession.Protocol = msg.Protocol + } + } + m.ModelPicker.Saving = false + m.State = AppStateChat + m.Error = "" + return m, nil + + case commandExecutedMsg: + if msg.Gen != m.CommandGen { + return m, nil + } + if msg.Err != nil { + m.Error = "Error: " + msg.Err.Error() + m.Notice = "" + } else { + m.Notice = msg.Message + m.Error = "" + } + return m, nil + + case glancesPolledMsg: + if msg.Gen != m.GlanceGen { + return m, nil + } + if msg.Err == nil { + m.Glances = msg.Glances + m.Chat.Glances = msg.Glances + m.Chat.SetSize(m.Width, m.Height) + } + return m, nil + + case profilesLoadedMsg: + if msg.Gen != m.ProfileGen { + return m, nil + } + if msg.Err != nil { + m.Error = "Error: " + msg.Err.Error() + } else { + m.Profiles = msg.Profiles + m.Error = "" + m.Notice = fmt.Sprintf("%s selected for new sessions", msg.Provider) + if m.ActiveSession != nil { + m.Notice += fmt.Sprintf("; use /model to switch this session from %s", m.ActiveSession.Provider) + } + } + if m.StandaloneLogin { + return m, tea.Quit + } + if msg.Err == nil && m.ActiveSession == nil && len(m.Sessions) == 0 { + m.SessionGen++ + return m, m.createSessionCmd(m.SessionGen) + } + if m.ActiveSession == nil { + m.State = AppStateSessionPicker + m.updateSessionPickerItems() + return m, nil + } + m.State = AppStateChat + return m, nil + + case ChatQuitMsg: + m.Chat.Close() + return m, tea.Quit + + case ChatBackToSessionsMsg: + m.State = AppStateSessionPicker + m.SessionGen++ + m.GlanceGen++ // Cancels pending glance poll ticks + return m, tea.Batch( + m.SessionPicker.Init(), + m.loadSessionsCmd(m.SessionGen), + ) + + case ChatNewSessionMsg: + m.SessionGen++ + return m, m.createSessionCmd(m.SessionGen) + + case ChatOpenModelPickerMsg: + if m.ActiveSession != nil { + m.ModelPicker = NewModelPickerModel(m.Conn, m.Profiles, m.ActiveSession.Model, m.ActiveSession.Provider) + m.ModelPicker.SetSize(m.Width, m.Height) + m.State = AppStateModelPicker + return m, m.ModelPicker.Init() + } + + case ModelPickerSelectMsg: + m.ModelPicker.Saving = true + m.ModelPicker.Error = "" + m.ModelGen++ + return m, m.changeModelCmd(msg.Model, msg.Provider, m.ModelGen) + + case ModelPickerCancelMsg: + m.State = AppStateChat + return m, nil + + case ChatOpenExtensionPickerMsg: + if m.ActiveSession != nil { + m.ExtensionPicker = NewExtensionPickerModel(m.Conn, m.ActiveSession.ID) + m.ExtensionPicker.SetSize(m.Width, m.Height) + m.State = AppStateExtensionPicker + return m, m.ExtensionPicker.Init() + } + + case ExtensionPickerDoneMsg: + m.State = AppStateChat + return m, nil + + case ExtensionPickerChangedMsg: + m.ExtensionRevision++ + m.CatalogGen++ + return m, m.loadCommandCatalogCmd(m.CatalogGen) + + case ChatOpenTreePickerMsg: + if m.ActiveSession != nil { + m.TreePicker = NewTreePickerModel(m.Conn, m.ActiveSession.ID) + m.TreePicker.SetSize(m.Width, m.Height) + m.State = AppStateTreePicker + return m, m.TreePicker.Init() + } + + case TreeCancelMsg: + m.State = AppStateChat + return m, nil + + case TreeForkSuccessMsg: + m.Chat.Close() + branch := msg.Session + m.ActiveSession = &branch + m.Sessions = append([]daemon.Session{branch}, m.Sessions...) + m.Chat = NewChatModel(&branch, m.newChatClient(branch.ID)) + m.Chat.SetSize(m.Width, m.Height) + m.State = AppStateChat + m.CatalogGen++ + return m, tea.Batch( + m.Chat.Init(), + m.loadCommandCatalogCmd(m.CatalogGen), + ) + + case ChatOpenContextInspectorMsg: + if m.ActiveSession != nil { + m.ContextInspector = NewContextInspectorModel(m.Conn, m.ActiveSession.ID) + m.ContextInspector.SetSize(m.Width, m.Height) + m.State = AppStateContextInspector + return m, m.ContextInspector.Init() + } + + case ContextDoneMsg: + m.State = AppStateChat + return m, nil + + case ChatOpenPageMsg: + if m.ActiveSession != nil { + m.PageView = NewPageViewModel(m.Conn, m.ActiveSession.ID, msg.Command) + m.PageView.SetSize(m.Width, m.Height) + m.State = AppStatePageView + return m, m.PageView.Init() + } + + case PageCancelMsg: + m.State = AppStateChat + return m, nil + + case PageViewChangedMsg: + m.GlanceRevision++ + m.GlanceGen++ + var cmds []tea.Cmd + cmds = append(cmds, m.pollGlancesCmd(m.GlanceGen)) + if m.ActiveSession != nil && m.hasPageCommands() { + cmds = append(cmds, glancePollTickCmd(m.ActiveSession.ID, m.GlanceGen)) + } + return m, tea.Batch(cmds...) + + case ChatOpenLoginMsg: + m.Login = NewLoginModel(m.Conn, msg.Name) + m.Login.BrowserOpener = m.BrowserOpener + m.Login.SetSize(m.Width, m.Height) + m.State = AppStateLogin + return m, m.Login.Init() + + case LoginCancelMsg: + m.ProfileGen++ + if m.StandaloneLogin { + return m, tea.Quit + } + if m.ActiveSession != nil { + m.State = AppStateChat + return m, nil + } + m.State = AppStateSessionPicker + m.updateSessionPickerItems() + m.SessionGen++ + return m, tea.Batch(m.SessionPicker.Init(), m.loadSessionsCmd(m.SessionGen)) + + case LoginDoneMsg: + if m.State != AppStateLogin { + return m, nil + } + m.ProfileGen++ + return m, m.loadProfilesCmd(msg.Name, m.ProfileGen) + + case ChatExecuteCommandMsg: + switch { + case msg.Name == "/login": + m.Login = NewLoginModel(m.Conn, msg.Args) + m.Login.BrowserOpener = m.BrowserOpener + m.Login.SetSize(m.Width, m.Height) + m.State = AppStateLogin + return m, m.Login.Init() + case msg.Name == "/model" && msg.Args != "": + m.ModelGen++ + return m, m.changeModelCmd(msg.Args, "", m.ModelGen) + case msg.Name == "/model": + if m.ActiveSession != nil { + m.ModelPicker = NewModelPickerModel(m.Conn, m.Profiles, m.ActiveSession.Model, m.ActiveSession.Provider) + m.ModelPicker.SetSize(m.Width, m.Height) + m.State = AppStateModelPicker + return m, m.ModelPicker.Init() + } + case msg.Name == "/new": + m.SessionGen++ + return m, m.createSessionCmd(m.SessionGen) + case msg.Name == "/sessions" || msg.Name == "/agents" || msg.Name == "/a": + m.State = AppStateSessionPicker + m.SessionGen++ + m.GlanceGen++ + return m, tea.Batch(m.SessionPicker.Init(), m.loadSessionsCmd(m.SessionGen)) + case msg.Name == "/extensions" || msg.Name == "/plugins": + if m.ActiveSession != nil { + m.ExtensionPicker = NewExtensionPickerModel(m.Conn, m.ActiveSession.ID) + m.ExtensionPicker.SetSize(m.Width, m.Height) + m.State = AppStateExtensionPicker + return m, m.ExtensionPicker.Init() + } + case msg.Name == "/tree": + if m.ActiveSession != nil { + m.TreePicker = NewTreePickerModel(m.Conn, m.ActiveSession.ID) + m.TreePicker.SetSize(m.Width, m.Height) + m.State = AppStateTreePicker + return m, m.TreePicker.Init() + } + case msg.Name == "/context": + if m.ActiveSession != nil { + m.ContextInspector = NewContextInspectorModel(m.Conn, m.ActiveSession.ID) + m.ContextInspector.SetSize(m.Width, m.Height) + m.State = AppStateContextInspector + return m, m.ContextInspector.Init() + } + default: + m.CommandGen++ + return m, m.executeCommandCmd(msg.Name, msg.Args, m.CommandGen) + } + + case PickerSelectMsg: + if m.State == AppStateSessionPicker { + if msg.ID == "new" { + m.SessionGen++ + return m, m.createSessionCmd(m.SessionGen) + } + if msg.ID == "login" { + m.Login = NewLoginModel(m.Conn, "") + m.Login.BrowserOpener = m.BrowserOpener + m.Login.SetSize(m.Width, m.Height) + m.State = AppStateLogin + return m, m.Login.Init() + } + // The active session may not yet appear in the daemon's recent list. + listed := m.Sessions + if m.ActiveSession != nil { + found := false + for _, s := range listed { + if s.ID == m.ActiveSession.ID { + found = true + break + } + } + if !found { + listed = append([]daemon.Session{*m.ActiveSession}, listed...) + } + } + for _, s := range listed { + if s.ID == msg.ID { + m.Chat.Close() + session := s + m.ActiveSession = &session + m.Chat = NewChatModel(&session, m.newChatClient(session.ID)) + m.Chat.SetSize(m.Width, m.Height) + m.State = AppStateChat + m.CatalogGen++ + m.GlanceGen++ + return m, tea.Batch( + m.Chat.Init(), + m.loadCommandCatalogCmd(m.CatalogGen), + ) + } + } + } + + case PickerCancelMsg: + if m.State == AppStateSessionPicker { + if m.ActiveSession != nil { + m.State = AppStateChat + return m, nil + } + return m, tea.Quit + } + } + + // Route to active state model + var cmd tea.Cmd + switch m.State { + case AppStateChat: + m.Chat, cmd = m.Chat.Update(msg) + 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 AppStateLogin: + m.Login, cmd = m.Login.Update(msg) + } + + return m, cmd +} + +func (m AppModel) View() string { + var prefix strings.Builder + if m.State == AppStateSessionPicker { + if m.Notice != "" { + prefix.WriteString(DefaultStyles.Dim.Render(m.Notice) + "\n") + } + if m.Error != "" { + prefix.WriteString(DefaultStyles.Error.Foreground(lipgloss.Color("1")).Render(m.Error) + "\n") + } + } + + var content string + switch m.State { + case AppStateChat: + content = m.Chat.View() + case AppStateSessionPicker: + content = m.SessionPicker.View() + case AppStateModelPicker: + content = m.ModelPicker.View() + case AppStateExtensionPicker: + content = m.ExtensionPicker.View() + case AppStateTreePicker: + content = m.TreePicker.View() + case AppStateContextInspector: + content = m.ContextInspector.View() + case AppStatePageView: + content = m.PageView.View() + case AppStateLogin: + content = m.Login.View() + } + + if prefix.Len() > 0 { + return prefix.String() + content + } + return content +} diff --git a/cli/internal/tui/bounded_history.go b/cli/internal/tui/bounded_history.go new file mode 100644 index 000000000..71e47c48b --- /dev/null +++ b/cli/internal/tui/bounded_history.go @@ -0,0 +1,166 @@ +package tui + +import ( + "albedo/cli/internal/daemon" + "encoding/json" + "fmt" +) + +type EntryKind string + +const ( + EntryUser EntryKind = "user" + EntryAssistant EntryKind = "assistant" + EntryThinking EntryKind = "thinking" + EntryTool EntryKind = "tool" + EntryNote EntryKind = "note" + EntryError EntryKind = "error" + EntryCompacted EntryKind = "compacted" +) + +type HistoryEntry struct { + Kind EntryKind + Speaker string + Text string + Timestamp int64 + ClientID string + ToolName string + ToolArgs map[string]any + ToolResult string + ToolTrace *daemon.ToolTrace + Evicted int + SizeBytes int64 +} + +func (e *HistoryEntry) ComputeSize() int64 { + size := int64(len(e.Speaker) + len(e.Text) + len(e.ClientID) + len(e.ToolName) + len(e.ToolResult) + 64) + if e.ToolArgs != nil { + for k, v := range e.ToolArgs { + size += int64(len(k) + 16) + switch val := v.(type) { + case string: + size += int64(len(val)) + default: + data, _ := json.Marshal(val) + size += int64(len(data)) + } + } + } + if e.ToolTrace != nil { + for _, act := range e.ToolTrace.Activities { + size += int64(len(act.Kind) + len(act.Target) + 16) + } + for _, ch := range e.ToolTrace.Changes { + size += int64(len(ch.Path) + len(ch.Kind) + len(ch.Diff) + len(ch.Reason) + 32) + } + } + e.SizeBytes = size + return size +} + +type BoundedHistory struct { + MaxEntries int + MaxBytes int64 + entries []HistoryEntry + totalBytes int64 + evictedEntries int + evictedBytes int64 +} + +func NewBoundedHistory(maxEntries int, maxBytes int64) *BoundedHistory { + if maxEntries <= 0 { + maxEntries = 500 + } + if maxBytes <= 0 { + maxBytes = 2 * 1024 * 1024 // 2MB default + } + return &BoundedHistory{ + MaxEntries: maxEntries, + MaxBytes: maxBytes, + entries: make([]HistoryEntry, 0, 128), + } +} + +func (h *BoundedHistory) Len() int { + return len(h.entries) +} + +func (h *BoundedHistory) TotalBytes() int64 { + return h.totalBytes +} + +func (h *BoundedHistory) EvictedCount() int { + return h.evictedEntries +} + +func (h *BoundedHistory) EvictedBytes() int64 { + return h.evictedBytes +} + +func (h *BoundedHistory) Entries() []HistoryEntry { + return h.entries +} + +func (h *BoundedHistory) TruncationNotice() string { + if h.evictedEntries > 0 { + return fmt.Sprintf("[%d older messages truncated (%d KB); durable history is in daemon]", h.evictedEntries, h.evictedBytes/1024) + } + return "" +} + +func (h *BoundedHistory) enforceBounds() { + for len(h.entries) > 0 && (len(h.entries) > h.MaxEntries || h.totalBytes > h.MaxBytes) { + removed := h.entries[0] + h.entries[0] = HistoryEntry{} // Explicitly zero out evicted slot to drop GC references + h.entries = h.entries[1:] + h.totalBytes -= removed.SizeBytes + if h.totalBytes < 0 { + h.totalBytes = 0 + } + h.evictedEntries++ + h.evictedBytes += removed.SizeBytes + } +} + +func (h *BoundedHistory) Append(entry HistoryEntry) { + entry.ComputeSize() + h.entries = append(h.entries, entry) + h.totalBytes += entry.SizeBytes + h.enforceBounds() +} + +func (h *BoundedHistory) AppendToLast(chunk string) { + if len(h.entries) == 0 { + h.Append(HistoryEntry{Kind: EntryAssistant, Text: chunk}) + return + } + lastIdx := len(h.entries) - 1 + oldSize := h.entries[lastIdx].SizeBytes + h.entries[lastIdx].Text += chunk + newSize := h.entries[lastIdx].ComputeSize() + h.totalBytes += (newSize - oldSize) + h.enforceBounds() +} + +func (h *BoundedHistory) ReplaceLast(entry HistoryEntry) { + if len(h.entries) == 0 { + h.Append(entry) + return + } + lastIdx := len(h.entries) - 1 + oldSize := h.entries[lastIdx].SizeBytes + entry.ComputeSize() + h.entries[lastIdx] = entry + h.totalBytes += (entry.SizeBytes - oldSize) + h.enforceBounds() +} + +func (h *BoundedHistory) Clear() { + for i := range h.entries { + h.entries[i] = HistoryEntry{} // Zero out all slots to prevent retaining pointers + } + h.entries = h.entries[:0] + h.totalBytes = 0 + h.evictedEntries = 0 + h.evictedBytes = 0 +} diff --git a/cli/internal/tui/bounded_history_test.go b/cli/internal/tui/bounded_history_test.go new file mode 100644 index 000000000..2520e912a --- /dev/null +++ b/cli/internal/tui/bounded_history_test.go @@ -0,0 +1,85 @@ +package tui + +import ( + "strings" + "testing" +) + +func TestBoundedHistory_EntryCountLimit(t *testing.T) { + h := NewBoundedHistory(5, 1000000) + for i := 0; i < 10; i++ { + h.Append(HistoryEntry{ + Kind: EntryUser, + Text: "message", + }) + } + + if h.Len() != 5 { + t.Fatalf("expected 5 entries, got %d", h.Len()) + } + if h.EvictedCount() != 5 { + t.Fatalf("expected 5 evicted, got %d", h.EvictedCount()) + } + notice := h.TruncationNotice() + if !strings.Contains(notice, "5 older messages truncated") { + t.Fatalf("expected truncation notice, got: %s", notice) + } +} + +func TestBoundedHistory_ByteLimit(t *testing.T) { + h := NewBoundedHistory(100, 500) + for i := 0; i < 10; i++ { + h.Append(HistoryEntry{ + Kind: EntryAssistant, + Text: strings.Repeat("x", 100), + }) + } + + if h.TotalBytes() > 500 { + t.Fatalf("expected total bytes <= 500, got %d", h.TotalBytes()) + } + if h.EvictedCount() == 0 { + t.Fatalf("expected evictions due to byte limit") + } + if h.EvictedBytes() == 0 { + t.Fatalf("expected non-zero evicted bytes") + } +} + +func TestBoundedHistory_ToolArgsComputeSize(t *testing.T) { + entryWithoutArgs := HistoryEntry{ + Kind: EntryTool, + ToolName: "test_tool", + } + size1 := entryWithoutArgs.ComputeSize() + + entryWithArgs := HistoryEntry{ + Kind: EntryTool, + ToolName: "test_tool", + ToolArgs: map[string]any{ + "command": "echo hello", + "count": 42, + }, + } + size2 := entryWithArgs.ComputeSize() + + if size2 <= size1 { + t.Fatalf("expected size with ToolArgs (%d) to be greater than without (%d)", size2, size1) + } +} + +func TestBoundedHistory_ClearZeroesSlots(t *testing.T) { + h := NewBoundedHistory(10, 100000) + h.Append(HistoryEntry{Kind: EntryUser, Text: "sample text"}) + if h.Len() != 1 { + t.Fatalf("expected 1 entry") + } + + h.Clear() + if h.Len() != 0 { + t.Fatalf("expected 0 entries after clear") + } + if h.TotalBytes() != 0 { + t.Fatalf("expected 0 total bytes after clear, got %d", h.TotalBytes()) + } +} diff --git a/cli/internal/tui/chat.go b/cli/internal/tui/chat.go new file mode 100644 index 000000000..ab86c50f7 --- /dev/null +++ b/cli/internal/tui/chat.go @@ -0,0 +1,1792 @@ +package tui + +import ( + "albedo/cli/internal/daemon" + "context" + "errors" + "fmt" + "regexp" + "strconv" + "strings" + "time" + + "github.com/charmbracelet/bubbles/cursor" + "github.com/charmbracelet/bubbles/textarea" + "github.com/charmbracelet/bubbles/textinput" + "github.com/charmbracelet/bubbles/viewport" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" +) + +type ChatBackToSessionsMsg struct{} +type ChatQuitMsg struct{} +type ChatNewSessionMsg struct{} +type ChatOpenModelPickerMsg struct{} +type ChatOpenExtensionPickerMsg struct{} +type ChatOpenTreePickerMsg struct{} +type ChatOpenContextInspectorMsg struct{} +type ChatOpenPageMsg struct { + Command string +} +type ChatOpenLoginMsg struct { + Name string +} +type ChatExecuteCommandMsg struct { + Name string + Args string +} + +type ChatStreamEventMsg struct { + SessionID string + Generation int64 + Event daemon.StreamEvent +} + +type ChatProgressTickMsg struct { + SessionID string + Generation int64 +} + +type ChatClearCopyStatusMsg struct { + SessionID string + Generation int64 + Revision uint64 +} + +type ChatStatusMsg struct { + SessionID string + Generation int64 + Revision uint64 + Status *daemon.AgentStatus + Err error +} + +type ChatStatusPollMsg struct { + SessionID string + Generation int64 +} + +type ChatStreamClosedMsg struct { + SessionID string + Generation int64 +} + +type ChatTurnSentMsg struct { + SessionID string + Generation int64 + Prompt string + Image *daemon.ImageAttachment + OK bool + Queued bool + Err error +} + +type ChatInterruptMsg struct { + SessionID string + Generation int64 + Interrupted bool + Err error +} + +type ChatReplaceWorkspaceMsg struct { + SessionID string + Generation int64 + Workspace string + Err error +} + +type WorkspaceRecoveryState struct { + Missing string + Replacement string + Prompt string + Image *daemon.ImageAttachment + Saving bool + Error string +} + +type ActiveStreamKind string + +const ( + StreamKindNone ActiveStreamKind = "" + StreamKindText ActiveStreamKind = "text" + StreamKindThinking ActiveStreamKind = "thinking" +) + +type PendingUserTurn struct { + Text string + Image *daemon.ImageAttachment + Queued bool +} + +const ( + MaxLiveStreamBytes = 64 * 1024 + MaxPendingUsers = 10 + MaxSettledLines = 1000 + MaxSettledLinesBytes = 256 * 1024 + fnvOffset64 = 14695981039346656037 + fnvPrime64 = 1099511628211 +) + +func fnv1a(h uint64, s string) uint64 { + for i := 0; i < len(s); i++ { + h ^= uint64(s[i]) + h *= fnvPrime64 + } + return h +} + +var sgrCode = regexp.MustCompile(`\x1b\[[0-9;]*m`) + +func wrapOrChunkLine(line string, width int) []string { + if width <= 0 { + width = 80 + } + // Match wrap-ansi's hard:true, trim:false word placement: a separator + // consumes a cell before deciding whether the next word fits. + words := strings.Split(line, " ") + rows := []string{""} + used := 0 + for i, word := range words { + if i > 0 { + if used >= width { + rows = append(rows, "") + used = 0 + } + rows[len(rows)-1] += " " + used++ + } + wordWidth := ansi.StringWidth(word) + if wordWidth > width { + remaining := width - used + breaksHere := 1 + (wordWidth-remaining-1)/width + breaksNext := (wordWidth - 1) / width + if breaksNext < breaksHere { + rows = append(rows, "") + used = 0 + } + wrapped := strings.Split(ansi.Hardwrap(rows[len(rows)-1]+word, width, true), "\n") + rows[len(rows)-1] = wrapped[0] + rows = append(rows, wrapped[1:]...) + used = ansi.StringWidth(rows[len(rows)-1]) + continue + } + if used+wordWidth > width && used > 0 && wordWidth > 0 { + rows = append(rows, "") + used = 0 + } + rows[len(rows)-1] += word + used += wordWidth + } + // Every viewport row can be rendered alone after a history scroll. Reopen + // styles that cross a physical wrap, as wrap-ansi does for the TS rows. + style := "" + for i, row := range rows { + if style != "" { + rows[i] = style + row + } + for _, code := range sgrCode.FindAllString(row, -1) { + if code == "\x1b[0m" || code == "\x1b[m" { + style = "" + } else { + style += code + } + } + if style != "" && i < len(rows)-1 { + rows[i] += "\x1b[0m" + } + } + return rows +} + +type ChatModel struct { + SessionID string + Generation int64 + AgentName string + Workspace string + Model string + Provider string + Client *daemon.ChatClient + History *BoundedHistory + Renderer TranscriptRenderer + Viewport viewport.Model + TextArea textarea.Model + CommandMenu CommandMenuModel + Flags DisplayFlags + Follow bool + TurnFailed bool + Stopping bool + Stopped bool + Status daemon.AgentStatus + Usage *daemon.Usage + Glances []PageGlance + AttachedImage *daemon.ImageAttachment + Notice string + CopyStatus string + copyStatusRevision uint64 + ErrorNotice string + ExternalNotice string + ExternalError string + ToolProgressText string + Progress *daemon.ToolProgress + ProgressFrame int + animationActive bool + statusRevision uint64 + Width int + Height int + Styles Styles + + settledLines []string + settledLinesBytes int64 + droppedSettledLines int + + scrollOffset int + + activeKind ActiveStreamKind + activeText string + + streamedHash uint64 + streamedLen int64 + + pendingUsers []PendingUserTurn + isSending bool + interruptDeferred bool + + WorkspaceRecovery *WorkspaceRecoveryState + RecoveryInput textinput.Model + + dragAnchor *Point + dragHead Point + + streamCtx context.Context + streamCancel context.CancelFunc + eventChan chan daemon.StreamEvent +} + +func NewChatModel(session *daemon.Session, client *daemon.ChatClient) ChatModel { + ta := textarea.New() + ta.Placeholder = "" + ta.Prompt = "› " + ta.ShowLineNumbers = false + ta.KeyMap.InsertNewline.SetKeys("enter", "ctrl+m", "alt+enter", "shift+enter") + ta.SetHeight(1) + ta.FocusedStyle.Prompt = DefaultStyles.PromptBright + ta.FocusedStyle.CursorLine = lipgloss.NewStyle() + ta.Cursor.Style = lipgloss.NewStyle().Reverse(true) + ta.Cursor.SetMode(cursor.CursorStatic) + ta.Focus() + + vp := viewport.New(80, 20) + vp.YPosition = 0 + + bh := NewBoundedHistory(500, 2*1024*1024) + + ctx, cancel := context.WithCancel(context.Background()) + gen := time.Now().UnixNano() + + m := ChatModel{ + SessionID: session.ID, + Generation: gen, + AgentName: "albedo", + Workspace: session.Workspace, + Model: session.Model, + Provider: session.Provider, + Client: client, + History: bh, + Renderer: NewTranscriptRenderer(), + Viewport: vp, + TextArea: ta, + CommandMenu: NewCommandMenuModel(), + Flags: DisplayFlags{ + Thinking: true, + Tools: false, + Compaction: false, + }, + Follow: true, + Styles: DefaultStyles, + streamedHash: fnvOffset64, + streamCtx: ctx, + streamCancel: cancel, + eventChan: make(chan daemon.StreamEvent, 16), + } + + return m +} + +func (m *ChatModel) Close() { + if m.streamCancel != nil { + m.streamCancel() + } +} + +func (m ChatModel) chromeRows() int { + menu := min(4, len(m.CommandMenu.Matches(m.TextArea.Value()))) + if m.WorkspaceRecovery != nil { + menu = 2 + } + notice := 0 + if m.Notice != "" || m.ErrorNotice != "" || m.ExternalNotice != "" || m.ExternalError != "" { + notice = 1 + } + return menu + notice + min(3, len(m.pendingUsers)) +} + +func (m *ChatModel) SetSize(width, height int) { + if m == nil || m.History == nil { + return + } + if width <= 0 { + width = 1 + } + if height <= 0 { + height = 1 + } + + m.Width = width + m.Height = height + + padding := m.padding() + available := max(1, width-2*padding) + chromeRows := m.chromeRows() + transcriptWidth := available + if m.sidebarWidth() > 0 { + transcriptWidth -= m.sidebarWidth() + 2 + } + m.Viewport.Width = transcriptWidth + m.Renderer.HeadingWidth = transcriptWidth + m.Renderer.BodyWidth = min(100, available) + m.Viewport.Height = max(1, height-6-chromeRows) + m.TextArea.SetHeight(1) + m.TextArea.SetWidth(max(1, available-2)) + m.RecoveryInput.Width = max(1, available-16) + + m.rebuildSettledLines() + m.refreshViewportContent() +} + +func (m *ChatModel) rebuildSettledLines() { + m.settledLines = nil + m.settledLinesBytes = 0 + entries := m.History.Entries() + for _, entry := range entries { + block := m.Renderer.RenderEntry(entry, m.Flags, m.Viewport.Width) + if len(m.settledLines) > 0 { + m.appendSettledLines([]string{""}, false) + } + m.appendSettledLines(strings.Split(block, "\n"), entry.Kind == EntryUser || entry.Kind == EntryAssistant) + } +} + +func (m *ChatModel) appendSettledLines(rawLines []string, heading bool) { + for i, line := range rawLines { + width := m.Renderer.BodyWidth + if heading && i == 0 { + width = m.Viewport.Width + } + for _, chunk := range wrapOrChunkLine(line, width) { + m.settledLines = append(m.settledLines, chunk) + m.settledLinesBytes += int64(len(chunk)) + } + } + m.trimSettledLines() +} + +func (m *ChatModel) trimSettledLines() { + dropped := 0 + for len(m.settledLines) > MaxSettledLines || m.settledLinesBytes > MaxSettledLinesBytes { + if len(m.settledLines) == 0 { + break + } + removed := m.settledLines[0] + m.settledLinesBytes -= int64(len(removed)) + m.settledLines[0] = "" + m.settledLines = m.settledLines[1:] + dropped++ + } + + if dropped > 0 { + m.droppedSettledLines += dropped + m.scrollOffset = max(0, m.scrollOffset-dropped) + fresh := make([]string, len(m.settledLines)) + for i := range m.settledLines { + fresh[i] = strings.Clone(m.settledLines[i]) + m.settledLines[i] = "" + } + m.settledLines = fresh + } +} + +func (m *ChatModel) appendSettledEntry(entry HistoryEntry) { + m.History.Append(entry) + block := m.Renderer.RenderEntry(entry, m.Flags, m.Viewport.Width) + if len(m.settledLines) > 0 { + m.appendSettledLines([]string{""}, false) + } + m.appendSettledLines(strings.Split(block, "\n"), entry.Kind == EntryUser || entry.Kind == EntryAssistant) +} + +func (m *ChatModel) settleActiveStream() { + if m.activeKind == StreamKindNone || m.activeText == "" { + m.activeKind = StreamKindNone + m.activeText = "" + return + } + var kind EntryKind = EntryAssistant + if m.activeKind == StreamKindThinking { + kind = EntryThinking + } + entry := HistoryEntry{ + Kind: kind, + Speaker: m.AgentName, + Text: m.activeText, + Timestamp: time.Now().UnixMilli(), + } + m.appendSettledEntry(entry) + m.activeKind = StreamKindNone + m.activeText = "" +} + +func (m *ChatModel) refreshViewportContent() { + if m.Viewport.Height != max(1, m.Height-6-m.chromeRows()) { + m.SetSize(m.Width, m.Height) + return + } + var allLines []string + + if notice := m.History.TruncationNotice(); notice != "" { + allLines = append(allLines, m.Styles.Warning.Render(notice), "") + } + if m.droppedSettledLines > 0 { + allLines = append(allLines, m.Styles.Faint.Render(fmt.Sprintf("[%d scrollback lines truncated]", m.droppedSettledLines)), "") + } + + allLines = append(allLines, m.settledLines...) + + if m.activeKind != StreamKindNone && m.activeText != "" { + if len(m.settledLines) > 0 { + allLines = append(allLines, "") + } + var kind EntryKind = EntryAssistant + if m.activeKind == StreamKindThinking { + kind = EntryThinking + } + activeEntry := HistoryEntry{Kind: kind, Speaker: m.AgentName, Text: m.activeText} + activeBlock := m.Renderer.RenderEntry(activeEntry, m.Flags, m.Viewport.Width) + for i, line := range strings.Split(activeBlock, "\n") { + width := m.Renderer.BodyWidth + if i == 0 { + width = m.Viewport.Width + } + allLines = append(allLines, wrapOrChunkLine(line, width)...) + } + } + + if m.ToolProgressText != "" { + if len(allLines) > 0 { + allLines = append(allLines, "") + } + allLines = append(allLines, m.renderProgress()) + } + + totalLines := len(allLines) + vpHeight := max(1, m.Viewport.Height) + maxScroll := max(0, totalLines-vpHeight) + + var visibleSlice []string + if m.Follow { + m.scrollOffset = maxScroll + visibleSlice = allLines[maxScroll:totalLines] + m.Viewport.SetContent(strings.Join(visibleSlice, "\n")) + m.Viewport.GotoBottom() + } else { + m.scrollOffset = max(0, min(m.scrollOffset, maxScroll)) + end := min(totalLines, m.scrollOffset+vpHeight) + if m.scrollOffset < end { + visibleSlice = allLines[m.scrollOffset:end] + } + m.Viewport.SetContent(strings.Join(visibleSlice, "\n")) + m.Viewport.GotoTop() + } +} + +func (m ChatModel) animating() bool { + return m.isSending || len(m.pendingUsers) > 0 || m.Stopping || m.Progress != nil || m.Status.Running && !m.Status.Idle +} + +func (m *ChatModel) startAnimation() tea.Cmd { + if m.animationActive || !m.animating() { + return nil + } + m.animationActive = true + return m.progressTickCmd() +} + +func (m ChatModel) progressTickCmd() tea.Cmd { + id, generation := m.SessionID, m.Generation + return tea.Tick(80*time.Millisecond, func(time.Time) tea.Msg { return ChatProgressTickMsg{SessionID: id, Generation: generation} }) +} + +func (m ChatModel) waitForNextEvent() tea.Cmd { + sessID := m.SessionID + gen := m.Generation + ch := m.eventChan + ctx := m.streamCtx + + return func() tea.Msg { + select { + case evt, ok := <-ch: + if !ok { + return ChatStreamClosedMsg{SessionID: sessID, Generation: gen} + } + return ChatStreamEventMsg{SessionID: sessID, Generation: gen, Event: evt} + case <-ctx.Done(): + return ChatStreamClosedMsg{SessionID: sessID, Generation: gen} + } + } +} + +func (m ChatModel) startStreamSubscription() tea.Cmd { + if m.Client == nil { + return nil + } + client := m.Client + ctx := m.streamCtx + ch := m.eventChan + + go func() { + defer close(ch) + for { + if ctx.Err() != nil { + return + } + err := client.Stream(ctx, nil, func(evt daemon.StreamEvent) error { + select { + case ch <- evt: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }) + if ctx.Err() != nil { + return + } + _ = err + select { + case <-ctx.Done(): + return + case <-time.After(500 * time.Millisecond): + } + } + }() + + return m.waitForNextEvent() +} + +func (m ChatModel) clearCopyStatusCmd() tea.Cmd { + id, generation, revision := m.SessionID, m.Generation, m.copyStatusRevision + return tea.Tick(3*time.Second, func(time.Time) tea.Msg { + return ChatClearCopyStatusMsg{SessionID: id, Generation: generation, Revision: revision} + }) +} + +func (m ChatModel) statusCmd() tea.Cmd { + if m.Client == nil { + return nil + } + client, ctx, id, generation, revision := m.Client, m.streamCtx, m.SessionID, m.Generation, m.statusRevision + return func() tea.Msg { + value, err := client.GetStatus(ctx) + return ChatStatusMsg{SessionID: id, Generation: generation, Revision: revision, Status: value, Err: err} + } +} + +func (m ChatModel) statusPollCmd() tea.Cmd { + id, generation := m.SessionID, m.Generation + return tea.Tick(750*time.Millisecond, func(time.Time) tea.Msg { return ChatStatusPollMsg{SessionID: id, Generation: generation} }) +} + +func (m ChatModel) Init() tea.Cmd { + return tea.Batch(m.startStreamSubscription(), m.statusCmd()) +} + +func (m ChatModel) Update(msg tea.Msg) (ChatModel, tea.Cmd) { + var cmds []tea.Cmd + + switch msg := msg.(type) { + case tea.KeyMsg: + if m.WorkspaceRecovery != nil { + if msg.Type == tea.KeyEsc { + prompt := m.WorkspaceRecovery.Prompt + img := m.WorkspaceRecovery.Image + m.WorkspaceRecovery = nil + if m.TextArea.Value() == "" { + m.TextArea.SetValue(prompt) + } + if m.AttachedImage == nil && img != nil { + m.AttachedImage = img + } + m.refreshViewportContent() + return m, nil + } + if msg.Type == tea.KeyEnter { + m.RecoveryInput.CursorStart() + replacement := strings.TrimSpace(m.RecoveryInput.Value()) + if replacement != "" && !m.WorkspaceRecovery.Saving { + m.WorkspaceRecovery.Saving = true + m.WorkspaceRecovery.Replacement = replacement + m.WorkspaceRecovery.Error = "" + return m, m.replaceWorkspaceCmd(replacement) + } + return m, nil + } + var riCmd tea.Cmd + m.RecoveryInput, riCmd = m.RecoveryInput.Update(msg) + return m, riCmd + } + + if msg.Type == tea.KeyLeft && m.TextArea.Value() == "" { + return m, func() tea.Msg { return ChatBackToSessionsMsg{} } + } + + if msg.Type == tea.KeyCtrlC { + if m.streamCancel != nil { + m.streamCancel() + } + return m, func() tea.Msg { return ChatQuitMsg{} } + } + if msg.Type == tea.KeyCtrlN { + return m, func() tea.Msg { return ChatNewSessionMsg{} } + } + if msg.Type == tea.KeyEsc && m.dragAnchor != nil { + m.dragAnchor = nil + return m, nil + } + + inputVal := m.TextArea.Value() + consumed := m.CommandMenu.OnKey( + msg, + inputVal, + func(replacement string) { + m.TextArea.SetValue(replacement) + }, + func(commandName string) { + m.handleSubmittedCommand(commandName, &cmds) + }, + ) + if consumed { + m.SetSize(m.Width, m.Height) + return m, tea.Batch(cmds...) + } + + if msg.Type == tea.KeyEsc { + if m.AttachedImage != nil { + m.AttachedImage = nil + m.CopyStatus = "image removed" + return m, nil + } + if m.isSending { + m.interruptDeferred = true + m.Stopping = true + return m, nil + } + if m.Status.Running || len(m.pendingUsers) > 0 { + m.Stopping = true + if m.Client != nil { + cmds = append(cmds, m.interruptCmd()) + } + return m, tea.Batch(cmds...) + } + } + + if msg.Type == tea.KeyCtrlV { + return m, PasteClipboardImageCmd(m.SessionID, m.Generation) + } + + if msg.Type == tea.KeyPgUp { + m.Follow = false + m.scrollOffset = max(0, m.scrollOffset-m.Viewport.Height) + m.refreshViewportContent() + return m, nil + } + if msg.Type == tea.KeyPgDown { + m.scrollOffset += m.Viewport.Height + m.refreshViewportContent() + if m.scrollOffset >= max(0, len(m.settledLines)-m.Viewport.Height) { + m.Follow = true + } + return m, nil + } + if msg.Type == tea.KeyUp { + if m.TextArea.Line() == 0 { + m.Follow = false + m.scrollOffset = max(0, m.scrollOffset-1) + m.refreshViewportContent() + return m, nil + } + } + if msg.Type == tea.KeyDown { + if m.TextArea.Line() >= m.TextArea.LineCount()-1 { + m.scrollOffset += 1 + m.refreshViewportContent() + if m.scrollOffset >= max(0, len(m.settledLines)-m.Viewport.Height) { + m.Follow = true + } + return m, nil + } + } + if msg.Type == tea.KeyCtrlHome { + m.Follow = false + m.scrollOffset = 0 + m.refreshViewportContent() + return m, nil + } + if msg.Type == tea.KeyCtrlEnd { + m.Follow = true + m.refreshViewportContent() + return m, nil + } + + if msg.Type == tea.KeyCtrlJ { + m.Flags.Diffs = !m.Flags.Diffs + m.rebuildSettledLines() + m.refreshViewportContent() + return m, nil + } + if msg.Type == tea.KeyCtrlK { + m.Flags.Compaction = !m.Flags.Compaction + m.rebuildSettledLines() + m.refreshViewportContent() + return m, nil + } + + if msg.Type == tea.KeyEnter && !msg.Alt { + trimmed := strings.TrimSpace(m.TextArea.Value()) + if trimmed != "" { + m.TextArea.Reset() + m.submitInput(trimmed, &cmds) + return m, tea.Batch(cmds...) + } + return m, nil + } + + case tea.MouseMsg: + firstRow := 2 + if m.Notice != "" || m.ErrorNotice != "" || m.ExternalNotice != "" || m.ExternalError != "" { + firstRow++ + } + point := func() Point { + return Point{Row: max(0, min(m.Viewport.Height-1, msg.Y-firstRow)), Col: max(0, min(m.Viewport.Width, msg.X-m.padding()))} + } + if msg.Action == tea.MouseActionRelease && m.dragAnchor != nil { + m.dragHead = point() + sel := Selection{Anchor: *m.dragAnchor, Head: m.dragHead} + m.dragAnchor = nil + if !sel.IsEmpty() { + lines := strings.Split(m.Viewport.View(), "\n") + if text := SelectedText(lines, sel); text != "" { + if err := CopyText(text); err != nil { + m.CopyStatus = "copy failed: " + err.Error() + } else { + m.CopyStatus = "copied" + } + m.copyStatusRevision++ + return m, m.clearCopyStatusCmd() + } + } + return m, nil + } + if msg.Action == tea.MouseActionMotion && m.dragAnchor != nil { + m.dragHead = point() + return m, nil + } + if msg.Action == tea.MouseActionPress && msg.Button == tea.MouseButtonLeft { + if msg.Y < firstRow || msg.Y >= firstRow+m.Viewport.Height { + return m, nil + } + pt := point() + m.dragAnchor = &pt + m.dragHead = pt + return m, nil + } + switch msg.Button { + case tea.MouseButtonWheelUp: + m.Follow = false + m.scrollOffset = max(0, m.scrollOffset-3) + m.refreshViewportContent() + return m, nil + case tea.MouseButtonWheelDown: + m.scrollOffset += 3 + m.refreshViewportContent() + if m.scrollOffset >= max(0, len(m.settledLines)-m.Viewport.Height) { + m.Follow = true + } + return m, nil + } + + case ClipboardImagePastedMsg: + if msg.SessionID != m.SessionID || msg.Generation != m.Generation { + return m, nil + } + if msg.Err == nil && msg.Image != nil { + m.AttachedImage = msg.Image + m.CopyStatus = "" + m.refreshViewportContent() + } else if msg.Err != nil && msg.Err.Error() != "no image in clipboard" { + m.ErrorNotice = fmt.Sprintf("image paste failed: %v", msg.Err) + } + return m, nil + + case ChatStatusPollMsg: + if msg.SessionID != m.SessionID || msg.Generation != m.Generation { + return m, nil + } + return m, m.statusCmd() + + case ChatStatusMsg: + if msg.SessionID != m.SessionID || msg.Generation != m.Generation { + return m, nil + } + if msg.Err == nil && msg.Status != nil && msg.Revision == m.statusRevision { + m.Status = *msg.Status + if !m.Status.Running || m.Status.Idle { + m.Progress = nil + m.ToolProgressText = "" + m.settleActiveStream() + m.refreshViewportContent() + } + } + return m, tea.Batch(m.startAnimation(), m.statusPollCmd()) + + case ChatStreamEventMsg: + if msg.SessionID != m.SessionID || msg.Generation != m.Generation { + return m, nil + } + m.statusRevision++ + m.handleStreamEvent(msg.Event) + m.refreshViewportContent() + return m, tea.Batch(m.waitForNextEvent(), m.startAnimation()) + + case ChatClearCopyStatusMsg: + if msg.SessionID == m.SessionID && msg.Generation == m.Generation && msg.Revision == m.copyStatusRevision { + m.CopyStatus = "" + } + return m, nil + + case ChatProgressTickMsg: + if msg.SessionID != m.SessionID || msg.Generation != m.Generation { + return m, nil + } + if !m.animating() { + m.animationActive = false + return m, nil + } + m.ProgressFrame++ + m.refreshViewportContent() + return m, m.progressTickCmd() + + case ChatStreamClosedMsg: + if msg.SessionID != m.SessionID || msg.Generation != m.Generation { + return m, nil + } + return m, nil + + case ChatTurnSentMsg: + if msg.SessionID != m.SessionID || msg.Generation != m.Generation { + return m, nil + } + m.isSending = false + if msg.Err != nil { + m.interruptDeferred = false + var wsErr *daemon.WorkspaceMissingError + if errors.As(msg.Err, &wsErr) { + m.Status.Running = false + m.Status.Idle = true + if len(m.pendingUsers) > 0 { + m.pendingUsers = m.pendingUsers[1:] + } + if m.TextArea.Value() == "" { + m.TextArea.SetValue(msg.Prompt) + } + if m.AttachedImage == nil && msg.Image != nil { + m.AttachedImage = msg.Image + } + ti := textinput.New() + ti.SetValue(wsErr.Workspace) + ti.Focus() + ti.Prompt = "new workspace › " + ti.PromptStyle = m.Styles.PromptBright + ti.Cursor.Style = lipgloss.NewStyle().Reverse(true) + ti.Cursor.SetMode(cursor.CursorStatic) + m.RecoveryInput = ti + m.WorkspaceRecovery = &WorkspaceRecoveryState{ + Missing: wsErr.Workspace, + Replacement: wsErr.Workspace, + Prompt: msg.Prompt, + Image: msg.Image, + } + m.refreshViewportContent() + return m, nil + } + + m.ErrorNotice = fmt.Sprintf("send failed: %v", msg.Err) + if msg.Queued { + m.appendSettledEntry(HistoryEntry{Kind: EntryError, Text: "message not queued: " + msg.Err.Error()}) + } else { + m.appendSettledEntry(HistoryEntry{Kind: EntryError, Text: msg.Err.Error()}) + } + if m.TextArea.Value() == "" { + m.TextArea.SetValue(msg.Prompt) + } + if m.AttachedImage == nil && msg.Image != nil { + m.AttachedImage = msg.Image + } + if len(m.pendingUsers) > 0 { + m.pendingUsers = m.pendingUsers[1:] + } + m.refreshViewportContent() + return m, nil + } + + if msg.Queued { + for i := range m.pendingUsers { + if m.pendingUsers[i].Text == msg.Prompt && !m.pendingUsers[i].Queued { + m.pendingUsers[i].Queued = true + break + } + } + } + + // If user pressed Esc while this send was in flight, dispatch interrupt now that send is accepted + if m.interruptDeferred { + m.interruptDeferred = false + m.Stopping = true + if m.Client != nil { + cmds = append(cmds, m.interruptCmd()) + } + } + return m, tea.Batch(cmds...) + + case ChatReplaceWorkspaceMsg: + if msg.SessionID != m.SessionID || msg.Generation != m.Generation { + return m, nil + } + if m.WorkspaceRecovery == nil { + return m, nil + } + if msg.Err != nil { + m.WorkspaceRecovery.Saving = false + m.WorkspaceRecovery.Error = msg.Err.Error() + return m, nil + } + m.Workspace = msg.Workspace + prompt := m.WorkspaceRecovery.Prompt + img := m.WorkspaceRecovery.Image + m.WorkspaceRecovery = nil + + cmds = append(cmds, func() tea.Msg { + return ChatWorkspaceChangedMsg{Workspace: msg.Workspace} + }) + // Set original image BEFORE submitInput so submitInput captures and sends it! + if img != nil && m.AttachedImage == nil { + m.AttachedImage = img + } + m.TextArea.Reset() + m.submitInput(prompt, &cmds) + return m, tea.Batch(cmds...) + + case ChatInterruptMsg: + if msg.SessionID != m.SessionID || msg.Generation != m.Generation { + return m, nil + } + if msg.Err != nil || !msg.Interrupted { + m.Stopping = false + if msg.Err != nil { + m.appendSettledEntry(HistoryEntry{Kind: EntryError, Text: "could not stop turn: " + msg.Err.Error()}) + } + } + return m, nil + } + + var taCmd tea.Cmd + oldMenuRows := min(4, len(m.CommandMenu.Matches(m.TextArea.Value()))) + m.TextArea, taCmd = m.TextArea.Update(msg) + if min(4, len(m.CommandMenu.Matches(m.TextArea.Value()))) != oldMenuRows { + m.SetSize(m.Width, m.Height) + } + cmds = append(cmds, taCmd) + + return m, tea.Batch(cmds...) +} + +func (m *ChatModel) replaceWorkspaceCmd(newWorkspace string) tea.Cmd { + client := m.Client + sessID := m.SessionID + gen := m.Generation + + return func() tea.Msg { + if client == nil { + return ChatReplaceWorkspaceMsg{SessionID: sessID, Generation: gen, Err: fmt.Errorf("no client available")} + } + upd, err := client.ReplaceWorkspace(context.Background(), newWorkspace) + if err != nil { + return ChatReplaceWorkspaceMsg{SessionID: sessID, Generation: gen, Err: err} + } + return ChatReplaceWorkspaceMsg{SessionID: sessID, Generation: gen, Workspace: upd.Workspace} + } +} + +func (m *ChatModel) sendTurnCmd(content string, image *daemon.ImageAttachment) tea.Cmd { + client := m.Client + sessID := m.SessionID + gen := m.Generation + + return func() tea.Msg { + if client == nil { + return ChatTurnSentMsg{SessionID: sessID, Generation: gen, Prompt: content, Image: image, Err: fmt.Errorf("no client available")} + } + res, err := client.Send(context.Background(), content, image) + if err != nil { + return ChatTurnSentMsg{SessionID: sessID, Generation: gen, Prompt: content, Image: image, Err: err} + } + return ChatTurnSentMsg{SessionID: sessID, Generation: gen, Prompt: content, Image: image, OK: res.OK, Queued: res.Queued} + } +} + +func (m *ChatModel) interruptCmd() tea.Cmd { + client := m.Client + sessID := m.SessionID + gen := m.Generation + + return func() tea.Msg { + if client == nil { + return ChatInterruptMsg{SessionID: sessID, Generation: gen, Err: fmt.Errorf("no client available")} + } + ok, err := client.Interrupt(context.Background()) + return ChatInterruptMsg{SessionID: sessID, Generation: gen, Interrupted: ok, Err: err} + } +} + +func (m *ChatModel) isRecognizedCommand(input string) bool { + trimmed := strings.TrimSpace(input) + if !strings.HasPrefix(trimmed, "/") { + return false + } + parts := strings.Fields(trimmed) + if len(parts) == 0 { + return false + } + token := parts[0] + switch token { + case "/a", "/agents", "/sessions", "/q", "/quit", "/exit", "/new", "/model", "/extensions", + "/plugins", "/tree", "/context", "/t", "/thinking", "/v", "/verbose", + "/status", "/login", "/mouse": + return true + } + for _, cmd := range m.CommandMenu.Catalog { + if cmd.Name == token { + return true + } + } + return false +} + +func (m *ChatModel) submitInput(input string, cmds *[]tea.Cmd) { + if strings.HasPrefix(input, "/") && m.isRecognizedCommand(input) { + m.handleSubmittedCommand(input, cmds) + return + } + + if len(m.pendingUsers) >= MaxPendingUsers { + m.ErrorNotice = "too many pending turns; wait for current turn to complete" + m.refreshViewportContent() + return + } + + img := m.AttachedImage + m.AttachedImage = nil + m.pendingUsers = append(m.pendingUsers, PendingUserTurn{ + Text: input, + Image: img, + }) + m.isSending = true + m.Follow = true + m.refreshViewportContent() + + *cmds = append(*cmds, m.sendTurnCmd(input, img), m.startAnimation()) +} + +func (m *ChatModel) handleSubmittedCommand(input string, cmds *[]tea.Cmd) { + m.TextArea.Reset() + trimmed := strings.TrimSpace(input) + + switch { + case trimmed == "/a" || trimmed == "/agents" || trimmed == "/sessions": + *cmds = append(*cmds, func() tea.Msg { return ChatBackToSessionsMsg{} }) + case trimmed == "/q" || trimmed == "/quit" || trimmed == "/exit": + if m.streamCancel != nil { + m.streamCancel() + } + *cmds = append(*cmds, func() tea.Msg { return ChatQuitMsg{} }) + case trimmed == "/new": + *cmds = append(*cmds, func() tea.Msg { return ChatNewSessionMsg{} }) + case trimmed == "/model": + *cmds = append(*cmds, func() tea.Msg { return ChatOpenModelPickerMsg{} }) + case strings.HasPrefix(trimmed, "/model "): + modelArg := strings.TrimSpace(trimmed[7:]) + *cmds = append(*cmds, func() tea.Msg { + return ChatExecuteCommandMsg{Name: "/model", Args: modelArg} + }) + case trimmed == "/extensions" || trimmed == "/plugins": + *cmds = append(*cmds, func() tea.Msg { return ChatOpenExtensionPickerMsg{} }) + case trimmed == "/tree": + *cmds = append(*cmds, func() tea.Msg { return ChatOpenTreePickerMsg{} }) + case trimmed == "/context": + *cmds = append(*cmds, func() tea.Msg { return ChatOpenContextInspectorMsg{} }) + case trimmed == "/t" || trimmed == "/thinking": + m.Flags.Thinking = !m.Flags.Thinking + m.rebuildSettledLines() + m.refreshViewportContent() + case trimmed == "/v" || trimmed == "/verbose": + m.Flags.Tools = !m.Flags.Tools + m.rebuildSettledLines() + m.refreshViewportContent() + case trimmed == "/status": + statusText := fmt.Sprintf("session: %s\nworkspace: %s\nmodel: %s", m.SessionID, m.Workspace, m.Model) + if m.Usage != nil { + statusText += fmt.Sprintf("\ntokens: %s", formatUsage(m.Usage)) + } + m.appendSettledEntry(HistoryEntry{ + Kind: EntryNote, + Text: statusText, + }) + m.refreshViewportContent() + case strings.HasPrefix(trimmed, "/login"): + name := strings.TrimSpace(strings.TrimPrefix(trimmed, "/login")) + *cmds = append(*cmds, func() tea.Msg { return ChatOpenLoginMsg{Name: name} }) + default: + for _, cmd := range m.CommandMenu.Catalog { + if cmd.Name == trimmed && cmd.Page != nil && *cmd.Page { + *cmds = append(*cmds, func() tea.Msg { return ChatOpenPageMsg{Command: trimmed} }) + return + } + } + parts := strings.SplitN(trimmed, " ", 2) + cmdName := parts[0] + cmdArgs := "" + if len(parts) > 1 { + cmdArgs = parts[1] + } + *cmds = append(*cmds, func() tea.Msg { + return ChatExecuteCommandMsg{Name: cmdName, Args: cmdArgs} + }) + } +} + +func (m *ChatModel) handleStreamEvent(evt daemon.StreamEvent) { + if evt.Type != daemon.EventToolProgress { + m.Progress = nil + } + switch evt.Type { + case daemon.EventReset: + m.settleActiveStream() + m.History.Clear() + m.settledLines = nil + m.settledLinesBytes = 0 + m.droppedSettledLines = 0 + m.activeKind = StreamKindNone + m.activeText = "" + m.streamedHash = fnvOffset64 + m.streamedLen = 0 + m.ToolProgressText = "" + m.Usage = nil + m.Notice = "" + m.ErrorNotice = "" + m.TurnFailed = false + m.Stopping = false + m.Stopped = false + m.Follow = true + m.scrollOffset = 0 + m.pendingUsers = nil + + case daemon.EventRetry: + m.activeKind = StreamKindNone + m.activeText = "" + m.streamedHash = fnvOffset64 + m.streamedLen = 0 + m.ToolProgressText = "" + + case daemon.EventUser: + m.Stopped = false + m.TurnFailed = false + m.settleActiveStream() + + if m.Client != nil && evt.ClientID == m.Client.ClientID() { + for i, p := range m.pendingUsers { + if p.Text == evt.Text { + m.pendingUsers = append(m.pendingUsers[:i], m.pendingUsers[i+1:]...) + break + } + } + } + + speaker := "You" + if evt.Source != "" && evt.Source != "chat" { + speaker = evt.Source + } + var ts int64 + if evt.Timestamp != nil && *evt.Timestamp > 0 { + ts = *evt.Timestamp + } else if evt.TriggeredAt != "" { + if parsedT, err := time.Parse(time.RFC3339, evt.TriggeredAt); err == nil { + ts = parsedT.UnixMilli() + } + } + entry := HistoryEntry{ + Kind: EntryUser, + Speaker: speaker, + Text: evt.Text, + ClientID: evt.ClientID, + Timestamp: ts, + } + m.appendSettledEntry(entry) + + case daemon.EventText: + m.ToolProgressText = "" + m.Status.Running = true + m.Status.Idle = false + phase := daemon.PhaseReasoning + m.Status.Phase = &phase + + if m.activeKind != StreamKindText { + m.settleActiveStream() + m.activeKind = StreamKindText + } + m.activeText += evt.Text + m.streamedHash = fnv1a(m.streamedHash, evt.Text) + m.streamedLen += int64(len(evt.Text)) + + if len(m.activeText) > MaxLiveStreamBytes { + m.settleActiveStream() + m.activeKind = StreamKindText + } + + case daemon.EventThinking: + m.ToolProgressText = "" + m.Status.Running = true + m.Status.Idle = false + phase := daemon.PhaseReasoning + m.Status.Phase = &phase + + if m.activeKind != StreamKindThinking { + m.settleActiveStream() + m.activeKind = StreamKindThinking + } + m.activeText += evt.Text + + if len(m.activeText) > MaxLiveStreamBytes { + m.settleActiveStream() + m.activeKind = StreamKindThinking + } + + case daemon.EventToolProgress: + m.Progress = evt.Progress + if evt.Progress != nil { + m.settleActiveStream() + m.Status.Running = true + m.Status.Idle = false + phase := daemon.PhaseTool + m.Status.Phase = &phase + m.ToolProgressText = progressLabel(*evt.Progress) + } else { + m.ToolProgressText = "" + } + + case daemon.EventTool: + m.settleActiveStream() + m.ToolProgressText = "" + m.Status.Running = true + m.Status.Idle = false + + entry := HistoryEntry{ + Kind: EntryTool, + ToolName: evt.ToolName, + ToolArgs: evt.ToolArgs, + ToolResult: evt.ToolResult, + ToolTrace: evt.ToolTrace, + Timestamp: time.Now().UnixMilli(), + } + m.appendSettledEntry(entry) + + case daemon.EventMessage: + m.ToolProgressText = "" + + targetHash := fnv1a(fnvOffset64, evt.Text) + isDuplicate := (m.streamedLen == int64(len(evt.Text))) && (m.streamedHash == targetHash) + m.streamedHash = fnvOffset64 + m.streamedLen = 0 + + m.settleActiveStream() + + if isDuplicate { + return + } + + var ts int64 + if evt.Timestamp != nil && *evt.Timestamp > 0 { + ts = *evt.Timestamp + } + entry := HistoryEntry{ + Kind: EntryAssistant, + Speaker: m.AgentName, + Text: evt.Text, + Timestamp: ts, + } + m.appendSettledEntry(entry) + + case daemon.EventNote: + m.settleActiveStream() + entry := HistoryEntry{ + Kind: EntryNote, + Text: evt.Text, + Timestamp: time.Now().UnixMilli(), + } + m.appendSettledEntry(entry) + + case daemon.EventError: + m.TurnFailed = true + m.settleActiveStream() + m.ToolProgressText = "" + m.Status.Running = false + m.Status.Idle = true + phase := daemon.PhaseResting + m.Status.Phase = &phase + + entry := HistoryEntry{ + Kind: EntryError, + Text: evt.Text, + Timestamp: time.Now().UnixMilli(), + } + m.appendSettledEntry(entry) + + case daemon.EventCompacted: + m.settleActiveStream() + m.ToolProgressText = "" + + entry := HistoryEntry{ + Kind: EntryCompacted, + Text: evt.Summary, + Evicted: evt.Evicted, + Timestamp: time.Now().UnixMilli(), + } + m.appendSettledEntry(entry) + + case daemon.EventUsage: + m.settleActiveStream() + m.Usage = evt.Usage + + case daemon.EventInterrupted: + m.Stopping = false + m.Stopped = true + m.TurnFailed = false + m.settleActiveStream() + m.ToolProgressText = "" + m.Status.Running = false + m.Status.Idle = true + phase := daemon.PhaseResting + m.Status.Phase = &phase + + entry := HistoryEntry{ + Kind: EntryNote, + Text: "stopped by you", + Timestamp: time.Now().UnixMilli(), + } + m.appendSettledEntry(entry) + } +} + +func formatUsage(u *daemon.Usage) string { + if u == nil { + return "—" + } + total := 0 + if u.TotalTokens != nil { + total = *u.TotalTokens + } + rate := "" + if u.TokensPerSecond != nil && *u.TokensPerSecond > 0 { + rate = fmt.Sprintf(" · %.1f tok/s", *u.TokensPerSecond) + } + return fmt.Sprintf("%s tokens%s", formatTokens(total), rate) +} + +func formatTokens(val int) string { + if val >= 1_000_000 { + return fmt.Sprintf("%.1fm", float64(val)/1_000_000.0) + } + if val >= 1_000 { + return fmt.Sprintf("%.1fk", float64(val)/1_000.0) + } + return fmt.Sprintf("%d", val) +} + +func (m ChatModel) padding() int { + if m.Width >= 50 { + return 2 + } + return 1 +} + +func (m ChatModel) chatWidth() int { return max(1, m.Width-2*m.padding()) } +func (m ChatModel) sidebarWidth() int { + for _, glance := range m.Glances { + if len(glance.Rows) > 0 { + margin := m.chatWidth() - min(100, m.chatWidth()) - 2 + if margin >= 16 { + return min(32, margin) + } + break + } + } + return 0 +} + +func progressLabel(progress daemon.ToolProgress) string { + if intent := progress.Intent; intent != nil { + verbs := map[string]string{"write": "writing", "edit": "editing", "read": "reading", "run": "running"} + verb := verbs[intent.Kind] + if intent.Kind == "run" && progress.Phase == "generating" { + verb = "preparing" + } + return verb + " " + intent.Target + } + if progress.Phase == "generating" { + return "making a " + progress.Name + " call" + } + return "running " + progress.Name +} + +func (m ChatModel) renderProgress() string { + if m.Progress == nil { + return "" + } + width := m.Renderer.BodyWidth + label := strings.Map(func(r rune) rune { + if r < 32 || r == 127 { + return ' ' + } + return r + }, m.ToolProgressText) + codeWidth := 0 + if m.Progress.Phase == "generating" && m.Progress.Code != nil { + labelWidth := min(ansi.StringWidth(label), max(0, (width-5)/2)) + codeWidth = max(0, width-2-labelWidth-3) + } + spinner := []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}[m.ProgressFrame%10] + prefix := spinner + " " + if width < 2 { + return "\x1b[36m" + spinner + "\x1b[0m" + } + label = ansi.Truncate(label, max(0, width-ansi.StringWidth(prefix)-max(0, codeWidth+3)), "…") + line := "\x1b[36m" + prefix + "\x1b[0m\x1b[37m" + label + "\x1b[0m" + if codeWidth > 0 { + line += "\x1b[90m · \x1b[0m\x1b[37m" + ansi.Truncate(m.Progress.Code.Text, codeWidth, "…") + "\x1b[0m" + } + return line +} + +func (m ChatModel) statusLine() string { + if m.TurnFailed || m.ErrorNotice != "" || m.ExternalError != "" { + return "turn failed · see error above" + } + if m.Stopping { + return "stopping…" + } + if m.Stopped { + return "stopped" + } + if m.isSending || len(m.pendingUsers) > 0 && !m.Status.Running { + return "preparing" + } + if m.Progress != nil { + if m.Progress.Phase == "generating" { + return "generating call" + } + return "running " + m.Progress.Name + } + if m.Status.Running && !m.Status.Idle { + if m.activeKind == StreamKindText { + return "responding" + } + if m.Status.Phase != nil { + switch *m.Status.Phase { + case daemon.PhaseTool: + return "running tool" + case daemon.PhaseCompacting: + return "compacting context" + case daemon.PhasePreparing: + return "preparing" + } + } + return "thinking" + } + if m.Status.Phase == nil && m.Client != nil { + return "connecting…" + } + if m.Status.Phase == nil { + return "opening session…" + } + return "ready" +} + +func truncateMiddle(text string, width int) string { + if width <= 0 { + return "" + } + runes := []rune(text) + if len(runes) <= width { + return text + } + if width == 1 { + return "…" + } + left := (width - 1 + 1) / 2 + return string(runes[:left]) + "…" + string(runes[len(runes)-(width-1-left):]) +} + +func (m ChatModel) View() string { + width := m.chatWidth() + pad := strings.Repeat(" ", m.padding()) + var rows []string + workspace := m.Workspace + if workspace == "" { + workspace = "chat" + } + model := m.Model + var glance *PageGlance + for i := range m.Glances { + if len(m.Glances[i].Rows) > 0 { + glance = &m.Glances[i] + break + } + } + right := model + if glance != nil && width-100 < 26 { + right = fmt.Sprintf("%s %d", glance.Title, len(glance.Rows)) + " " + right + } + nameWidth := lipgloss.Width(m.AgentName) + workspaceWidth := max(1, width-nameWidth-2-lipgloss.Width(right)-2) + workspace = truncateMiddle(workspace, workspaceWidth) + header := m.Styles.Bold.Render(m.AgentName) + " " + m.Styles.Faint.Render(workspace) + if right != "" { + space := max(1, width-lipgloss.Width(header)-lipgloss.Width(right)) + header += strings.Repeat(" ", space) + m.Styles.Faint.Render(right) + } + rows = append(rows, header, "") + errorNotice := m.ExternalError + if m.ErrorNotice != "" { + errorNotice = m.ErrorNotice + } + notice := m.ExternalNotice + if m.Notice != "" { + notice = m.Notice + } + if errorNotice != "" { + rows = append(rows, m.Styles.Error.Render("error: "+errorNotice)) + } else if notice != "" { + rows = append(rows, lipgloss.NewStyle().Foreground(lipgloss.Color("14")).Render(notice)) + } + + view := m.Viewport.View() + if m.History.Len() == 0 && m.activeText == "" && m.ToolProgressText == "" { + view = m.Styles.Faint.Render("what are we working on?") + } + if m.sidebarWidth() > 0 { + view = lipgloss.JoinHorizontal(lipgloss.Top, view, " ", m.renderGlances()) + } + content := strings.Split(view, "\n") + for len(content) < m.Viewport.Height { + content = append(content, "") + } + content = content[:min(len(content), m.Viewport.Height)] + if m.dragAnchor != nil { + content = HighlightSelection(content, Selection{Anchor: *m.dragAnchor, Head: m.dragHead}) + } + rows = append(rows, content...) + pendingRows := min(3, len(m.pendingUsers)) + for i := 0; i < pendingRows; i++ { + if i == 2 && len(m.pendingUsers) > 2 { + rows = append(rows, m.Styles.ChatWarning.Render(fmt.Sprintf("+%d more pending", len(m.pendingUsers)-2))) + break + } + label := "sending" + if m.pendingUsers[i].Queued { + label = fmt.Sprintf("queued %d", i+1) + } + rows = append(rows, m.Styles.ChatWarning.Render(label+" · "+strings.Join(strings.Fields(m.pendingUsers[i].Text), " "))) + } + status := m.statusLine() + if m.Follow && m.animating() && m.Progress == nil && !m.TurnFailed && m.ErrorNotice == "" && m.ExternalError == "" { + spinner := []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}[m.ProgressFrame%10] + status = spinner + " " + status + } + if !m.Follow { + status = fmt.Sprintf("history · %d rows below · pgdn", max(0, len(m.settledLines)-m.scrollOffset-m.Viewport.Height)) + } + if m.AttachedImage != nil { + status = daemon.ImageLabel(m.AttachedImage.ImageMetadata) + " attached · esc remove" + } + if m.CopyStatus != "" { + status = m.CopyStatus + } + if m.TurnFailed || m.ErrorNotice != "" || m.ExternalError != "" { + rows = append(rows, m.Styles.Error.Render(status)) + } else { + rows = append(rows, m.Styles.Faint.Render(status)) + } + rows = append(rows, m.Styles.Faint.Render(strings.Repeat("─", width))) + if m.WorkspaceRecovery != nil { + rows = append(rows, m.Styles.ChatWarning.Render("workspace not found: "+m.WorkspaceRecovery.Missing), m.RecoveryInput.View()) + help := "enter confirms and retries · esc cancels" + if m.WorkspaceRecovery.Saving { + help = "updating workspace…" + } + if m.WorkspaceRecovery.Error != "" { + help = m.WorkspaceRecovery.Error + } + if m.WorkspaceRecovery.Error != "" { + rows = append(rows, m.Styles.Error.Render(help)) + } else { + rows = append(rows, m.Styles.Faint.Render(help)) + } + } else { + rows = append(rows, m.composerView()) + if menu := m.CommandMenu.View(m.TextArea.Value()); menu != "" { + rows = append(rows, strings.Split(strings.TrimSuffix(menu, "\n"), "\n")...) + } + } + rows = append(rows, m.renderFooter()) + for i, row := range rows { + rows[i] = pad + row + } + return strings.Join(rows, "\n") +} + +func (m ChatModel) composerView() string { + value := m.TextArea.Value() + lines := strings.Split(value, "\n") + cursor := 0 + for i := 0; i < min(m.TextArea.Line(), len(lines)); i++ { + cursor += len([]rune(lines[i])) + 1 + } + cursor += m.TextArea.LineInfo().StartColumn + m.TextArea.LineInfo().ColumnOffset + shown := []rune(strings.ReplaceAll(value, "\n", " ")) + cursor = min(cursor, len(shown)) + columns := max(1, m.chatWidth()-2) + first := max(0, cursor-columns+1) + end := min(len(shown), first+columns) + before := string(shown[first:cursor]) + block := " " + if cursor < len(shown) { + block = string(shown[cursor : cursor+1]) + } + after := "" + if cursor+1 < end { + after = string(shown[cursor+1 : end]) + } + return m.Styles.PromptBright.Render("› ") + before + lipgloss.NewStyle().Reverse(true).Render(block) + after +} + +func (m ChatModel) renderGlances() string { + for _, g := range m.Glances { + if len(g.Rows) == 0 { + continue + } + room := max(0, min(m.Viewport.Height, 12)-1) + shown := min(room, len(g.Rows)) + if len(g.Rows) > room { + shown = max(0, room-1) + } + rows := []string{m.Styles.Faint.Render(fmt.Sprintf("%s · %d", g.Title, len(g.Rows)))} + for _, item := range g.Rows[:shown] { + mark := "○" + style := m.Styles.Faint + switch item.Tone { + case ToneActive: + mark = "●" + style = m.Styles.ChatSuccess + case ToneWarning: + mark = "!" + style = m.Styles.ChatWarning + case ToneMuted: + mark = "✓" + } + rows = append(rows, style.Render(mark)+" "+item.Text) + } + if shown < len(g.Rows) { + rows = append(rows, m.Styles.Faint.Render(fmt.Sprintf("+%d more", len(g.Rows)-shown))) + } + return lipgloss.NewStyle().Width(m.sidebarWidth()).Render(strings.Join(rows, "\n")) + } + return "" +} + +func (m ChatModel) renderFooter() string { + width := m.chatWidth() + context, cache := "—", "—/—" + usage := m.Usage + if usage != nil && (usage.Model == "" || m.Model == "" || usage.Model == m.Model) { + total := usage.TotalTokens + if total == nil && usage.PromptTokens != nil { + fallback := *usage.PromptTokens + if usage.CompletionTokens != nil { + fallback += *usage.CompletionTokens + } + total = &fallback + } + if total != nil && *total >= 0 { + context = formatTokens(*total) + } + prompt, cached := "—", "—" + if usage.PromptTokens != nil && *usage.PromptTokens >= 0 { + prompt = formatGroupedCount(*usage.PromptTokens) + } + if usage.CachedPromptTokens != nil && *usage.CachedPromptTokens >= 0 { + cached = formatGroupedCount(*usage.CachedPromptTokens) + } + cache = cached + "/" + prompt + } + modes := fmt.Sprintf("thinking %s · verbose %s", onOff(m.Flags.Thinking), onOff(m.Flags.Tools)) + brief := fmt.Sprintf("t:%s v:%s", onOff(m.Flags.Thinking), onOff(m.Flags.Tools)) + right := "ctx " + context + " · cached " + cache + compact := context + " · " + cache + candidates := [][2]string{ + {"/ commands · drag to copy · ctrl+j diffs · ctrl+k summary · " + modes, right}, + {"/ commands · drag to copy · ctrl+k summary · " + modes, right}, + {"/ commands · drag to copy · " + modes, right}, + {"/ commands · ctrl+j diffs · " + brief, compact}, + {"/ commands · drag copy · " + brief, compact}, + {"/ commands · " + brief, compact}, + {"/", compact}, + } + for _, pair := range candidates { + if lipgloss.Width(pair[0])+lipgloss.Width(pair[1]) < width { + return m.Styles.Footer.Render(pair[0] + strings.Repeat(" ", width-lipgloss.Width(pair[0])-lipgloss.Width(pair[1])) + pair[1]) + } + } + return m.Styles.Footer.Render(string([]rune("/ commands")[:min(width, len([]rune("/ commands")))])) +} + +func formatGroupedCount(count int) string { + digits := strconv.Itoa(count) + for i := len(digits) - 3; i > 0; i -= 3 { + digits = digits[:i] + "," + digits[i:] + } + return digits +} + +func onOff(enabled bool) string { + if enabled { + return "on" + } + return "off" +} diff --git a/cli/internal/tui/clipboard.go b/cli/internal/tui/clipboard.go new file mode 100644 index 000000000..0a2373a43 --- /dev/null +++ b/cli/internal/tui/clipboard.go @@ -0,0 +1,244 @@ +package tui + +import ( + "albedo/cli/internal/daemon" + "bytes" + "context" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "image" + _ "image/jpeg" + _ "image/png" + "io" + "os" + "os/exec" + "runtime" + "strings" + "time" + + "github.com/atotto/clipboard" + tea "github.com/charmbracelet/bubbletea" +) + +const ( + MaxClipboardImageBytes = 5 * 1024 * 1024 + MaxClipboardImageEdge = 16384 +) + +type CommandExecutor func(ctx context.Context, name string, args ...string) ([]byte, error) + +func defaultExec(ctx context.Context, name string, args ...string) ([]byte, error) { + cmd := exec.CommandContext(ctx, name, args...) + stdout, err := cmd.StdoutPipe() + if err != nil { + return nil, err + } + if err := cmd.Start(); err != nil { + return nil, err + } + + // Bounded read: read up to MaxClipboardImageBytes + 1 so we never buffer unbounded subprocess output + limited := io.LimitReader(stdout, MaxClipboardImageBytes+1) + buf, err := io.ReadAll(limited) + _ = cmd.Wait() + + if len(buf) > MaxClipboardImageBytes { + return nil, fmt.Errorf("clipboard image exceeds %d byte limit", MaxClipboardImageBytes) + } + return buf, err +} + +var CurrentExecutor CommandExecutor = defaultExec + +func CopyText(text string) error { + return clipboard.WriteAll(text) +} + +func ReadClipboardText() (string, error) { + return clipboard.ReadAll() +} + +func isRemote() bool { + return os.Getenv("SSH_CONNECTION") != "" || os.Getenv("SSH_CLIENT") != "" || os.Getenv("MOSH_CONNECTION") != "" +} + +func ClipboardHasImage() bool { + if isRemote() { + return false + } + + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + defer cancel() + + switch runtime.GOOS { + case "darwin": + if _, err := exec.LookPath("pngpaste"); err == nil { + out, err := CurrentExecutor(ctx, "pngpaste", "-b") + if err == nil && len(out) == 0 { + return true + } + } + out, err := CurrentExecutor(ctx, "osascript", "-e", "clipboard info") + if err == nil { + s := string(out) + if strings.Contains(s, "«class PNGf»") || strings.Contains(s, "JPEG picture") || strings.Contains(s, "TIFF picture") { + return true + } + } + return false + + case "linux": + if os.Getenv("WAYLAND_DISPLAY") != "" { + if _, err := exec.LookPath("wl-paste"); err == nil { + out, err := CurrentExecutor(ctx, "wl-paste", "--list-types") + if err == nil && strings.Contains(string(out), "image/") { + return true + } + } + } + if os.Getenv("DISPLAY") != "" { + if _, err := exec.LookPath("xclip"); err == nil { + out, err := CurrentExecutor(ctx, "xclip", "-selection", "clipboard", "-t", "TARGETS", "-o") + if err == nil && strings.Contains(string(out), "image/") { + return true + } + } + } + return false + } + + return false +} + +func parseAppleScriptHex(out []byte) ([]byte, error) { + s := strings.TrimSpace(string(out)) + if !strings.HasPrefix(s, "«data ") || !strings.HasSuffix(s, "»") { + return nil, errors.New("not an AppleScript hex payload") + } + content := strings.TrimSuffix(strings.TrimPrefix(s, "«data "), "»") + parts := strings.Fields(content) + if len(parts) == 0 { + return nil, errors.New("empty AppleScript data") + } + hexPart := parts[0] + // Skip the 4-char ostype code (e.g. PNGf, JPEG) + if len(hexPart) <= 4 { + return nil, errors.New("missing hex payload in AppleScript data") + } + rawHex := hexPart[4:] + return hex.DecodeString(rawHex) +} + +func ReadClipboardImage() (*daemon.ImageAttachment, error) { + if isRemote() { + return nil, errors.New("remote clipboard image unsupported") + } + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + var data []byte + var err error + + switch runtime.GOOS { + case "darwin": + if _, errPath := exec.LookPath("pngpaste"); errPath == nil { + data, err = CurrentExecutor(ctx, "pngpaste", "-") + } else { + script := "get the clipboard as «class PNGf»" + rawOut, errCmd := CurrentExecutor(ctx, "osascript", "-e", script) + if errCmd != nil { + return nil, errCmd + } + if len(rawOut) > MaxClipboardImageBytes { + return nil, fmt.Errorf("clipboard image too large: %d bytes (max %d)", len(rawOut), MaxClipboardImageBytes) + } + data, err = parseAppleScriptHex(rawOut) + } + + case "linux": + if os.Getenv("WAYLAND_DISPLAY") != "" { + data, err = CurrentExecutor(ctx, "wl-paste", "-t", "image/png") + } else if os.Getenv("DISPLAY") != "" { + data, err = CurrentExecutor(ctx, "xclip", "-selection", "clipboard", "-t", "image/png", "-o") + } else { + return nil, errors.New("no display or clipboard tool available") + } + + default: + return nil, fmt.Errorf("unsupported platform for clipboard images: %s", runtime.GOOS) + } + + if err != nil { + return nil, fmt.Errorf("failed to read clipboard image: %w", err) + } + + if len(data) == 0 { + return nil, errors.New("clipboard contains no image data") + } + + if len(data) > MaxClipboardImageBytes { + return nil, fmt.Errorf("clipboard image too large: %d bytes (max %d)", len(data), MaxClipboardImageBytes) + } + + // Strictly validate config - rejects truncated or 0-dimension images + cfg, format, err := image.DecodeConfig(bytes.NewReader(data)) + if err != nil { + return nil, fmt.Errorf("invalid or truncated image: %w", err) + } + if cfg.Width <= 0 || cfg.Height <= 0 { + return nil, errors.New("invalid image dimensions: zero or negative") + } + if cfg.Width > MaxClipboardImageEdge || cfg.Height > MaxClipboardImageEdge { + return nil, fmt.Errorf("image dimensions too large: %dx%d (max edge %d)", cfg.Width, cfg.Height, MaxClipboardImageEdge) + } + + var mime daemon.ImageMimeType + switch format { + case "jpeg", "jpg": + mime = daemon.ImageJPEG + case "webp": + mime = daemon.ImageWEBP + default: + mime = daemon.ImagePNG + } + + encoded := base64.StdEncoding.EncodeToString(data) + return &daemon.ImageAttachment{ + ImageMetadata: daemon.ImageMetadata{ + MimeType: mime, + Width: cfg.Width, + Height: cfg.Height, + Bytes: len(data), + }, + Data: encoded, + }, nil +} + +type ClipboardImagePastedMsg struct { + SessionID string + Generation int64 + Image *daemon.ImageAttachment + Err error +} + +func PasteClipboardImageCmd(sessionID string, gen int64) tea.Cmd { + return func() tea.Msg { + if !ClipboardHasImage() { + return ClipboardImagePastedMsg{ + SessionID: sessionID, + Generation: gen, + Err: errors.New("no image in clipboard"), + } + } + img, err := ReadClipboardImage() + return ClipboardImagePastedMsg{ + SessionID: sessionID, + Generation: gen, + Image: img, + Err: err, + } + } +} diff --git a/cli/internal/tui/commands.go b/cli/internal/tui/commands.go new file mode 100644 index 000000000..868a51209 --- /dev/null +++ b/cli/internal/tui/commands.go @@ -0,0 +1,156 @@ +package tui + +import ( + "albedo/cli/internal/daemon" + "strings" + + tea "github.com/charmbracelet/bubbletea" +) + +type ChatCommand struct { + Name string + Description string +} + +var CommonCommands = []ChatCommand{ + {Name: "/a", Description: "browse sessions"}, + {Name: "/t", Description: "show or hide thinking"}, + {Name: "/v", Description: "expand or collapse code, output and diffs"}, + {Name: "/status", Description: "show state, workspace and usage"}, + {Name: "/q", Description: "quit"}, +} + +var AppCommands = []ChatCommand{ + {Name: "/login", Description: "add or select a named openai-compatible api"}, + {Name: "/new", Description: "new coding session"}, + {Name: "/sessions", Description: "switch session"}, + {Name: "/extensions", Description: "manage this session's extension plugins"}, + {Name: "/tree", Description: "branch this session from a history checkpoint"}, +} + +type CommandMenuModel struct { + Catalog []daemon.SessionCommand + Selected int + Dismissed string + Styles Styles +} + +func NewCommandMenuModel() CommandMenuModel { + return CommandMenuModel{ + Styles: DefaultStyles, + } +} + +func (m *CommandMenuModel) SetCatalog(catalog []daemon.SessionCommand) { + m.Catalog = catalog +} + +func (m CommandMenuModel) Matches(input string) []ChatCommand { + if !strings.HasPrefix(input, "/") || strings.Contains(input, "\n") || input == m.Dismissed { + return nil + } + + all := append([]ChatCommand{}, AppCommands...) + for _, cmd := range m.Catalog { + all = append(all, ChatCommand{ + Name: cmd.Name, + Description: cmd.Description, + }) + } + // Common commands appended (override if duplicate) + for _, cmd := range CommonCommands { + all = append(all, cmd) + } + + // De-duplicate by name (last occurrence wins) + seen := make(map[string]bool) + var deduped []ChatCommand + for i := len(all) - 1; i >= 0; i-- { + name := all[i].Name + if !seen[name] { + seen[name] = true + deduped = append([]ChatCommand{all[i]}, deduped...) + } + } + + var matched []ChatCommand + for _, cmd := range deduped { + if strings.HasPrefix(cmd.Name, input) { + matched = append(matched, cmd) + } + } + return matched +} + +// OnKey handles navigation within the command popup. Returns true if consumed. +func (m *CommandMenuModel) OnKey(msg tea.KeyMsg, input string, replace func(string), submit func(string)) bool { + matches := m.Matches(input) + if len(matches) == 0 { + return false + } + + idx := m.Selected + if idx >= len(matches) { + idx = len(matches) - 1 + } + if idx < 0 { + idx = 0 + } + + switch msg.Type { + case tea.KeyEsc: + m.Dismissed = input + return true + case tea.KeyUp: + if idx > 0 { + m.Selected = idx - 1 + } + return true + case tea.KeyDown: + if idx < len(matches)-1 { + m.Selected = idx + 1 + } + return true + case tea.KeyTab: + replace(matches[idx].Name) + return true + case tea.KeyEnter: + submit(matches[idx].Name) + return true + default: + m.Selected = 0 + } + return false +} + +func (m CommandMenuModel) View(input string) string { + matches := m.Matches(input) + if len(matches) == 0 { + return "" + } + + idx := m.Selected + if idx >= len(matches) { + idx = len(matches) - 1 + } + if idx < 0 { + idx = 0 + } + + start := max(0, idx-3) + end := min(len(matches), max(4, idx+1)) + + var b strings.Builder + for i := start; i < end; i++ { + cmd := matches[i] + isSel := (i == idx) + line := cmd.Name + " " + cmd.Description + if isSel { + b.WriteString(m.Styles.Selected.Render(line)) + } else { + b.WriteString(line) + } + b.WriteString("\n") + } + return b.String() +} diff --git a/cli/internal/tui/context_inspector.go b/cli/internal/tui/context_inspector.go new file mode 100644 index 000000000..552c96f30 --- /dev/null +++ b/cli/internal/tui/context_inspector.go @@ -0,0 +1,460 @@ +package tui + +import ( + "albedo/cli/internal/daemon" + "context" + "errors" + "fmt" + "github.com/charmbracelet/lipgloss" + "math" + "net/url" + "strings" + "unicode/utf16" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" + "golang.org/x/text/language" + "golang.org/x/text/message" +) + +type ContextSection struct { + ID string `json:"id"` + Label string `json:"label"` + Kind string `json:"kind"` // "instructions" | "extension_context" | "history" | "tools" | "other" + Source string `json:"source"` + ItemCount int `json:"item_count"` + ByteCount int `json:"byte_count"` + Preview string `json:"preview"` + Pages int `json:"pages"` +} + +type CompactionState struct { + Strategy string `json:"strategy,omitempty"` + Status string `json:"status"` // "not_configured" | "not_needed" | "compacted" | "unknown" + Source string `json:"source,omitempty"` + TriggerFreePercent *float64 `json:"trigger_free_percent,omitempty"` + InputLimitTokens *int `json:"input_limit_tokens,omitempty"` + EstimatedInputTokens *int `json:"estimated_input_tokens,omitempty"` + EstimateMethod string `json:"estimate_method,omitempty"` + BeforeItems *int `json:"before_items,omitempty"` + AfterItems *int `json:"after_items,omitempty"` +} + +type ContextSnapshot struct { + State string `json:"state"` // "pending" | "ready" + Reason string `json:"reason,omitempty"` + CapturedAt *int64 `json:"captured_at,omitempty"` + Provider string `json:"provider,omitempty"` + Model string `json:"model,omitempty"` + Protocol string `json:"protocol,omitempty"` + ContextWindowTokens *int `json:"context_window_tokens,omitempty"` + Sections []ContextSection `json:"sections,omitempty"` + Compaction CompactionState `json:"compaction,omitempty"` +} + +type ContextPage struct { + Section string `json:"section"` + Page int `json:"page"` + Pages int `json:"pages"` + Content string `json:"content"` + Omitted string `json:"omitted,omitempty"` +} + +type ContextDetail struct { + Section ContextSection + Page int + Value *ContextPage + Error string + Scroll int +} + +type ContextDoneMsg struct{} + +type contextSnapshotLoadedMsg struct { + Snapshot *ContextSnapshot + Err error + Gen int +} + +type contextPageLoadedMsg struct { + SectionID string + Page int + Data *ContextPage + Err error + Gen int +} + +type ContextInspectorModel struct { + Conn *daemon.Connection + SessionID string + Snapshot *ContextSnapshot + Cursor int + Detail *ContextDetail + Loading bool + Error string + Generation int + Width int + Height int + Styles Styles +} + +func NewContextInspectorModel(conn *daemon.Connection, sessionID string) ContextInspectorModel { + return ContextInspectorModel{ + Conn: conn, + SessionID: sessionID, + Loading: true, + Styles: DefaultStyles, + } +} + +func (m *ContextInspectorModel) SetSize(width, height int) { + m.Width = width + m.Height = height +} + +func (m ContextInspectorModel) Init() tea.Cmd { + return m.loadSnapshotCmd(m.Generation) +} + +func jsLength(s string) int { return len(utf16.Encode([]rune(s))) } + +func validContextSnapshot(s ContextSnapshot) error { + if s.State == "pending" { + if jsLength(s.Reason) <= 500 { + return nil + } + return errors.New("daemon returned invalid context metadata") + } + if s.State != "ready" || jsLength(s.Model) > 512 || s.Sections == nil || len(s.Sections) > 1000 || + jsLength(s.Provider) > 512 || jsLength(s.Protocol) > 512 || s.CapturedAt != nil && *s.CapturedAt < 0 || + s.ContextWindowTokens != nil && *s.ContextWindowTokens < 0 { + return errors.New("daemon returned invalid context metadata") + } + kinds := map[string]bool{"instructions": true, "extension_context": true, "history": true, "tools": true, "other": true} + for _, sec := range s.Sections { + if sec.ID == "" || jsLength(sec.ID) > 200 || sec.Label == "" || jsLength(sec.Label) > 200 || !kinds[sec.Kind] || + jsLength(sec.Source) > 500 || sec.ItemCount < 0 || sec.ByteCount < 0 || jsLength(sec.Preview) > 2000 || sec.Pages < 0 || sec.Pages > 10000 { + return errors.New("daemon returned invalid context section metadata") + } + } + c := s.Compaction + statuses := map[string]bool{"not_configured": true, "not_needed": true, "compacted": true, "unknown": true} + if !statuses[c.Status] || jsLength(c.Strategy) > 200 || jsLength(c.Source) > 500 || jsLength(c.EstimateMethod) > 500 || + c.TriggerFreePercent != nil && (math.IsNaN(*c.TriggerFreePercent) || math.IsInf(*c.TriggerFreePercent, 0) || *c.TriggerFreePercent < 0 || *c.TriggerFreePercent > 100) || + c.InputLimitTokens != nil && *c.InputLimitTokens < 0 || c.EstimatedInputTokens != nil && *c.EstimatedInputTokens < 0 || + c.BeforeItems != nil && *c.BeforeItems < 0 || c.AfterItems != nil && *c.AfterItems < 0 { + return errors.New("daemon returned invalid compaction metadata") + } + return nil +} + +func validContextPage(p ContextPage, sectionID string) error { + if p.Section != sectionID || p.Page < 0 || p.Pages < 0 || p.Pages > 10000 || p.Page >= max(1, p.Pages) || jsLength(p.Content) > 65536 || jsLength(p.Omitted) > 1000 { + return errors.New("daemon returned invalid context page") + } + return nil +} + +func (m ContextInspectorModel) loadSnapshotCmd(gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil { + return contextSnapshotLoadedMsg{Err: errors.New("daemon connection unavailable"), Gen: gen} + } + + health, err := daemon.Request[struct { + Capabilities []string `json:"capabilities"` + }](context.Background(), m.Conn, "/health", nil) + if err == nil { + hasCap := false + for _, c := range health.Capabilities { + if c == "session_context" { + hasCap = true + break + } + } + if !hasCap { + return contextSnapshotLoadedMsg{ + Err: errors.New("daemon upgrade needed for /context; when ready, run albedo daemon --stop, then albedo (this clears python variables)"), + Gen: gen, + } + } + } + + path := fmt.Sprintf("/sessions/%s/context", url.PathEscape(m.SessionID)) + snapshot, err := daemon.Request[ContextSnapshot](context.Background(), m.Conn, path, nil) + if err != nil { + return contextSnapshotLoadedMsg{Err: err, Gen: gen} + } + if err := validContextSnapshot(snapshot); err != nil { + return contextSnapshotLoadedMsg{Err: err, Gen: gen} + } + return contextSnapshotLoadedMsg{Snapshot: &snapshot, Gen: gen} + } +} + +func (m ContextInspectorModel) loadPageCmd(sectionID string, page int, gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil { + return contextPageLoadedMsg{SectionID: sectionID, Page: page, Err: errors.New("daemon connection unavailable"), Gen: gen} + } + path := fmt.Sprintf("/sessions/%s/context/%s/%d", url.PathEscape(m.SessionID), url.PathEscape(sectionID), page) + data, err := daemon.Request[ContextPage](context.Background(), m.Conn, path, nil) + if err != nil { + return contextPageLoadedMsg{SectionID: sectionID, Page: page, Err: err, Gen: gen} + } + if err := validContextPage(data, sectionID); err != nil { + return contextPageLoadedMsg{SectionID: sectionID, Page: page, Err: err, Gen: gen} + } + return contextPageLoadedMsg{SectionID: sectionID, Page: page, Data: &data, Gen: gen} + } +} + +func (m ContextInspectorModel) Update(msg tea.Msg) (ContextInspectorModel, tea.Cmd) { + switch msg := msg.(type) { + case contextSnapshotLoadedMsg: + if msg.Gen != m.Generation { + return m, nil + } + m.Loading = false + if msg.Err != nil { + m.Error = msg.Err.Error() + return m, nil + } + m.Snapshot = msg.Snapshot + m.Error = "" + if m.Snapshot != nil && m.Cursor >= len(m.Snapshot.Sections) { + m.Cursor = max(0, len(m.Snapshot.Sections)-1) + } + return m, nil + + case contextPageLoadedMsg: + if msg.Gen != m.Generation || m.Detail == nil || m.Detail.Section.ID != msg.SectionID || m.Detail.Page != msg.Page { + return m, nil + } + if msg.Err != nil { + m.Detail.Error = msg.Err.Error() + } else { + m.Detail.Value = msg.Data + m.Detail.Error = "" + } + return m, nil + + case tea.KeyMsg: + if msg.Type == tea.KeyEsc || msg.Type == tea.KeyCtrlC || msg.Type == tea.KeyCtrlD { + if m.Detail != nil { + m.Detail = nil + m.Generation++ + return m, nil + } + return m, func() tea.Msg { return ContextDoneMsg{} } + } + + if m.Detail != nil { + lines := []string{} + if m.Detail.Value != nil { + lines = wrapContextContent(m.Detail.Value.Content, max(1, m.Width-4)) + } + visibleRows := max(1, m.Height-7) + maxScroll := max(0, len(lines)-visibleRows) + + switch msg.Type { + case tea.KeyLeft: + if m.Detail.Page > 0 { + m.Detail.Page-- + m.Detail.Value = nil + m.Detail.Scroll = 0 + m.Detail.Error = "" + m.Generation++ + return m, m.loadPageCmd(m.Detail.Section.ID, m.Detail.Page, m.Generation) + } + case tea.KeyRight: + if m.Detail.Page+1 < m.Detail.Section.Pages { + m.Detail.Page++ + m.Detail.Value = nil + m.Detail.Scroll = 0 + m.Detail.Error = "" + m.Generation++ + return m, m.loadPageCmd(m.Detail.Section.ID, m.Detail.Page, m.Generation) + } + case tea.KeyUp: + if m.Detail.Scroll > 0 { + m.Detail.Scroll-- + } + case tea.KeyDown: + if m.Detail.Scroll < maxScroll { + m.Detail.Scroll++ + } + case tea.KeyPgUp: + m.Detail.Scroll = max(0, m.Detail.Scroll-visibleRows) + case tea.KeyPgDown: + m.Detail.Scroll = min(maxScroll, m.Detail.Scroll+visibleRows) + } + return m, nil + } + + if strings.ToLower(msg.String()) == "r" { + m.Loading = true + m.Snapshot = nil + m.Detail = nil + m.Error = "" + m.Generation++ + return m, m.loadSnapshotCmd(m.Generation) + } + + switch msg.Type { + case tea.KeyUp, tea.KeyCtrlP: + if m.Cursor > 0 { + m.Cursor-- + } + case tea.KeyDown, tea.KeyCtrlN: + if m.Snapshot != nil && m.Cursor < len(m.Snapshot.Sections)-1 { + m.Cursor++ + } + case tea.KeyEnter: + if m.Snapshot != nil && len(m.Snapshot.Sections) > m.Cursor { + sec := m.Snapshot.Sections[m.Cursor] + if sec.Pages > 0 { + m.Detail = &ContextDetail{ + Section: sec, + Page: 0, + Scroll: 0, + } + m.Generation++ + return m, m.loadPageCmd(sec.ID, 0, m.Generation) + } + } + } + } + + return m, nil +} + +func wrapContextContent(content string, width int) []string { + if width <= 1 { + width = 76 + } + return strings.Split(ansi.Wrap(content, width, " "), "\n") +} + +func contextCount(n int, unit string) string { + value := message.NewPrinter(language.English).Sprintf("%d", n) + if n != 1 { + unit += "s" + } + return value + " " + unit +} + +func (m ContextInspectorModel) View() string { + var b strings.Builder + line := func(text string) { b.WriteString(text); b.WriteByte('\n') } + faint := func(text string) { line(m.Styles.Dim.Render(text)) } + if m.Detail != nil { + sec, d := m.Detail.Section, m.Detail + line("albedo /context · " + sec.Label) + faint(fmt.Sprintf("%s · page %d/%d · %s", sec.Source, d.Page+1, sec.Pages, contextCount(sec.ByteCount, "byte"))) + if d.Error != "" { + line(inkRed.Render(d.Error)) + } else if d.Value == nil { + faint("loading inspectable prepared content…") + } else { + if d.Value.Omitted != "" { + line(inkYellow.Render("omitted: " + d.Value.Omitted)) + } + line("") + rows := wrapContextContent(d.Value.Content, m.Width-4) + visible := max(1, m.Height-7) + if m.Height <= 0 { + visible = 17 + } + for _, row := range rows[min(d.Scroll, len(rows)):min(len(rows), d.Scroll+visible)] { + line(row) + } + } + faint("↑↓ scroll · pgup/pgdn jump · ←→ page · esc sections") + return strings.TrimSuffix(b.String(), "\n") + } + line("albedo /context · prepared request") + faint(inkWrap("read-only · durable transcript and request-only context are separate", m.Width)) + if m.Error != "" { + line(inkRed.Render(m.Error)) + } + if m.Loading && m.Snapshot == nil && m.Error == "" { + faint("loading prepared request snapshot…") + } else if m.Snapshot == nil { + faint("r retry · esc return to chat") + } else if m.Snapshot.State == "pending" { + line(inkYellow.Render("pending · no request has been prepared for this runtime session")) + faint(m.Snapshot.Reason) + faint("r refresh · esc return to chat") + } else { + snap := m.Snapshot + label := snap.Model + if snap.Provider != "" { + label = snap.Provider + " · " + label + } + if snap.Protocol != "" { + label += " · " + snap.Protocol + } + line(label) + window := "not reported" + if snap.ContextWindowTokens != nil { + window = contextCount(*snap.ContextWindowTokens, "token") + " (configured)" + } + faint(inkWrap("context window: "+window, m.Width)) + status := map[string]string{"not_configured": "not configured", "not_needed": "not needed", "compacted": "applied", "unknown": "state unavailable"}[snap.Compaction.Status] + strategy := snap.Compaction.Strategy + if strategy == "" { + strategy = "none" + } + faint("compaction: " + strategy + " · " + status) + if snap.Compaction.TriggerFreePercent != nil { + faint(fmt.Sprintf("trigger: keep %g%% free", *snap.Compaction.TriggerFreePercent)) + } + if snap.Compaction.EstimatedInputTokens != nil { + method := snap.Compaction.EstimateMethod + if method == "" { + method = "method not reported" + } + faint("estimated input: " + contextCount(*snap.Compaction.EstimatedInputTokens, "token") + " · " + method) + } + line("") + capacity := max(1, (m.Height-9)/3) + if m.Height <= 0 { + capacity = 5 + } + first := min(max(0, m.Cursor-capacity/2), max(0, len(snap.Sections)-capacity)) + for i := first; i < min(len(snap.Sections), first+capacity); i++ { + sec := snap.Sections[i] + marker := " " + if i == m.Cursor { + marker = ">" + } + label := fmt.Sprintf("%s %d. %s ", marker, i+1, sec.Label) + source := "· " + sec.Source + if i == m.Cursor { + label = inkCyan.Render(label) + source = lipgloss.NewStyle().Foreground(lipgloss.Color("6")).Faint(true).Render(source) + } else { + source = lipgloss.NewStyle().Faint(true).Render(source) + } + label += source + line(label) + available := "content unavailable" + if sec.Pages > 0 { + available = contextCount(sec.Pages, "page") + } + faint(" " + contextCount(sec.ItemCount, "item") + " · " + contextCount(sec.ByteCount, "measured byte") + " · " + available) + if i == m.Cursor && sec.Preview != "" { + line(" " + sec.Preview) + } + } + if len(snap.Sections) == 0 { + faint("the prepared request contains no inspectable sections") + } + if len(snap.Sections) > capacity { + faint(fmt.Sprintf("showing %d–%d of %d sections", first+1, min(len(snap.Sections), first+capacity), len(snap.Sections))) + } + faint(inkWrap("↑↓ select · enter inspect content · r refresh · esc return to chat", m.Width)) + } + return strings.TrimSuffix(b.String(), "\n") +} diff --git a/cli/internal/tui/extension_picker.go b/cli/internal/tui/extension_picker.go new file mode 100644 index 000000000..64a204013 --- /dev/null +++ b/cli/internal/tui/extension_picker.go @@ -0,0 +1,330 @@ +package tui + +import ( + "albedo/cli/internal/daemon" + "context" + "errors" + "fmt" + "github.com/charmbracelet/lipgloss" + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" +) + +type ExtensionItem struct { + Name string `json:"name"` + Description string `json:"description"` + Enabled bool `json:"enabled"` + Context bool `json:"context"` + Tools []string `json:"tools"` + PythonModules []string `json:"python_modules"` + Requires []string `json:"requires"` + Plugins []string `json:"plugins"` +} + +type ExtensionPickerDoneMsg struct{} +type ExtensionPickerChangedMsg struct{} + +type extensionsLoadedMsg struct { + Extensions []ExtensionItem + Err error + Gen int +} + +type extensionToggledMsg struct { + Extensions []ExtensionItem + Err error + Gen int +} + +type ExtensionPickerModel struct { + Conn *daemon.Connection + SessionID string + Extensions []ExtensionItem + Cursor int + Confirming bool + Saving bool + Loading bool + Error string + Generation int + Width int + Height int + Styles Styles +} + +func NewExtensionPickerModel(conn *daemon.Connection, sessionID string) ExtensionPickerModel { + return ExtensionPickerModel{ + Conn: conn, + SessionID: sessionID, + Loading: true, + Styles: DefaultStyles, + } +} + +func (m *ExtensionPickerModel) SetSize(width, height int) { + m.Width = width + m.Height = height +} + +func (m ExtensionPickerModel) Init() tea.Cmd { + return m.loadExtensionsCmd(m.Generation) +} + +func (m ExtensionPickerModel) loadExtensionsCmd(gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil { + return extensionsLoadedMsg{Err: errors.New("daemon connection unavailable"), Gen: gen} + } + + // Check capability + health, err := daemon.Request[struct { + Capabilities []string `json:"capabilities"` + }](context.Background(), m.Conn, "/health", nil) + if err == nil { + hasCap := false + for _, c := range health.Capabilities { + if c == "session_extensions" { + hasCap = true + break + } + } + if !hasCap { + return extensionsLoadedMsg{ + Err: errors.New("daemon upgrade needed for /extensions; when ready, run albedo daemon --stop, then albedo (this clears python variables)"), + Gen: gen, + } + } + } + + path := fmt.Sprintf("/sessions/%s/extensions", m.SessionID) + items, err := daemon.Request[[]ExtensionItem](context.Background(), m.Conn, path, nil) + return extensionsLoadedMsg{Extensions: items, Err: err, Gen: gen} + } +} + +func (m ExtensionPickerModel) toggleExtensionCmd(name string, enabled bool, gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil { + return extensionToggledMsg{Err: errors.New("daemon connection unavailable"), Gen: gen} + } + path := fmt.Sprintf("/sessions/%s/extensions", m.SessionID) + body := map[string]any{"name": name, "enabled": enabled} + updated, err := daemon.Request[[]ExtensionItem](context.Background(), m.Conn, path, body) + return extensionToggledMsg{Extensions: updated, Err: err, Gen: gen} + } +} + +func (m ExtensionPickerModel) capabilitiesList(ext ExtensionItem) []string { + var caps []string + if ext.Context { + caps = append(caps, "context") + } + if len(ext.Tools) > 0 { + caps = append(caps, fmt.Sprintf("tools (%s)", strings.Join(ext.Tools, ", "))) + } + if len(ext.PythonModules) > 0 { + caps = append(caps, fmt.Sprintf("python modules (%s)", strings.Join(ext.PythonModules, ", "))) + } + return caps +} + +func (m ExtensionPickerModel) Update(msg tea.Msg) (ExtensionPickerModel, tea.Cmd) { + switch msg := msg.(type) { + case extensionsLoadedMsg: + if msg.Gen != m.Generation { + return m, nil + } + m.Loading = false + if msg.Err != nil { + m.Error = msg.Err.Error() + return m, nil + } + m.Extensions = msg.Extensions + m.Error = "" + if m.Cursor >= len(m.Extensions) { + m.Cursor = max(0, len(m.Extensions)-1) + } + return m, nil + + case extensionToggledMsg: + if msg.Gen != m.Generation { + return m, nil + } + m.Saving = false + if msg.Err != nil { + m.Error = msg.Err.Error() + return m, nil + } + name := "" + if m.Cursor < len(m.Extensions) { + name = m.Extensions[m.Cursor].Name + } + m.Extensions = msg.Extensions + for i, ext := range m.Extensions { + if ext.Name == name { + m.Cursor = i + break + } + } + m.Confirming = false + m.Error = "" + return m, func() tea.Msg { return ExtensionPickerChangedMsg{} } + + case tea.KeyMsg: + if msg.Type == tea.KeyEsc || (msg.Type == tea.KeyCtrlC || msg.Type == tea.KeyCtrlD) { + if m.Confirming { + m.Confirming = false + m.Error = "" + return m, nil + } + return m, func() tea.Msg { return ExtensionPickerDoneMsg{} } + } + + if m.Loading || m.Saving { + return m, nil + } + + if len(m.Extensions) == 0 && m.Error != "" { + if strings.ToLower(msg.String()) == "r" { + m.Loading = true + m.Error = "" + m.Generation++ + return m, m.loadExtensionsCmd(m.Generation) + } + return m, nil + } + + if m.Confirming { + if msg.Type == tea.KeyEnter && len(m.Extensions) > m.Cursor { + ext := m.Extensions[m.Cursor] + m.Saving = true + m.Error = "" + m.Generation++ + return m, m.toggleExtensionCmd(ext.Name, !ext.Enabled, m.Generation) + } + return m, nil + } + + switch msg.Type { + case tea.KeyUp, tea.KeyCtrlP: + if m.Cursor > 0 { + m.Cursor-- + } + case tea.KeyDown, tea.KeyCtrlN: + if m.Cursor < len(m.Extensions)-1 { + m.Cursor++ + } + case tea.KeySpace, tea.KeyEnter: + if len(m.Extensions) > 0 && m.Cursor < len(m.Extensions) { + m.Error = "" + m.Confirming = true + } + } + } + return m, nil +} + +func (m ExtensionPickerModel) View() string { + var b strings.Builder + + b.WriteString("albedo /extensions · session plugins") + b.WriteString("\n") + b.WriteString(m.Styles.Dim.Render("extensions bundle plugins for this session only")) + b.WriteString("\n") + b.WriteString(inkYellow.Render(ansi.Wrap("changes reload workers and available plugins, bust prompt-cache reuse, and may reset unsavable python variables", max(1, m.Width), " "))) + b.WriteString("\n") + + if m.Error != "" { + b.WriteString(inkRed.Render(m.Error)) + b.WriteString("\n") + } + + if m.Loading { + b.WriteString(m.Styles.Dim.Render("loading extensions…\n")) + return b.String() + } + + if len(m.Extensions) == 0 { + if m.Error != "" { + b.WriteString(m.Styles.Dim.Render("r retry · esc return to chat\n")) + } else { + b.WriteString(m.Styles.Dim.Render("no matches\nno extensions installed for this session\n" + inkWrap("↑↓ select · enter/space toggle · esc return to chat", m.Width))) + } + return b.String() + } + + lines := make([]string, len(m.Extensions)) + for i, ext := range m.Extensions { + status := "off" + if ext.Enabled { + status = inkGreen.Render("on ") + } + lines[i] = status + " " + ext.Name + if ext.Description != "" { + lines[i] += lipgloss.NewStyle().Faint(true).Render(" " + ext.Description) + } + } + b.WriteString(selectableRows(lines, m.Cursor, m.Height, m.Height, m.Width, m.Styles)) + b.WriteByte('\n') + + // Current item details + if m.Cursor < len(m.Extensions) { + current := m.Extensions[m.Cursor] + b.WriteString("\n") + if current.Description != "" { + b.WriteString(current.Description) + b.WriteString("\n") + } + + pluginsStr := "not reported" + if len(current.Plugins) > 0 { + pluginsStr = strings.Join(current.Plugins, ", ") + } + b.WriteString(m.Styles.Dim.Render("plugins: " + pluginsStr)) + b.WriteString("\n") + + caps := m.capabilitiesList(current) + capsStr := "not reported" + if len(caps) > 0 { + capsStr = strings.Join(caps, " · ") + } + b.WriteString(m.Styles.Dim.Render("capabilities: " + capsStr)) + b.WriteString("\n") + + reqStr := "none" + if len(current.Requires) > 0 { + reqStr = strings.Join(current.Requires, ", ") + } + b.WriteString(m.Styles.Dim.Render("requires: " + reqStr)) + b.WriteString("\n") + + if m.Confirming { + actionWord := "enable" + if current.Enabled { + actionWord = "disable" + } + choice := "enter confirm" + if m.Error != "" { + choice = "enter retry" + } + confirmMsg := fmt.Sprintf("%s %s and reload this session's workers? %s · esc cancel", actionWord, current.Name, choice) + b.WriteString(inkYellow.Render(confirmMsg)) + b.WriteString("\n") + } + } + + if m.Saving { + currName := "extension" + if m.Cursor < len(m.Extensions) { + currName = m.Extensions[m.Cursor].Name + } + b.WriteString(m.Styles.Dim.Render(fmt.Sprintf("reloading workers for %s…", currName))) + } else if m.Confirming { + b.WriteString(m.Styles.Dim.Render("waiting for confirmation")) + } else { + b.WriteString(m.Styles.Dim.Render(inkWrap("↑↓ select · enter/space toggle · esc return to chat", m.Width))) + } + + return b.String() +} diff --git a/cli/internal/tui/login.go b/cli/internal/tui/login.go new file mode 100644 index 000000000..0649e08ce --- /dev/null +++ b/cli/internal/tui/login.go @@ -0,0 +1,822 @@ +package tui + +import ( + "albedo/cli/internal/config" + "albedo/cli/internal/daemon" + "context" + "errors" + "fmt" + "net/http" + "net/url" + "sort" + "strings" + "time" + + "github.com/charmbracelet/bubbles/cursor" + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" +) + +type LoginDoneMsg struct { + Name string + Settings config.Settings +} + +type LoginCancelMsg struct{} + +type LoginStep int + +const ( + StepChoose LoginStep = iota + StepName + StepBaseURL + StepAPIKey + StepProtocol + StepModels + StepModel + StepCodexAuth + StepCodexModels + StepSaving +) + +type loginModelsLoadedMsg struct { + Models []string + Note string + Err error + Gen int +} + +type codexAuthStartedMsg struct { + Verifier string + State string + AuthURL string + Ctx context.Context + Cancel context.CancelFunc + Close func() + CodeChan <-chan string + ErrChan <-chan error + Gen int +} + +type codexAuthExchangedMsg struct { + Cred *config.CodexCredential + Models []string + Err error + Gen int +} + +type providerSavedMsg struct { + Name string + Settings config.Settings + Err error +} + +type LoginModel struct { + Conn *daemon.Connection + Step LoginStep + Profiles config.Profiles + Name string + Kind string // "openai" | "codex" + Draft config.Settings + TextInput textinput.Model + ChoosePicker PickerModel + ProtocolPicker PickerModel + ModelPicker PickerModel + BrowserOpener func(url string) // Fail-closed: nil means do not launch browser + ExchangeCodeFunc func(ctx context.Context, client *http.Client, code, verifier string) (*config.CodexCredential, error) + CodexVerifier string + CodexState string + CodexAuthURL string + CodexStatus string + CodexClose func() + CodexCancel context.CancelFunc + CodexManualChan chan string + Catalog []string + CatalogNote string + Error string + Generation int + Width int + Height int + Styles Styles +} + +func (m LoginModel) openBrowserCmd(urlStr string) tea.Cmd { + return func() tea.Msg { + m.openBrowser(urlStr) + return nil + } +} + +func (m LoginModel) openBrowser(urlStr string) { + if m.BrowserOpener != nil { + m.BrowserOpener(urlStr) + } + // Fail-closed by default: nil opener does NOT launch a browser. +} + +func NewLoginModel(conn *daemon.Connection, nameHint string) LoginModel { + home := config.HomeDir() + profiles, loadErr := config.LoadProfiles(home) + + ti := textinput.New() + ti.Prompt = "" + ti.Cursor.SetMode(cursor.CursorStatic) + + emptyDraft := config.Settings{ + Extension: "openai", + BaseURL: "https://api.openai.com/v1", + Protocol: "responses", + } + + m := LoginModel{ + Conn: conn, + Profiles: profiles, + Draft: emptyDraft, + TextInput: ti, + Styles: DefaultStyles, + } + if loadErr != nil { + m.Error = loadErr.Error() + m.Step = StepChoose + m.buildChoosePicker() + return m + } + + if nameHint != "" { + cleanName, err := config.ValidateProviderName(nameHint) + if err != nil { + m.Error = err.Error() + m.Step = StepChoose + m.buildChoosePicker() + return m + } + if s, ok := profiles.Providers[cleanName]; ok { + m.Name = cleanName + m.Draft = s + m.Step = StepSaving + return m + } + if cleanName == "codex" { + m.Kind = "codex" + m.Name = "codex" + m.Step = StepCodexAuth + m.TextInput.Focus() + return m + } + m.Name = cleanName + m.Kind = "openai" + m.Step = StepBaseURL + m.resetInput() + m.TextInput.SetValue(emptyDraft.BaseURL) + m.TextInput.Focus() + return m + } + + if len(profiles.Providers) > 0 { + m.Step = StepChoose + m.buildChoosePicker() + } else { + m.Step = StepName + m.resetInput() + m.TextInput.Placeholder = "" + m.TextInput.Focus() + } + + return m +} + +func (m LoginModel) inputWidth() int { + // Ink includes its cursor cell in width; Bubbles tracks the cursor separately. + if m.Step == StepCodexAuth { + return max(8, m.Width-25) + } + return max(8, m.Width-19) +} + +func (m *LoginModel) resetInput() { + m.TextInput.Reset() + m.TextInput.EchoMode = textinput.EchoNormal + m.TextInput.Width = m.inputWidth() +} + +func (m *LoginModel) SetSize(width, height int) { + m.Width = width + m.Height = height + m.TextInput.Width = m.inputWidth() + m.TextInput.SetValue(m.TextInput.Value()) + m.ChoosePicker.SetSize(width, height) + m.ProtocolPicker.SetSize(width, height) + m.ModelPicker.SetSize(width, height) +} + +func (m *LoginModel) cancelCodex() { + if m.CodexClose != nil { + m.CodexClose() + m.CodexClose = nil + } + if m.CodexCancel != nil { + m.CodexCancel() + m.CodexCancel = nil + } + m.CodexManualChan = nil +} + +func (m LoginModel) startCodexCmd(gen int) tea.Cmd { + return func() tea.Msg { + verifier, state, authURL := config.CreateAuthorization() + ctx, cancel := context.WithCancel(context.Background()) + + listener, codeChan, errChan, closeServer := config.StartCallbackServer(ctx, state) + if listener == nil { + codeChan = nil + } + + return codexAuthStartedMsg{ + Verifier: verifier, + State: state, + AuthURL: authURL, + Ctx: ctx, + Cancel: cancel, + Close: closeServer, + CodeChan: codeChan, + ErrChan: errChan, + Gen: gen, + } + } +} + +func (m LoginModel) waitForCodexAuthCmd(ctx context.Context, codeChan <-chan string, errChan <-chan error, manualChan <-chan string, verifier, state string, gen int) tea.Cmd { + return func() tea.Msg { + var code string + select { + case <-ctx.Done(): + return codexAuthExchangedMsg{Err: ctx.Err(), Gen: gen} + case err, ok := <-errChan: + if !ok || err == nil { + return codexAuthExchangedMsg{Err: errors.New("callback server closed"), Gen: gen} + } + return codexAuthExchangedMsg{Err: err, Gen: gen} + case c, ok := <-codeChan: + if !ok || c == "" { + return codexAuthExchangedMsg{Err: errors.New("callback server closed"), Gen: gen} + } + code = c + case manualInput, ok := <-manualChan: + if !ok || manualInput == "" { + return codexAuthExchangedMsg{Err: errors.New("manual input closed"), Gen: gen} + } + parsedCode, parsedState := config.ParseAuthorizationInput(manualInput) + if parsedState != "" && parsedState != state { + return codexAuthExchangedMsg{Err: errors.New("oauth state mismatch"), Gen: gen} + } + if parsedCode == "" { + return codexAuthExchangedMsg{Err: errors.New("missing authorization code"), Gen: gen} + } + code = parsedCode + } + + reqCtx, reqCancel := context.WithTimeout(ctx, 20*time.Second) + defer reqCancel() + + var cred *config.CodexCredential + var err error + + if m.ExchangeCodeFunc != nil { + cred, err = m.ExchangeCodeFunc(reqCtx, nil, code, verifier) + } else { + client := &http.Client{Timeout: 20 * time.Second} + cred, err = config.ExchangeCodexCode(reqCtx, client, code, verifier) + } + + if err != nil { + return codexAuthExchangedMsg{Err: err, Gen: gen} + } + + home := config.HomeDir() + if err := config.SaveCodexAccount(home, *cred); err != nil { + return codexAuthExchangedMsg{Err: err, Gen: gen} + } + + var names []string + if m.Conn != nil { + names, _ = daemon.Request[[]string](reqCtx, m.Conn, "/models/codex", nil) + } + + return codexAuthExchangedMsg{Cred: cred, Models: names, Gen: gen} + } +} + +func (m *LoginModel) buildChoosePicker() { + var items []PickerItem + names := make([]string, 0, len(m.Profiles.Providers)) + for name := range m.Profiles.Providers { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + settings := m.Profiles.Providers[name] + extension := settings.Extension + if extension == "" { + extension = "openai" + } + detail := fmt.Sprintf("%s · %s", settings.Model, extension) + if name == m.Profiles.Active { + detail += " · active" + } + items = append(items, PickerItem{ + ID: "use:" + name, + Label: name, + Detail: detail, + }) + } + items = append(items, PickerItem{ + ID: "add-openai", + Label: "add or update openai-compatible provider", + Detail: "", + }) + items = append(items, PickerItem{ + ID: "add-codex", + Label: "add chatgpt codex account", + Detail: "oauth · supports multiple accounts", + }) + + initialSel := "use:" + m.Profiles.Active + m.ChoosePicker = NewPickerModel("provider for new sessions", items, false, initialSel) + m.ChoosePicker.SetSize(m.Width, m.Height) +} + +func (m *LoginModel) buildProtocolPicker() { + items := []PickerItem{ + {ID: "responses", Label: "responses", Detail: "openai responses api"}, + {ID: "chat_completions", Label: "chat completions", Detail: "widely supported by compatible endpoints"}, + } + m.ProtocolPicker = NewPickerModel("api protocol", items, false, m.Draft.Protocol) + m.ProtocolPicker.SetSize(m.Width, m.Height) +} + +func (m *LoginModel) buildModelPicker() { + var items []PickerItem + for _, name := range m.Catalog { + items = append(items, PickerItem{ + ID: "model:" + name, + Label: name, + Detail: "", + }) + } + items = append(items, PickerItem{ + ID: "manual", + Label: "enter model id manually", + Detail: "", + }) + + initialSel := "model:" + m.Draft.Model + m.ModelPicker = NewPickerModel("model", items, true, initialSel) + m.ModelPicker.SetSize(m.Width, m.Height) +} + +func (m LoginModel) Init() tea.Cmd { + if m.Step == StepSaving { + return m.saveProviderCmd(m.Name, m.Draft) + } + if m.Step == StepChoose { + return m.ChoosePicker.Init() + } + if m.Step == StepCodexAuth { + return m.startCodexCmd(m.Generation) + } + return textinput.Blink +} + +func (m LoginModel) fetchCatalogCmd(ext, endpoint string, gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil { + return loginModelsLoadedMsg{ + Note: "could not read the models.dev catalog; enter a model id", + Gen: gen, + } + } + + path := fmt.Sprintf("/models/%s?endpoint=%s", ext, url.QueryEscape(endpoint)) + names, err := daemon.Request[[]string](context.Background(), m.Conn, path, nil) + if err != nil { + return loginModelsLoadedMsg{ + Models: nil, + Note: "could not read the models.dev catalog; enter a model id", + Err: err, + Gen: gen, + } + } + var note string + if len(names) == 0 { + note = "models.dev has no matching models; enter a model id" + } + return loginModelsLoadedMsg{Models: names, Note: note, Gen: gen} + } +} + +func (m LoginModel) saveProviderCmd(name string, settings config.Settings) tea.Cmd { + return func() tea.Msg { + home := config.HomeDir() + if err := config.SaveProvider(home, name, settings); err != nil { + return providerSavedMsg{Name: name, Settings: settings, Err: err} + } + return providerSavedMsg{Name: name, Settings: settings} + } +} + +func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { + switch msg := msg.(type) { + case codexAuthStartedMsg: + if msg.Gen != m.Generation || m.Step != StepCodexAuth { + // Stale started result: close listener and cancel context immediately + if msg.Close != nil { + msg.Close() + } + if msg.Cancel != nil { + msg.Cancel() + } + return m, nil + } + + m.CodexClose = msg.Close + m.CodexCancel = msg.Cancel + m.CodexVerifier = msg.Verifier + m.CodexState = msg.State + m.CodexAuthURL = msg.AuthURL + m.CodexStatus = "waiting for browser authorization" + m.CodexManualChan = make(chan string, 1) + m.TextInput.Focus() + + var cmds []tea.Cmd + cmds = append(cmds, textinput.Blink) + + if msg.AuthURL != "" { + cmds = append(cmds, m.openBrowserCmd(msg.AuthURL)) + } + + if msg.CodeChan == nil { + m.Error = "could not start callback server on port 1455; paste callback url or code manually" + } + + cmds = append(cmds, m.waitForCodexAuthCmd(msg.Ctx, msg.CodeChan, msg.ErrChan, m.CodexManualChan, msg.Verifier, msg.State, m.Generation)) + return m, tea.Batch(cmds...) + + case loginModelsLoadedMsg: + if msg.Gen != m.Generation || m.Step != StepModels { + return m, nil + } + m.Catalog = msg.Models + if m.Catalog == nil { + m.Catalog = []string{} + } + m.CatalogNote = msg.Note + m.buildModelPicker() + return m, m.ModelPicker.Init() + + case codexAuthExchangedMsg: + if msg.Gen != m.Generation || m.Step != StepCodexAuth { + return m, nil + } + m.cancelCodex() + if msg.Err != nil { + m.Error = msg.Err.Error() + return m, nil + } + m.Catalog = msg.Models + if m.Catalog == nil { + m.Catalog = []string{} + } + if len(m.Catalog) == 0 { + m.CatalogNote = "models.dev has no OpenAI models cached; enter a model id" + } + if current, ok := m.Profiles.Providers["codex"]; ok && current.IsCodex() { + m.Draft.Model = current.Model + } + m.Step = StepCodexModels + m.buildModelPicker() + return m, m.ModelPicker.Init() + + case providerSavedMsg: + if msg.Err != nil { + m.Error = msg.Err.Error() + m.Step = StepChoose + m.buildChoosePicker() + return m, m.ChoosePicker.Init() + } + return m, func() tea.Msg { + return LoginDoneMsg{Name: msg.Name, Settings: msg.Settings} + } + + case tea.KeyMsg: + if msg.Type == tea.KeyEsc || msg.Type == tea.KeyCtrlC || msg.Type == tea.KeyCtrlD { + pickerStep := m.Step == StepChoose || m.Step == StepProtocol || m.Step == StepModels || m.Step == StepCodexModels + if !pickerStep || msg.Type == tea.KeyCtrlD { + m.cancelCodex() + m.Generation++ + return m, func() tea.Msg { return LoginCancelMsg{} } + } + } + + case PickerSelectMsg: + switch m.Step { + case StepChoose: + if msg.ID == "add-openai" { + m.Name = "" + m.Kind = "openai" + m.Draft = config.Settings{Extension: "openai", BaseURL: "https://api.openai.com/v1", Protocol: "responses"} + m.Step = StepName + m.resetInput() + m.TextInput.Placeholder = "" + m.TextInput.Focus() + return m, textinput.Blink + } + if msg.ID == "add-codex" { + m.Kind = "codex" + m.Name = "codex" + m.Step = StepCodexAuth + m.resetInput() + m.TextInput.Placeholder = "" + m.TextInput.Focus() + m.Generation++ + return m, m.startCodexCmd(m.Generation) + } + if strings.HasPrefix(msg.ID, "use:") { + name := strings.TrimPrefix(msg.ID, "use:") + if s, ok := m.Profiles.Providers[name]; ok { + m.Step = StepSaving + return m, m.saveProviderCmd(name, s) + } + } + + case StepProtocol: + m.Draft.Protocol = msg.ID + m.Catalog = nil + m.CatalogNote = "" + m.Step = StepModels + m.Generation++ + return m, m.fetchCatalogCmd("openai", m.Draft.BaseURL, m.Generation) + + case StepModels, StepCodexModels: + if msg.ID == "manual" { + m.Step = StepModel + m.resetInput() + m.TextInput.Placeholder = "" + m.TextInput.Focus() + return m, textinput.Blink + } + if strings.HasPrefix(msg.ID, "model:") { + modelName := strings.TrimPrefix(msg.ID, "model:") + m.Draft.Model = modelName + m.Step = StepSaving + if m.Kind == "codex" { + m.Draft.Extension = "codex" + m.Draft.Protocol = "responses" + } + return m, m.saveProviderCmd(m.Name, m.Draft) + } + } + + case PickerCancelMsg: + if m.Step == StepChoose { + return m, func() tea.Msg { return LoginCancelMsg{} } + } + if m.Step == StepProtocol { + m.Step = StepAPIKey + m.resetInput() + m.TextInput.EchoMode = textinput.EchoPassword + m.TextInput.Focus() + return m, textinput.Blink + } + if m.Step == StepModels { + m.Generation++ + m.Step = StepBaseURL + m.resetInput() + m.TextInput.SetValue(m.Draft.BaseURL) + m.TextInput.Focus() + return m, textinput.Blink + } + if m.Step == StepCodexModels { + return m, func() tea.Msg { return LoginCancelMsg{} } + } + } + + // Handle input submissions per step + switch m.Step { + case StepChoose: + var cmd tea.Cmd + m.ChoosePicker, cmd = m.ChoosePicker.Update(msg) + return m, cmd + + case StepProtocol: + var cmd tea.Cmd + m.ProtocolPicker, cmd = m.ProtocolPicker.Update(msg) + return m, cmd + + case StepModels, StepCodexModels: + var cmd tea.Cmd + m.ModelPicker, cmd = m.ModelPicker.Update(msg) + return m, cmd + + case StepName: + if keyMsg, ok := msg.(tea.KeyMsg); ok && keyMsg.Type == tea.KeyEnter { + val := strings.TrimSpace(m.TextInput.Value()) + m.TextInput.SetCursor(0) + name, err := config.ValidateProviderName(val) + if err != nil { + m.Error = err.Error() + return m, nil + } + m.Name = name + m.Error = "" + + _, saved := m.Profiles.Providers[name] + if name == "codex" && !saved { + m.Kind = "codex" + m.Step = StepCodexAuth + m.resetInput() + m.TextInput.Placeholder = "" + m.TextInput.Focus() + m.Generation++ + return m, m.startCodexCmd(m.Generation) + } + + // If exists in providers, prefill + if s, ok := m.Profiles.Providers[name]; ok { + if s.IsCodex() { + m.Kind = "codex" + m.Step = StepCodexAuth + m.resetInput() + m.TextInput.Placeholder = "" + m.TextInput.Focus() + m.Generation++ + return m, m.startCodexCmd(m.Generation) + } + m.Draft = s + } + + m.Step = StepBaseURL + m.resetInput() + m.TextInput.SetValue(m.Draft.BaseURL) + m.TextInput.Focus() + return m, textinput.Blink + } + + case StepBaseURL: + if keyMsg, ok := msg.(tea.KeyMsg); ok && keyMsg.Type == tea.KeyEnter { + val := strings.TrimSpace(m.TextInput.Value()) + m.TextInput.SetCursor(0) + if val == "" { + val = m.Draft.BaseURL + } + endpoint, err := config.ValidateEndpoint(val) + if err != nil { + m.Error = err.Error() + return m, nil + } + if endpoint != m.Draft.BaseURL { + m.Draft.APIKey = "" + } + m.Draft.BaseURL = endpoint + m.Error = "" + m.Step = StepAPIKey + m.resetInput() + m.TextInput.EchoMode = textinput.EchoPassword + m.TextInput.Placeholder = "" + m.TextInput.Focus() + return m, textinput.Blink + } + + case StepAPIKey: + if keyMsg, ok := msg.(tea.KeyMsg); ok && keyMsg.Type == tea.KeyEnter { + val := m.TextInput.Value() + m.TextInput.SetCursor(0) + if val == "" && m.Draft.APIKey != "" { + val = m.Draft.APIKey + } + if val == "" { + m.Error = "enter an api key without spaces or control characters" + return m, nil + } + for _, r := range val { + if r <= 0x20 || r == 0x7f { + m.Error = "enter an api key without spaces or control characters" + return m, nil + } + } + m.Draft.APIKey = val + m.Error = "" + m.Step = StepProtocol + m.buildProtocolPicker() + return m, m.ProtocolPicker.Init() + } + + case StepCodexAuth: + if keyMsg, ok := msg.(tea.KeyMsg); ok && keyMsg.Type == tea.KeyEnter { + val := strings.TrimSpace(m.TextInput.Value()) + if val != "" && m.CodexManualChan != nil { + m.CodexStatus = "exchanging authorization code…" + m.Error = "" + select { + case m.CodexManualChan <- val: + default: + } + return m, nil + } + } + + case StepModel: + if keyMsg, ok := msg.(tea.KeyMsg); ok && keyMsg.Type == tea.KeyEnter { + val := strings.TrimSpace(m.TextInput.Value()) + m.TextInput.SetCursor(0) + if err := validateModelID(val); err != nil { + m.Error = err.Error() + return m, nil + } + m.Draft.Model = val + m.Error = "" + m.Step = StepSaving + if m.Kind == "codex" { + m.Draft.Extension = "codex" + m.Draft.Protocol = "responses" + } + return m, m.saveProviderCmd(m.Name, m.Draft) + } + } + + var cmd tea.Cmd + m.TextInput, cmd = m.TextInput.Update(msg) + return m, cmd +} + +func (m LoginModel) View() string { + var b strings.Builder + b.WriteString("albedo /login") + if m.Name != "" { + b.WriteString(" " + m.Name) + } + b.WriteByte('\n') + location := "model auth extensions · saved in " + config.HomeDir() + if m.Width > 0 && ansi.StringWidth(location) > m.Width && ansi.StringWidth(config.HomeDir()) <= m.Width { + location = "model auth extensions · saved in\n" + config.HomeDir() + } + b.WriteString(m.Styles.Dim.Render(ansi.Wrap(location, m.Width, ""))) + b.WriteByte('\n') + if m.Error != "" { + b.WriteString(m.Styles.Error.Foreground(lipgloss.Color("1")).Render(ansi.Wrap(m.Error, m.Width, ""))) + b.WriteByte('\n') + } + + switch m.Step { + case StepChoose: + b.WriteString(m.ChoosePicker.View()) + case StepProtocol: + b.WriteString(m.ProtocolPicker.View()) + case StepModels, StepCodexModels: + if m.Catalog == nil { + b.WriteString(m.Styles.Dim.Render("loading models…")) + break + } + if m.CatalogNote != "" { + b.WriteString(m.Styles.Dim.Render(m.CatalogNote)) + b.WriteByte('\n') + } + b.WriteString(m.ModelPicker.View()) + case StepCodexAuth: + status := m.CodexStatus + if status == "" { + status = "starting codex oauth…" + } + b.WriteString(status) + b.WriteByte('\n') + if m.CodexAuthURL != "" { + b.WriteString(m.Styles.Dim.Render(ansi.Hardwrap(m.CodexAuthURL, m.Width, true))) + b.WriteByte('\n') + } + b.WriteString("callback url or code: ") + b.WriteString(m.TextInput.View()) + b.WriteByte('\n') + b.WriteString(m.Styles.Dim.Render(ansi.Hardwrap("browser callback completes automatically · enter pastes manually · esc cancel", m.Width, true))) + case StepSaving: + b.WriteString(m.Styles.Dim.Render("saving provider…")) + default: + stepLabels := map[LoginStep]string{ + StepName: "provider name", StepBaseURL: "api base url", + StepAPIKey: "api key", StepModel: "model id", + } + b.WriteString(stepLabels[m.Step] + ": ") + b.WriteString(m.TextInput.View()) + b.WriteByte('\n') + var hints []string + if m.Step == StepAPIKey && m.Draft.APIKey != "" { + hints = append(hints, "enter keeps the saved key") + } + if m.Step == StepName && m.Conn != nil { + hints = append(hints, "use codex for ChatGPT oauth") + } + hints = append(hints, "enter continue", "esc cancel") + b.WriteString(m.Styles.Dim.Render(ansi.Wrap(strings.Join(hints, " · "), m.Width, ""))) + } + return b.String() +} diff --git a/cli/internal/tui/markdown.go b/cli/internal/tui/markdown.go new file mode 100644 index 000000000..1f969f452 --- /dev/null +++ b/cli/internal/tui/markdown.go @@ -0,0 +1,287 @@ +package tui + +import ( + "regexp" + "strings" + "unicode" +) + +var ( + headerRegex = regexp.MustCompile(`^(#{1,6})\s+(.*)`) + ulRegex = regexp.MustCompile(`^(\s*)[*\-+]\s+(.*)`) + olRegex = regexp.MustCompile(`^(\s*)(\d+)\.\s+(.*)`) + hrRegex = regexp.MustCompile(`^(\*\*\*|---|___)$`) + + kwPy = map[string]bool{ + "if": true, "elif": true, "else": true, "for": true, "while": true, "in": true, "not": true, "and": true, + "or": true, "is": true, "import": true, "from": true, "as": true, "def": true, "class": true, "return": true, + "yield": true, "pass": true, "break": true, "continue": true, "try": true, "except": true, "finally": true, + "raise": true, "with": true, "lambda": true, "True": true, "False": true, "None": true, "async": true, "await": true, + } + + kwJS = map[string]bool{ + "if": true, "else": true, "for": true, "while": true, "do": true, "switch": true, "case": true, "break": true, + "continue": true, "return": true, "function": true, "class": true, "const": true, "let": true, "var": true, + "new": true, "import": true, "export": true, "default": true, "from": true, "async": true, "await": true, + "try": true, "catch": true, "finally": true, "throw": true, "null": true, "undefined": true, "true": true, "false": true, + } + + kwGo = map[string]bool{ + "break": true, "default": true, "func": true, "interface": true, "select": true, "case": true, "defer": true, + "go": true, "map": true, "struct": true, "chan": true, "else": true, "goto": true, "package": true, + "switch": true, "const": true, "fallthrough": true, "if": true, "range": true, "type": true, "continue": true, + "for": true, "import": true, "return": true, "var": true, "nil": true, "true": true, "false": true, + } +) + +const ( + ansiReset = "\x1b[0m" + ansiBold = "\x1b[1m" + ansiDim = "\x1b[2m" + ansiItalic = "\x1b[3m" + ansiGreen = "\x1b[32m" + ansiCyan = "\x1b[36m" + ansiGray = "\x1b[90m" + ansiBYellow = "\x1b[93m" + ansiBBlue = "\x1b[94m" + ansiBMagenta = "\x1b[95m" + ansiBCyan = "\x1b[96m" +) + +func getKeywords(lang string) map[string]bool { + switch strings.ToLower(lang) { + case "python", "py": + return kwPy + default: + return kwJS + } +} + +func HighlightCode(code string, lang string) string { + l := strings.ToLower(lang) + if l == "" || l == "text" || l == "plain" || l == "txt" { + return code + } + keywords := getKeywords(l) + isPy := l == "python" || l == "py" + + var b strings.Builder + chars := []rune(code) + n := len(chars) + i := 0 + + for i < n { + ch := chars[i] + + // Single line comments + if (!isPy && ch == '/' && i+1 < n && chars[i+1] == '/') || (isPy && ch == '#') { + j := i + for j < n && chars[j] != '\n' { + j++ + } + b.WriteString(ansiGray + ansiItalic) + b.WriteString(string(chars[i:j])) + b.WriteString(ansiReset) + i = j + continue + } + + // Strings + if ch == '"' || ch == '\'' || ch == '`' { + quote := ch + j := i + 1 + for j < n { + if chars[j] == '\\' && j+1 < n { + j += 2 + continue + } + if chars[j] == quote { + j++ + break + } + j++ + } + b.WriteString(ansiGreen) + b.WriteString(string(chars[i:j])) + b.WriteString(ansiReset) + i = j + continue + } + + // Numbers + if unicode.IsDigit(ch) && (i == 0 || !unicode.IsLetter(chars[i-1])) { + j := i + for j < n && (unicode.IsDigit(chars[j]) || chars[j] == '.' || chars[j] == '_' || chars[j] == 'x' || chars[j] == 'b') { + j++ + } + b.WriteString(ansiBYellow) + b.WriteString(string(chars[i:j])) + b.WriteString(ansiReset) + i = j + continue + } + + // Identifiers / keywords + if unicode.IsLetter(ch) || ch == '_' { + j := i + for j < n && (unicode.IsLetter(chars[j]) || unicode.IsDigit(chars[j]) || chars[j] == '_') { + j++ + } + word := string(chars[i:j]) + if keywords[word] { + b.WriteString(ansiBMagenta + word + ansiReset) + } else if unicode.IsUpper(chars[i]) { + b.WriteString(ansiBYellow + word + ansiReset) + } else if j < n && chars[j] == '(' { + b.WriteString(ansiBBlue + word + ansiReset) + } else { + b.WriteString(word) + } + i = j + continue + } + + b.WriteRune(ch) + i++ + } + + return b.String() +} + +func RenderInlineMarkdown(text string) string { + // Inline code: `code` + res := text + for { + start := strings.Index(res, "`") + if start == -1 { + break + } + end := strings.Index(res[start+1:], "`") + if end == -1 { + break + } + end += start + 1 + code := res[start+1 : end] + res = res[:start] + ansiCyan + code + ansiReset + res[end+1:] + } + + // Bold: **text** + for { + start := strings.Index(res, "**") + if start == -1 { + break + } + end := strings.Index(res[start+2:], "**") + if end == -1 { + break + } + end += start + 2 + content := res[start+2 : end] + res = res[:start] + ansiBold + content + ansiReset + res[end+2:] + } + + // Italic: *text* + for { + start := strings.Index(res, "*") + if start == -1 { + break + } + end := strings.Index(res[start+1:], "*") + if end == -1 { + break + } + end += start + 1 + content := res[start+1 : end] + res = res[:start] + ansiItalic + content + ansiReset + res[end+1:] + } + + return res +} + +func RenderMarkdownAnsi(text string, width int) string { + if width <= 0 { + width = 80 + } + lines := strings.Split(text, "\n") + var out []string + i := 0 + + for i < len(lines) { + line := lines[i] + + // Fenced code block + if strings.HasPrefix(line, "```") { + lang := strings.TrimSpace(strings.TrimPrefix(line, "```")) + var codeLines []string + i++ + for i < len(lines) && !strings.HasPrefix(lines[i], "```") { + codeLines = append(codeLines, lines[i]) + i++ + } + if i < len(lines) { + i++ + } + + code := strings.Join(codeLines, "\n") + highlighted := HighlightCode(code, lang) + + if lang != "" { + out = append(out, ansiDim+ansiCyan+"┌─ "+lang+ansiReset) + } + for _, hl := range strings.Split(highlighted, "\n") { + out = append(out, ansiDim+"│"+ansiReset+" "+hl) + } + out = append(out, ansiDim+"└"+ansiReset) + continue + } + + // Headers + if hMatch := headerRegex.FindStringSubmatch(line); hMatch != nil { + title := RenderInlineMarkdown(hMatch[2]) + colors := []string{ansiBCyan, ansiCyan, ansiBBlue, ansiBBlue, ansiBMagenta, ansiBMagenta} + out = append(out, ansiBold+colors[len(hMatch[1])-1]+title+ansiReset) + i++ + continue + } + + // Horizontal rule + if hrRegex.MatchString(strings.TrimSpace(line)) { + barLen := width + out = append(out, ansiDim+strings.Repeat("─", barLen)+ansiReset) + i++ + continue + } + + // Bullet list + if ulMatch := ulRegex.FindStringSubmatch(line); ulMatch != nil { + indent := ulMatch[1] + item := RenderInlineMarkdown(ulMatch[2]) + out = append(out, indent+ansiDim+"•"+ansiReset+" "+item) + i++ + continue + } + + // Numbered list + if olMatch := olRegex.FindStringSubmatch(line); olMatch != nil { + indent := olMatch[1] + num := olMatch[2] + item := RenderInlineMarkdown(olMatch[3]) + out = append(out, indent+ansiDim+num+"."+ansiReset+" "+item) + i++ + continue + } + + // Blockquote + if strings.HasPrefix(line, "> ") { + quote := RenderInlineMarkdown(strings.TrimPrefix(line, "> ")) + out = append(out, ansiDim+"│"+ansiReset+" "+ansiItalic+quote+ansiReset) + i++ + continue + } + + out = append(out, RenderInlineMarkdown(line)) + i++ + } + + return strings.Join(out, "\n") +} diff --git a/cli/internal/tui/memory_profile_test.go b/cli/internal/tui/memory_profile_test.go new file mode 100644 index 000000000..6aafa7bb9 --- /dev/null +++ b/cli/internal/tui/memory_profile_test.go @@ -0,0 +1,299 @@ +package tui + +import ( + "albedo/cli/internal/config" + "albedo/cli/internal/daemon" + "encoding/json" + "fmt" + tea "github.com/charmbracelet/bubbletea" + "os" + "os/exec" + "path/filepath" + "runtime" + "runtime/debug" + "runtime/pprof" + "strconv" + "strings" + "testing" + "time" +) + +const profileDir = "/tmp/albedo-memory-profile" + +type ProcessOSMemory struct { + PID int `json:"pid"` + RSSBytes uint64 `json:"rss_bytes"` + RSSFormatted string `json:"rss_formatted"` + MaxRSSBytes uint64 `json:"max_rss_bytes"` + VMMapFootprintMB float64 `json:"vmmap_footprint_mb"` + VMMapRawSummary string `json:"vmmap_raw_summary,omitempty"` +} + +func readOSMemory() ProcessOSMemory { + pid := os.Getpid() + var rusage runtime.MemStats + runtime.ReadMemStats(&rusage) + + mem := ProcessOSMemory{ + PID: pid, + } + + // Read RSS via ps + out, err := exec.Command("ps", "-o", "rss=", "-p", strconv.Itoa(pid)).Output() + if err == nil { + rssKb, err := strconv.ParseUint(strings.TrimSpace(string(out)), 10, 64) + if err == nil { + mem.RSSBytes = rssKb * 1024 + mem.RSSFormatted = fmt.Sprintf("%.2f MB", float64(mem.RSSBytes)/(1024*1024)) + } + } + + // Read macOS vmmap summary if available + vmOut, err := exec.Command("vmmap", "-summary", strconv.Itoa(pid)).Output() + if err == nil { + lines := strings.Split(string(vmOut), "\n") + for _, line := range lines { + if strings.HasPrefix(line, "Physical footprint:") { + parts := strings.Fields(line) + if len(parts) >= 3 { + valStr := parts[2] + if strings.HasSuffix(valStr, "K") { + if f, err := strconv.ParseFloat(strings.TrimSuffix(valStr, "K"), 64); err == nil { + mem.VMMapFootprintMB = f / 1024.0 + } + } else if strings.HasSuffix(valStr, "M") { + if f, err := strconv.ParseFloat(strings.TrimSuffix(valStr, "M"), 64); err == nil { + mem.VMMapFootprintMB = f + } + } else if strings.HasSuffix(valStr, "G") { + if f, err := strconv.ParseFloat(strings.TrimSuffix(valStr, "G"), 64); err == nil { + mem.VMMapFootprintMB = f * 1024.0 + } + } + } + break + } + } + } + + return mem +} + +type PhaseMetrics struct { + PhaseName string `json:"phase_name"` + PhaseDescription string `json:"phase_description"` + Timestamp string `json:"timestamp"` + OSMemory ProcessOSMemory `json:"os_memory"` + HeapAllocBytes uint64 `json:"heap_alloc_bytes"` + HeapInuseBytes uint64 `json:"heap_inuse_bytes"` + HeapIdleBytes uint64 `json:"heap_idle_bytes"` + HeapReleasedBytes uint64 `json:"heap_released_bytes"` + StackInuseBytes uint64 `json:"stack_inuse_bytes"` + MSpanInuseBytes uint64 `json:"mspan_inuse_bytes"` + MCacheInuseBytes uint64 `json:"mcache_inuse_bytes"` + OtherSysBytes uint64 `json:"other_sys_bytes"` + SysBytes uint64 `json:"sys_bytes"` + NumGC uint32 `json:"num_gc"` + HeapProfilePath string `json:"heap_profile_path"` + ModelRetainedEntries int `json:"model_retained_entries,omitempty"` + ModelRetainedBytes int64 `json:"model_retained_bytes,omitempty"` + ModelDroppedLines int `json:"model_dropped_lines,omitempty"` +} + +func capturePhaseMetrics(phaseName, description, pprofFilename string) (PhaseMetrics, error) { + _ = os.MkdirAll(profileDir, 0755) + pprofPath := filepath.Join(profileDir, pprofFilename) + + // CRITICAL: Capture runtime.MemStats and OS memory BEFORE writing the heap profile. + // Writing a gzip-compressed heap profile allocates runtime buffers and formatting + // memory which would contaminate HeapAlloc and HeapInuse if measured after. + var m runtime.MemStats + runtime.ReadMemStats(&m) + osMem := readOSMemory() + + // Write heap profile snapshot for call-site attribution + f, err := os.Create(pprofPath) + if err != nil { + return PhaseMetrics{}, fmt.Errorf("failed to create pprof file: %w", err) + } + defer f.Close() + + if err := pprof.WriteHeapProfile(f); err != nil { + return PhaseMetrics{}, fmt.Errorf("failed to write heap profile: %w", err) + } + + return PhaseMetrics{ + PhaseName: phaseName, + PhaseDescription: description, + Timestamp: time.Now().UTC().Format(time.RFC3339), + OSMemory: osMem, + HeapAllocBytes: m.HeapAlloc, + HeapInuseBytes: m.HeapInuse, + HeapIdleBytes: m.HeapIdle, + HeapReleasedBytes: m.HeapReleased, + StackInuseBytes: m.StackInuse, + MSpanInuseBytes: m.MSpanInuse, + MCacheInuseBytes: m.MCacheInuse, + OtherSysBytes: m.OtherSys, + SysBytes: m.Sys, + NumGC: m.NumGC, + HeapProfilePath: pprofPath, + }, nil +} + +// TestMemoryProfile_FreshPicker captures Phase 1: Fresh App Picker Idle. +func TestMemoryProfile_FreshPicker(t *testing.T) { + if os.Getenv("ALBEDO_MEM_PROFILE") != "1" { + t.Skip("skipping memory profiling; set ALBEDO_MEM_PROFILE=1 to run") + } + + // Fresh AppModel with no active session => Session Picker state + app := NewAppModel(nil, config.Profiles{}, nil, "/workspace/fresh", false) + newApp, _ := app.Update(tea.WindowSizeMsg{Width: 120, Height: 40}) + app = newApp.(AppModel) + _ = app.View() + + metrics, err := capturePhaseMetrics( + "fresh_picker_idle", + "Fresh AppModel in Session Picker state before loading any chat session", + "fresh_picker_heap.pb.gz", + ) + if err != nil { + t.Fatalf("failed to capture fresh picker metrics: %v", err) + } + + // Retain app alive strictly AFTER capture + runtime.KeepAlive(&app) + + data, _ := json.MarshalIndent(metrics, "", " ") + _ = os.WriteFile(filepath.Join(profileDir, "fresh_picker.json"), data, 0644) + t.Logf("=== PHASE 1: FRESH PICKER IDLE ===") + t.Logf(" RSS: %s (vmmap footprint: %.1f MB)", metrics.OSMemory.RSSFormatted, metrics.OSMemory.VMMapFootprintMB) + t.Logf(" HeapAlloc: %d B (%.2f MB), HeapInuse: %d B (%.2f MB), Sys: %d B (%.2f MB)", + metrics.HeapAllocBytes, float64(metrics.HeapAllocBytes)/(1024*1024), + metrics.HeapInuseBytes, float64(metrics.HeapInuseBytes)/(1024*1024), + metrics.SysBytes, float64(metrics.SysBytes)/(1024*1024)) +} + +// TestMemoryProfile_PostStreamStress captures Phase 2 (Natural Idle) and Phase 3 (Diagnostic Forced-GC Idle) +// under an uninterrupted 300KB+ SSE stress transcript. +func TestMemoryProfile_PostStreamStress(t *testing.T) { + if os.Getenv("ALBEDO_MEM_PROFILE") != "1" { + t.Skip("skipping memory profiling; set ALBEDO_MEM_PROFILE=1 to run") + } + + session := &daemon.Session{ID: "sess-mem-stress", Workspace: "/workspace/stress"} + app := NewAppModel(nil, config.Profiles{}, session, "/workspace/stress", false) + newApp, _ := app.Update(tea.WindowSizeMsg{Width: 120, Height: 40}) + app = newApp.(AppModel) + + // Stream 1,200 chunks of ~270 bytes each = ~325 KB (matching canonical SSE stress flow) + chunkTemplate := "assistant token chunk with code snippet `let mut ring = RingBuffer::new(4096);` and multiline buffer text for stress testing memory retention, history truncation bounds, and viewport rendering performance invariants across large scrollback buffers\n" + totalChunks := 1200 + totalStreamedBytes := 0 + + var fullStreamBuilder strings.Builder + for i := 0; i < totalChunks; i++ { + chunkText := fmt.Sprintf("[%04d] %s", i, chunkTemplate) + totalStreamedBytes += len(chunkText) + fullStreamBuilder.WriteString(chunkText) + + msg := ChatStreamEventMsg{ + SessionID: app.Chat.SessionID, + Generation: app.Chat.Generation, + Event: daemon.StreamEvent{ + Type: daemon.EventText, + Text: chunkText, + }, + } + newApp, _ := app.Update(msg) + app = newApp.(AppModel) + } + + // Settle the stream with canonical EventMessage containing the full original stream content + canonicalFullText := fullStreamBuilder.String() + settleMsg := ChatStreamEventMsg{ + SessionID: app.Chat.SessionID, + Generation: app.Chat.Generation, + Event: daemon.StreamEvent{ + Type: daemon.EventMessage, + Text: canonicalFullText, + }, + } + newApp, _ = app.Update(settleMsg) + app = newApp.(AppModel) + + // Explicitly release fixture memory references before taking snapshots + canonicalFullText = "" + fullStreamBuilder.Reset() + + // Populate rendered viewport cache + _ = app.View() + + // Verify transcript invariants + if app.Chat.activeKind != StreamKindNone { + t.Errorf("expected activeKind to be None after settle, got %v", app.Chat.activeKind) + } + if len(app.Chat.pendingUsers) != 0 { + t.Errorf("expected pendingUsers to be empty, got %d", len(app.Chat.pendingUsers)) + } + + // Let runtime settle naturally + time.Sleep(50 * time.Millisecond) + + // Phase 2: Natural Post-Stream Idle (NO forced GC; represents real runtime idle with floating garbage) + naturalMetrics, err := capturePhaseMetrics( + "post_stream_natural_idle", + "Post-stream settled state under natural Go GC (canonical 325KB stream settled, rendered cache populated, pending zero)", + "post_stream_natural_heap.pb.gz", + ) + if err != nil { + t.Fatalf("failed to capture natural post-stream metrics: %v", err) + } + naturalMetrics.ModelRetainedEntries = app.Chat.History.Len() + naturalMetrics.ModelRetainedBytes = app.Chat.History.TotalBytes() + naturalMetrics.ModelDroppedLines = app.Chat.droppedSettledLines + + // Phase 3: Diagnostic Forced-GC + Explicit FreeOSMemory Idle + // Explicitly forces full GC sweep and OS madvise return to distinguish live objects from allocator spans. + runtime.GC() + debug.FreeOSMemory() + time.Sleep(20 * time.Millisecond) + + diagnosticMetrics, err := capturePhaseMetrics( + "post_stream_diagnostic_gc_idle", + "Post-stream settled state after diagnostic runtime.GC() + debug.FreeOSMemory() to isolate true live retained objects", + "post_stream_diagnostic_gc_heap.pb.gz", + ) + if err != nil { + t.Fatalf("failed to capture diagnostic GC metrics: %v", err) + } + diagnosticMetrics.ModelRetainedEntries = app.Chat.History.Len() + diagnosticMetrics.ModelRetainedBytes = app.Chat.History.TotalBytes() + diagnosticMetrics.ModelDroppedLines = app.Chat.droppedSettledLines + + // Retain app alive strictly AFTER all captures + runtime.KeepAlive(&app) + + dataNat, _ := json.MarshalIndent(naturalMetrics, "", " ") + _ = os.WriteFile(filepath.Join(profileDir, "post_stream_natural.json"), dataNat, 0644) + + dataDiag, _ := json.MarshalIndent(diagnosticMetrics, "", " ") + _ = os.WriteFile(filepath.Join(profileDir, "post_stream_diagnostic.json"), dataDiag, 0644) + + t.Logf("=== PHASE 2: POST-STREAM NATURAL IDLE ===") + t.Logf(" Streamed: %d bytes across %d chunks", totalStreamedBytes, totalChunks) + t.Logf(" Model: %d entries (%d B), %d dropped lines", naturalMetrics.ModelRetainedEntries, naturalMetrics.ModelRetainedBytes, naturalMetrics.ModelDroppedLines) + t.Logf(" RSS: %s (vmmap footprint: %.1f MB)", naturalMetrics.OSMemory.RSSFormatted, naturalMetrics.OSMemory.VMMapFootprintMB) + t.Logf(" Allocated Heap (pre-GC): %d B (%.2f MB), HeapInuse: %d B (%.2f MB), Sys: %d B (%.2f MB)", + naturalMetrics.HeapAllocBytes, float64(naturalMetrics.HeapAllocBytes)/(1024*1024), + naturalMetrics.HeapInuseBytes, float64(naturalMetrics.HeapInuseBytes)/(1024*1024), + naturalMetrics.SysBytes, float64(naturalMetrics.SysBytes)/(1024*1024)) + + t.Logf("=== PHASE 3: POST-STREAM DIAGNOSTIC GC IDLE ===") + t.Logf(" RSS: %s (vmmap footprint: %.1f MB)", diagnosticMetrics.OSMemory.RSSFormatted, diagnosticMetrics.OSMemory.VMMapFootprintMB) + t.Logf(" Live Retained Heap (post-GC): %d B (%.2f MB), HeapInuse: %d B (%.2f MB), HeapReleased: %d B (%.2f MB)", + diagnosticMetrics.HeapAllocBytes, float64(diagnosticMetrics.HeapAllocBytes)/(1024*1024), + diagnosticMetrics.HeapInuseBytes, float64(diagnosticMetrics.HeapInuseBytes)/(1024*1024), + diagnosticMetrics.HeapReleasedBytes, float64(diagnosticMetrics.HeapReleasedBytes)/(1024*1024)) +} diff --git a/cli/internal/tui/model_picker.go b/cli/internal/tui/model_picker.go new file mode 100644 index 000000000..632390119 --- /dev/null +++ b/cli/internal/tui/model_picker.go @@ -0,0 +1,397 @@ +package tui + +import ( + "albedo/cli/internal/config" + "albedo/cli/internal/daemon" + "context" + "errors" + "fmt" + "net/url" + "sort" + "strings" + + "github.com/charmbracelet/bubbles/cursor" + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" +) + +type ModelPickerSelectMsg struct { + Model string + Provider string +} + +type ModelPickerCancelMsg struct{} + +type modelCatalogLoadedMsg struct { + Provider string + Models []string + Note string + Err error + Gen int +} + +type ModelPickerModel struct { + Conn *daemon.Connection + Profiles config.Profiles + CurrentModel string + SessionProvider string + SelectedProvider string + ChoosingProvider bool + EnteringManual bool + LoadingModels bool + Saving bool + CatalogNote string + Error string + ModelPicker PickerModel + ProviderPicker PickerModel + ManualInput textinput.Model + Generation int + Width int + Height int + Styles Styles +} + +func NewModelPickerModel(conn *daemon.Connection, profiles config.Profiles, currentModel, currentProvider string) ModelPickerModel { + provider := currentProvider + if provider == "" { + provider = profiles.Active + } + + ti := textinput.New() + ti.Cursor.SetMode(cursor.CursorStatic) + ti.Placeholder = "" + ti.Prompt = "model id: " + + m := ModelPickerModel{ + Conn: conn, + Profiles: profiles, + CurrentModel: currentModel, + SessionProvider: provider, + SelectedProvider: provider, + LoadingModels: true, + ManualInput: ti, + Styles: DefaultStyles, + } + + m.buildModelPicker(nil) + return m +} + +func (m *ModelPickerModel) SetSize(width, height int) { + m.Width = width + m.Height = height + m.ModelPicker.SetSize(width, height) + m.ProviderPicker.SetSize(width, height) + m.ManualInput.Width = max(1, width-10) +} + +func (m ModelPickerModel) Init() tea.Cmd { + return m.fetchModelsCmd(m.SelectedProvider, m.Generation) +} + +func (m ModelPickerModel) fetchModelsCmd(provider string, gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil { + return modelCatalogLoadedMsg{ + Provider: provider, + Models: nil, + Note: "daemon connection unavailable; enter a model id manually", + Gen: gen, + } + } + + settings, ok := m.Profiles.Providers[provider] + if !ok { + return modelCatalogLoadedMsg{ + Provider: provider, + Models: nil, + Note: "provider settings missing; enter a model id manually or check /login", + Gen: gen, + } + } + + providerExtension := settings.Extension + if providerExtension == "" { + providerExtension = "openai" + } + endpoint := settings.BaseURL + if providerExtension == "codex" { + endpoint = "" + } + + reqURL := fmt.Sprintf("/models/%s?endpoint=%s", providerExtension, url.QueryEscape(endpoint)) + names, err := daemon.Request[[]string](context.Background(), m.Conn, reqURL, nil) + if err != nil { + return modelCatalogLoadedMsg{ + Provider: provider, + Models: nil, + Note: "could not list models for this provider; enter a model id manually or check /login", + Err: err, + Gen: gen, + } + } + + var note string + if len(names) == 0 { + note = "no models listed; enter a model id manually" + } + + return modelCatalogLoadedMsg{ + Provider: provider, + Models: names, + Note: note, + Gen: gen, + } + } +} + +func (m *ModelPickerModel) buildProviderPicker() { + var items []PickerItem + var names []string + for name := range m.Profiles.Providers { + names = append(names, name) + } + sort.Strings(names) + + for _, name := range names { + settings := m.Profiles.Providers[name] + detail := settings.Protocol + if name == m.SessionProvider { + detail += " · current" + } + items = append(items, PickerItem{ + ID: name, + Label: name, + Detail: detail, + }) + } + + m.ProviderPicker = NewPickerModel("session provider", items, true, m.SelectedProvider) + m.ProviderPicker.SetSize(m.Width, m.Height) +} + +func (m *ModelPickerModel) buildModelPicker(catalog []string) { + initial := "" + if m.SelectedProvider == m.SessionProvider { + initial = m.CurrentModel + } + if initial == "" { + if settings, ok := m.Profiles.Providers[m.SelectedProvider]; ok { + initial = settings.Model + } + } + + seen := make(map[string]bool) + var models []string + if initial != "" { + seen[initial] = true + models = append(models, initial) + } + for _, name := range catalog { + if !seen[name] && name != "" { + seen[name] = true + models = append(models, name) + } + } + + var items []PickerItem + items = append(items, PickerItem{ + ID: "provider", + Label: "change provider", + Detail: m.SelectedProvider, + }) + + for _, model := range models { + detail := "" + if model == m.CurrentModel && m.SelectedProvider == m.SessionProvider { + detail = "current" + } + items = append(items, PickerItem{ + ID: "model:" + model, + Label: model, + Detail: detail, + }) + } + + items = append(items, PickerItem{ + ID: "manual", + Label: "enter model id manually", + Detail: "", + }) + + initialSel := "model:" + initial + m.ModelPicker = NewPickerModel("session model", items, true, initialSel) + m.ModelPicker.SetSize(m.Width, m.Height) +} + +func validateModelID(m string) error { + m = strings.TrimSpace(m) + if m == "" || jsLength(m) > 512 { + return errors.New("enter a model id of 1–512 characters") + } + for _, r := range m { + if r < 0x20 || r == 0x7f { + return errors.New("enter a model id of 1–512 characters") + } + } + return nil +} + +func (m ModelPickerModel) Update(msg tea.Msg) (ModelPickerModel, tea.Cmd) { + if m.Saving { + if _, ok := msg.(tea.KeyMsg); ok { + return m, nil + } + } + switch msg := msg.(type) { + case modelCatalogLoadedMsg: + if msg.Gen != m.Generation || msg.Provider != m.SelectedProvider { + return m, nil + } + m.LoadingModels = false + m.CatalogNote = msg.Note + m.buildModelPicker(msg.Models) + return m, m.ModelPicker.Init() + + case tea.KeyMsg: + if m.EnteringManual { + switch msg.Type { + case tea.KeyEsc, tea.KeyCtrlC, tea.KeyCtrlD: + return m, func() tea.Msg { return ModelPickerCancelMsg{} } + case tea.KeyEnter: + val := strings.TrimSpace(m.ManualInput.Value()) + if err := validateModelID(val); err != nil { + m.Error = err.Error() + return m, nil + } + m.Error = "" + return m, func() tea.Msg { + return ModelPickerSelectMsg{ + Model: val, + Provider: m.SelectedProvider, + } + } + } + var cmd tea.Cmd + m.ManualInput, cmd = m.ManualInput.Update(msg) + return m, cmd + } + + if msg.Type == tea.KeyCtrlC || msg.Type == tea.KeyCtrlD { + return m, func() tea.Msg { return ModelPickerCancelMsg{} } + } + + case PickerSelectMsg: + if m.ChoosingProvider { + m.SelectedProvider = msg.ID + m.ChoosingProvider = false + m.LoadingModels = true + m.CatalogNote = "" + m.buildModelPicker(nil) + m.Error = "" + m.Generation++ + return m, m.fetchModelsCmd(m.SelectedProvider, m.Generation) + } + + switch { + case msg.ID == "provider": + m.ChoosingProvider = true + m.buildProviderPicker() + return m, m.ProviderPicker.Init() + + case msg.ID == "manual": + m.EnteringManual = true + m.ManualInput.Reset() + initial := "" + if m.SelectedProvider == m.SessionProvider { + initial = m.CurrentModel + } + if initial == "" { + if settings, ok := m.Profiles.Providers[m.SelectedProvider]; ok { + initial = settings.Model + } + } + m.ManualInput.SetValue(initial) + m.ManualInput.Focus() + m.Error = "" + return m, textinput.Blink + + case strings.HasPrefix(msg.ID, "model:"): + modelName := strings.TrimPrefix(msg.ID, "model:") + if err := validateModelID(modelName); err != nil { + m.Error = err.Error() + return m, nil + } + m.Error = "" + return m, func() tea.Msg { + return ModelPickerSelectMsg{ + Model: modelName, + Provider: m.SelectedProvider, + } + } + } + + case PickerCancelMsg: + if m.ChoosingProvider { + m.ChoosingProvider = false + return m, nil + } + return m, func() tea.Msg { return ModelPickerCancelMsg{} } + } + + var cmd tea.Cmd + if m.ChoosingProvider { + m.ProviderPicker, cmd = m.ProviderPicker.Update(msg) + } else if !m.EnteringManual { + m.ModelPicker, cmd = m.ModelPicker.Update(msg) + } + return m, cmd +} + +func (m ModelPickerModel) View() string { + var b strings.Builder + + titleProvider := m.SelectedProvider + if titleProvider == "" { + titleProvider = "session provider" + } + b.WriteString(fmt.Sprintf("albedo /model · %s", titleProvider)) + b.WriteString("\n") + b.WriteString(m.Styles.Dim.Render(inkWrap("changes this idle session and the default for new sessions", m.Width))) + b.WriteByte('\n') + + if m.Error != "" { + b.WriteString(inkRed.Render(m.Error)) + b.WriteByte('\n') + } + + if m.Saving { + b.WriteString(m.Styles.Dim.Render("switching model…")) + return b.String() + } + + if m.ChoosingProvider { + b.WriteString(m.ProviderPicker.View()) + return b.String() + } + + if m.EnteringManual { + b.WriteString(m.ManualInput.View()) + b.WriteByte('\n') + b.WriteString(m.Styles.Dim.Render("enter choose · esc cancel")) + return b.String() + } + + if m.LoadingModels { + b.WriteString(m.Styles.Dim.Render("loading models…")) + b.WriteByte('\n') + } + + if m.CatalogNote != "" { + b.WriteString(m.Styles.Dim.Render(inkWrap(m.CatalogNote, m.Width))) + b.WriteByte('\n') + } + + b.WriteString(m.ModelPicker.View()) + return b.String() +} diff --git a/cli/internal/tui/page_view.go b/cli/internal/tui/page_view.go new file mode 100644 index 000000000..59a13b602 --- /dev/null +++ b/cli/internal/tui/page_view.go @@ -0,0 +1,641 @@ +package tui + +import ( + "albedo/cli/internal/daemon" + "context" + "errors" + "fmt" + "strings" + + "github.com/charmbracelet/bubbles/cursor" + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" +) + +type PageTone string + +const ( + TonePlain PageTone = "plain" + ToneActive PageTone = "active" + ToneWarning PageTone = "warning" + ToneMuted PageTone = "muted" +) + +type PageRow struct { + ID string `json:"id"` + Text string `json:"text"` + Badge string `json:"badge"` + Tone PageTone `json:"tone"` +} + +type PageAction struct { + Key string `json:"key"` + Label string `json:"label"` + Run string `json:"run"` + Row bool `json:"row"` + Confirm bool `json:"confirm"` + Input string `json:"input"` // "none" | "text" | "choice" | "value" + Prompt string `json:"prompt,omitempty"` + Prefill bool `json:"prefill,omitempty"` + Options []string `json:"options,omitempty"` + Value string `json:"value,omitempty"` +} + +type PageGlance struct { + Title string `json:"title"` + Rows []PageRow `json:"rows"` +} + +type PageDocument struct { + Title string `json:"title"` + Summary string `json:"summary"` + Empty string `json:"empty"` + Rows []PageRow `json:"rows"` + Actions []PageAction `json:"actions"` + Glance *PageGlance `json:"glance,omitempty"` +} + +type PageCancelMsg struct{} +type PageViewChangedMsg struct{} + +type pageLoadedMsg struct { + Doc *PageDocument + Err error + Gen int +} + +type pageActionExecutedMsg struct { + Result map[string]any + Action PageAction + Err error + Gen int +} + +type pageModeKind int + +const ( + modeBrowse pageModeKind = iota + modeText + modeChoice + modeConfirm +) + +type PageViewModel struct { + Conn *daemon.Connection + SessionID string + Command string + Doc *PageDocument + SelectedID string + Mode pageModeKind + CurrentAction *PageAction + ChoiceIndex int + TextInput textinput.Model + Busy bool + Notice string + Error string + Generation int + Width int + Height int + Styles Styles +} + +func NewPageViewModel(conn *daemon.Connection, sessionID, command string) PageViewModel { + ti := textinput.New() + ti.Cursor.SetMode(cursor.CursorStatic) + ti.Prompt = "" + return PageViewModel{ + Conn: conn, + SessionID: sessionID, + Command: command, + TextInput: ti, + Busy: true, + Styles: DefaultStyles, + } +} + +func (m *PageViewModel) SetSize(width, height int) { + m.Width = width + m.Height = height + m.TextInput.Width = max(10, width-20) +} + +func (m PageViewModel) Init() tea.Cmd { + return m.loadPageCmd(m.Generation) +} + +func parsePageDocument(result any) (*PageDocument, error) { + response, ok := result.(map[string]any) + if !ok { + return nil, errors.New("command did not answer a page") + } + page, ok := response["page"].(map[string]any) + if !ok { + return nil, errors.New("command did not answer a page") + } + title, ok := page["title"].(string) + if !ok { + return nil, errors.New("command did not answer a page") + } + doc := &PageDocument{Title: title, Empty: "nothing here yet"} + if summary, ok := page["summary"].(string); ok { + doc.Summary = summary + } + if empty, ok := page["empty"].(string); ok { + doc.Empty = empty + } + parseRows := func(raw any) []PageRow { + result := []PageRow{} + entries, _ := raw.([]any) + for _, entry := range entries { + obj, ok := entry.(map[string]any) + if !ok { + continue + } + id, idOK := obj["id"].(string) + text, textOK := obj["text"].(string) + badge, badgeOK := obj["badge"].(string) + if !idOK || !textOK || !badgeOK { + continue + } + tone, _ := obj["tone"].(string) + if tone != "plain" && tone != "active" && tone != "warning" && tone != "muted" { + tone = "plain" + } + result = append(result, PageRow{ID: id, Text: text, Badge: badge, Tone: PageTone(tone)}) + } + return result + } + doc.Rows = parseRows(page["rows"]) + if raw, ok := page["actions"].([]any); ok { + for _, entry := range raw { + obj, ok := entry.(map[string]any) + if !ok { + continue + } + key, keyOK := obj["key"].(string) + label, labelOK := obj["label"].(string) + run, runOK := obj["run"].(string) + if !keyOK || len([]rune(key)) != 1 || !labelOK || !runOK { + continue + } + action := PageAction{Key: key, Label: label, Run: run, Row: obj["row"] == true, Confirm: obj["confirm"] == true, Input: "none"} + kind, _ := obj["input"].(string) + switch kind { + case "text": + action.Input = "text" + action.Prompt = label + if prompt, ok := obj["prompt"].(string); ok { + action.Prompt = prompt + } + action.Prefill = obj["prefill"] == true + case "choice": + choices, ok := obj["options"].([]any) + if !ok || len(choices) == 0 { + continue + } + action.Input = "choice" + for _, raw := range choices { + value, ok := raw.(string) + if !ok { + action.Options = nil + break + } + action.Options = append(action.Options, value) + } + if len(action.Options) != len(choices) { + continue + } + case "value": + value, ok := obj["value"].(string) + if !ok { + continue + } + action.Input = "value" + action.Value = value + } + doc.Actions = append(doc.Actions, action) + } + } + if glance, ok := page["glance"].(map[string]any); ok { + if title, ok := glance["title"].(string); ok { + doc.Glance = &PageGlance{Title: title, Rows: parseRows(glance["rows"])} + } + } + return doc, nil +} + +func (m PageViewModel) loadPageCmd(gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil { + return pageLoadedMsg{Err: errors.New("daemon connection unavailable"), Gen: gen} + } + path := fmt.Sprintf("/sessions/%s/commands", m.SessionID) + body := map[string]any{"name": m.Command, "args": map[string]string{}} + res, err := daemon.Request[map[string]any](context.Background(), m.Conn, path, body) + if err != nil { + return pageLoadedMsg{Err: err, Gen: gen} + } + + var targetObj any = res + if r, ok := res["result"]; ok && r != nil { + targetObj = r + } + doc, err := parsePageDocument(targetObj) + if err != nil { + err = fmt.Errorf("%s did not answer a page", m.Command) + } + return pageLoadedMsg{Doc: doc, Err: err, Gen: gen} + } +} + +func (m PageViewModel) executeActionCmd(act PageAction, row *PageRow, entered string, gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil { + return pageActionExecutedMsg{Action: act, Err: errors.New("daemon connection unavailable"), Gen: gen} + } + + val := entered + if act.Input == "value" { + val = act.Value + } + + var detailsParts []string + if act.Row && row != nil { + detailsParts = append(detailsParts, row.ID) + } + if val != "" { + detailsParts = append(detailsParts, val) + } + details := strings.Join(detailsParts, " ") + + path := fmt.Sprintf("/sessions/%s/commands", m.SessionID) + body := map[string]any{ + "name": m.Command, + "args": map[string]string{ + "action": act.Run, + "details": details, + }, + } + + res, err := daemon.Request[map[string]any](context.Background(), m.Conn, path, body) + return pageActionExecutedMsg{Result: res, Action: act, Err: err, Gen: gen} + } +} + +func (m PageViewModel) currentRow() *PageRow { + if m.Doc == nil || len(m.Doc.Rows) == 0 { + return nil + } + for i := range m.Doc.Rows { + if m.Doc.Rows[i].ID == m.SelectedID { + return &m.Doc.Rows[i] + } + } + return &m.Doc.Rows[0] +} + +func (m PageViewModel) currentIndex() int { + if m.Doc == nil || len(m.Doc.Rows) == 0 { + return 0 + } + for i := range m.Doc.Rows { + if m.Doc.Rows[i].ID == m.SelectedID { + return i + } + } + return 0 +} + +func (m PageViewModel) Update(msg tea.Msg) (PageViewModel, tea.Cmd) { + switch msg := msg.(type) { + case pageLoadedMsg: + if msg.Gen != m.Generation { + return m, nil + } + m.Busy = false + if msg.Err != nil { + m.Error = msg.Err.Error() + return m, nil + } + m.Doc = msg.Doc + m.Error = "" + if m.currentRow() != nil { + m.SelectedID = m.currentRow().ID + } + return m, nil + + case pageActionExecutedMsg: + if msg.Gen != m.Generation { + return m, nil + } + m.Busy = false + if msg.Err != nil { + m.Error = msg.Err.Error() + return m, nil + } + + // Notice from result or action label + notice := fmt.Sprintf("%s done", msg.Action.Label) + if msg.Result != nil { + if r, ok := msg.Result["result"].(map[string]any); ok { + if msgStr, ok := r["message"].(string); ok && msgStr != "" { + notice = msgStr + } + } else if msgStr, ok := msg.Result["message"].(string); ok && msgStr != "" { + notice = msgStr + } + } + m.Notice = notice + m.Error = "" + + // Reload page and notify changed + m.Busy = true + m.Generation++ + return m, tea.Batch( + func() tea.Msg { return PageViewChangedMsg{} }, + m.loadPageCmd(m.Generation), + ) + + case tea.KeyMsg: + if msg.Type == tea.KeyCtrlC || msg.Type == tea.KeyEsc { + if m.Mode == modeBrowse { + return m, func() tea.Msg { return PageCancelMsg{} } + } + m.Mode = modeBrowse + m.CurrentAction = nil + return m, nil + } + + if m.Busy { + return m, nil + } + + if m.Doc == nil { + if strings.ToLower(msg.String()) == "r" { + m.Busy = true + m.Error = "" + m.Generation++ + return m, m.loadPageCmd(m.Generation) + } + return m, nil + } + + switch m.Mode { + case modeConfirm: + if msg.Type == tea.KeyEnter && m.CurrentAction != nil { + act := *m.CurrentAction + m.CurrentAction = nil + m.Mode = modeBrowse + // If action still needs text or choice, collect it + switch act.Input { + case "text": + m.Mode = modeText + m.CurrentAction = &act + m.TextInput.Reset() + if act.Prefill && m.currentRow() != nil { + m.TextInput.SetValue(m.currentRow().Text) + } + m.TextInput.Focus() + return m, textinput.Blink + case "choice": + m.Mode = modeChoice + m.CurrentAction = &act + m.ChoiceIndex = 0 + if row := m.currentRow(); row != nil { + for i, opt := range act.Options { + if opt == row.Badge { + m.ChoiceIndex = i + break + } + } + } + return m, nil + default: + m.Busy = true + m.Error = "" + m.Notice = "" + m.Generation++ + return m, m.executeActionCmd(act, m.currentRow(), "", m.Generation) + } + } + return m, nil + + case modeChoice: + if m.CurrentAction != nil && len(m.CurrentAction.Options) > 0 { + numOpts := len(m.CurrentAction.Options) + switch msg.Type { + case tea.KeyLeft, tea.KeyUp: + m.ChoiceIndex = (m.ChoiceIndex - 1 + numOpts) % numOpts + case tea.KeyRight, tea.KeyDown: + m.ChoiceIndex = (m.ChoiceIndex + 1) % numOpts + case tea.KeyEnter: + act := *m.CurrentAction + chosenOpt := act.Options[m.ChoiceIndex] + m.CurrentAction = nil + m.Mode = modeBrowse + m.Busy = true + m.Error = "" + m.Notice = "" + m.Generation++ + return m, m.executeActionCmd(act, m.currentRow(), chosenOpt, m.Generation) + } + } + return m, nil + + case modeText: + switch msg.Type { + case tea.KeyEnter: + val := strings.TrimSpace(m.TextInput.Value()) + if val != "" && m.CurrentAction != nil { + act := *m.CurrentAction + m.CurrentAction = nil + m.Mode = modeBrowse + m.Busy = true + m.Error = "" + m.Notice = "" + m.Generation++ + return m, m.executeActionCmd(act, m.currentRow(), val, m.Generation) + } + return m, nil + } + var cmd tea.Cmd + m.TextInput, cmd = m.TextInput.Update(msg) + return m, cmd + + case modeBrowse: + idx := m.currentIndex() + switch msg.Type { + case tea.KeyUp, tea.KeyCtrlP: + if idx > 0 { + m.SelectedID = m.Doc.Rows[idx-1].ID + } + case tea.KeyDown, tea.KeyCtrlN: + if idx < len(m.Doc.Rows)-1 { + m.SelectedID = m.Doc.Rows[idx+1].ID + } + default: + // Match action key + keyStr := msg.String() + for _, act := range m.Doc.Actions { + if act.Key == keyStr { + actionCopy := act + if actionCopy.Row && m.currentRow() == nil { + continue + } + m.Notice = "" + m.Error = "" + + if actionCopy.Confirm { + m.Mode = modeConfirm + m.CurrentAction = &actionCopy + return m, nil + } + + switch actionCopy.Input { + case "text": + m.Mode = modeText + m.CurrentAction = &actionCopy + m.TextInput.Reset() + if actionCopy.Prefill && m.currentRow() != nil { + m.TextInput.SetValue(m.currentRow().Text) + } + m.TextInput.Focus() + return m, textinput.Blink + case "choice": + m.Mode = modeChoice + m.CurrentAction = &actionCopy + m.ChoiceIndex = 0 + if m.currentRow() != nil { + for optIdx, opt := range actionCopy.Options { + if opt == m.currentRow().Badge { + m.ChoiceIndex = optIdx + break + } + } + } + return m, nil + default: + m.Busy = true + m.Generation++ + return m, m.executeActionCmd(actionCopy, m.currentRow(), "", m.Generation) + } + } + } + } + } + } + return m, nil +} + +func (m PageViewModel) View() string { + var b strings.Builder + line := func(text string) { b.WriteString(text); b.WriteByte('\n') } + faint := func(text string) { line(m.Styles.Dim.Render(text)) } + title := "albedo " + m.Command + if m.Doc != nil && m.Doc.Summary != "" { + title += " · " + m.Doc.Summary + } + line(title) + if m.Error != "" { + line(inkRed.Render(m.Error)) + } + if m.Notice != "" && m.Error == "" { + line(inkBrightCyan.Render(m.Notice)) + } + if m.Doc == nil { + if m.Error != "" { + faint("r retry · esc return to chat") + } else { + faint("loading " + m.Command + "…") + } + return strings.TrimSuffix(b.String(), "\n") + } + row := m.currentRow() + if len(m.Doc.Rows) == 0 { + faint(m.Doc.Empty) + } else { + rows := make([]string, len(m.Doc.Rows)) + for i, item := range m.Doc.Rows { + var style lipgloss.Style + switch item.Tone { + case ToneActive: + style = inkGreen + case ToneWarning: + style = inkYellow + case ToneMuted: + style = m.Styles.Faint + default: + style = lipgloss.NewStyle() + } + rows[i] = style.Render(fmt.Sprintf("%-9s", item.Badge)) + " " + item.Text + if item.ID != item.Text { + rows[i] += lipgloss.NewStyle().Faint(true).Render(" #" + item.ID) + } + } + line(selectableRows(rows, m.currentIndex(), m.Height, m.Height, m.Width, m.Styles)) + } + target := "" + if row != nil { + if row.ID == row.Text { + target = " " + row.Text + } else { + target = fmt.Sprintf(" #%s %s", row.ID, row.Text) + } + } + if m.CurrentAction != nil { + act := m.CurrentAction + actionTarget := "" + if act.Row { + actionTarget = target + } + switch m.Mode { + case modeConfirm: + line(inkYellow.Render(act.Label + actionTarget + "? enter confirm · esc cancel")) + case modeChoice: + var choice strings.Builder + choice.WriteString(inkBrightCyan.Render(act.Label + target + " › ")) + for i, opt := range act.Options { + label := " " + opt + " " + if i == m.ChoiceIndex { + label = m.Styles.Selected.Render(label) + } + choice.WriteString(label) + } + line(choice.String()) + case modeText: + prompt := act.Prompt + if prompt == "" { + prompt = act.Label + } + b.WriteString(inkBrightCyan.Render(act.Label + actionTarget + " · " + prompt + " › ")) + line(m.TextInput.View()) + } + } + var hints []string + switch { + case m.Busy: + hints = []string{"working…"} + case m.Mode == modeBrowse: + if len(m.Doc.Rows) > 1 { + hints = append(hints, "↑↓ select") + } + for _, act := range m.Doc.Actions { + if !act.Row || row != nil { + hints = append(hints, act.Key+" "+act.Label) + } + } + hints = append(hints, "esc return to chat") + case m.Mode == modeText: + hints = []string{"enter save · esc cancel"} + case m.Mode == modeChoice: + hints = []string{"←→ choose · enter apply · esc cancel"} + } + footer := strings.Join(hints, " · ") + if m.Width > 0 { + footer = ansi.Truncate(footer, m.Width, "…") + } + faint(footer) + return strings.TrimSuffix(b.String(), "\n") +} diff --git a/cli/internal/tui/picker.go b/cli/internal/tui/picker.go new file mode 100644 index 000000000..eeba11858 --- /dev/null +++ b/cli/internal/tui/picker.go @@ -0,0 +1,220 @@ +package tui + +import ( + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + "strings" + + "github.com/charmbracelet/bubbles/cursor" + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" +) + +type PickerItem struct { + ID string + Label string + Detail string +} + +type PickerSelectMsg struct { + ID string +} + +type PickerCancelMsg struct{} + +type PickerModel struct { + Title string + Items []PickerItem + Filtered []PickerItem + Cursor int + SearchInput textinput.Model + WithSearch bool + Width int + Height int + Styles Styles +} + +func NewPickerModel(title string, items []PickerItem, withSearch bool, initialSelection string) PickerModel { + ti := textinput.New() + ti.Cursor.SetMode(cursor.CursorStatic) + ti.Placeholder = "" + ti.Focus() + ti.Prompt = "" + + m := PickerModel{ + Title: title, + Items: items, + WithSearch: withSearch, + SearchInput: ti, + Styles: DefaultStyles, + } + m.applyFilter() + + if initialSelection != "" { + for i, item := range m.Filtered { + if item.ID == initialSelection { + m.Cursor = i + break + } + } + } + + return m +} + +func (m *PickerModel) SetSize(width, height int) { + m.Width = width + m.Height = height + m.SearchInput.Width = max(1, width-8) +} + +func (m *PickerModel) applyFilter() { + old := "" + if m.Cursor >= 0 && m.Cursor < len(m.Filtered) { + old = m.Filtered[m.Cursor].ID + } + tokens := strings.Fields(strings.ToLower(m.SearchInput.Value())) + m.Filtered = nil + for _, item := range m.Items { + haystack := strings.ToLower(item.ID + " " + item.Label + " " + item.Detail) + found := true + for _, token := range tokens { + if !strings.Contains(haystack, token) { + found = false + break + } + } + if found { + m.Filtered = append(m.Filtered, item) + } + } + m.Cursor = 0 + for i, item := range m.Filtered { + if item.ID == old { + m.Cursor = i + break + } + } +} + +// selectableRows shares Ink's bottom-anchored list window and full-row inverse marker. +func inkWrap(text string, width int) string { + if width <= 0 { + return text + } + return ansi.Wrap(text, width, " ") +} + +var inkRed = lipgloss.NewStyle().Foreground(lipgloss.Color("1")) +var inkYellow = lipgloss.NewStyle().Foreground(lipgloss.Color("3")) +var inkGreen = lipgloss.NewStyle().Foreground(lipgloss.Color("2")) +var inkCyan = lipgloss.NewStyle().Foreground(lipgloss.Color("6")) +var inkBrightCyan = lipgloss.NewStyle().Foreground(lipgloss.Color("14")) + +func selectableRows(lines []string, selected, height, limit, width int, styles Styles) string { + if height <= 0 { + height = 24 + } + if limit <= 0 { + limit = height + } + available := max(1, min(limit, height-8)) + first := min(max(0, selected-available+1), max(0, len(lines)-available)) + if len(lines) == 0 { + return styles.Dim.Render("no matches") + } + var b strings.Builder + for i := first; i < min(len(lines), first+available); i++ { + prefix := " " + if i == selected { + prefix = "> " + } + line := prefix + lines[i] + if width > 0 { + line = ansi.Truncate(line, width, "…") + } + if i == selected { + line = "\x1b[7m" + strings.ReplaceAll(line, "\x1b[0m", "\x1b[0m\x1b[7m") + "\x1b[0m" + } + if i > first { + b.WriteByte('\n') + } + b.WriteString(line) + } + return b.String() +} + +func pickerRow(item PickerItem, styles Styles) string { + line := item.Label + if item.Detail != "" { + line += lipgloss.NewStyle().Faint(true).Render(" " + item.Detail) + } + return line +} + +func (m PickerModel) Init() tea.Cmd { + if m.WithSearch { + return textinput.Blink + } + return nil +} + +func (m PickerModel) Update(msg tea.Msg) (PickerModel, tea.Cmd) { + var cmd tea.Cmd + + switch msg := msg.(type) { + case tea.KeyMsg: + switch msg.Type { + case tea.KeyEsc, tea.KeyCtrlC, tea.KeyCtrlD: + return m, func() tea.Msg { return PickerCancelMsg{} } + case tea.KeyEnter: + if len(m.Filtered) > 0 && m.Cursor < len(m.Filtered) { + selectedID := m.Filtered[m.Cursor].ID + return m, func() tea.Msg { return PickerSelectMsg{ID: selectedID} } + } + return m, nil + case tea.KeyUp, tea.KeyCtrlP: + if m.Cursor > 0 { + m.Cursor-- + } + return m, nil + case tea.KeyDown, tea.KeyCtrlN: + if m.Cursor < len(m.Filtered)-1 { + m.Cursor++ + } + return m, nil + } + } + + if m.WithSearch { + var tiCmd tea.Cmd + m.SearchInput, tiCmd = m.SearchInput.Update(msg) + m.applyFilter() + cmd = tea.Batch(cmd, tiCmd) + } + + return m, cmd +} + +func (m PickerModel) View() string { + var b strings.Builder + if m.Title != "" { + b.WriteString(m.Title) + b.WriteByte('\n') + } + lines := make([]string, len(m.Filtered)) + for i, item := range m.Filtered { + lines[i] = pickerRow(item, m.Styles) + } + b.WriteString(selectableRows(lines, m.Cursor, m.Height, m.Height, m.Width, m.Styles)) + b.WriteByte('\n') + if m.WithSearch { + b.WriteString(m.Styles.Dim.Render("search: ")) + b.WriteString(m.SearchInput.View()) + } else { + b.WriteString(m.Styles.Selected.Render(" ")) + } + b.WriteByte('\n') + b.WriteString(m.Styles.Dim.Render("↑↓ select · enter choose · esc cancel")) + return b.String() +} diff --git a/cli/internal/tui/scroll_perf_test.go b/cli/internal/tui/scroll_perf_test.go new file mode 100644 index 000000000..20887548e --- /dev/null +++ b/cli/internal/tui/scroll_perf_test.go @@ -0,0 +1,930 @@ +package tui + +import ( + "albedo/cli/internal/daemon" + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "math" + "os" + "runtime" + "runtime/debug" + "sort" + "sync" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/mattn/go-isatty" +) + +// Fixture generators for dense markdown, fenced code, multi-file diffs, CJK, and ANSI. + +func generateMarkdownFixture() string { + return `### Architectural Invariants: Concurrent Scrollback Engine + +When optimizing the **TUI terminal pipeline**, several critical invariants must hold: +1. *Zero mutation* during read passes. +2. Direct index slicing rather than linear allocations where possible. +3. Strict bounds enforcement against memory leaks. + +> "Premature optimization is the root of all evil, but unmeasured scrolling latency destroys user trust faster than functional bugs." + +| Subsystem | Target Latency | Budget (120Hz) | Budget (60Hz) | +| :--- | :--- | :--- | :--- | +| Update (State) | < 0.50 ms | 8.33 ms | 16.67 ms | +| View (Diff/Format) | < 3.00 ms | 8.33 ms | 16.67 ms | +| Emission (PTY) | < 2.00 ms | 8.33 ms | 16.67 ms | +` +} + +func generateFencedCodeFixture() string { + return `Here is the concurrent ring buffer implementation in Rust: + +` + "```go" + ` +package ringbuf + +import "sync/atomic" + +type RingBuffer[T any] struct { + buffer []T + head atomic.Uint64 + tail atomic.Uint64 + mask uint64 +} + +func NewRingBuffer[T any](size int) *RingBuffer[T] { + return &RingBuffer[T]{buffer: make([]T, size), mask: uint64(size - 1)} +} +` + "```" + ` + +And the consumer routine: + +` + "```py" + ` +class BatchProcessor: + def __init__(self, capacity: int): + self.capacity = capacity + self.queue = [] + + async def drain(self) -> list: + items = list(self.queue) + self.queue.clear() + return items +` + "```" +} + +func generateMultiFileToolTrace() *daemon.ToolTrace { + diff1 := `@@ -370,12 +370,18 @@ func (m *ChatModel) refreshViewportContent() { +- m.scrollOffset = max(0, min(m.scrollOffset, maxScroll)) +- end := min(totalLines, m.scrollOffset+vpHeight) +- if m.scrollOffset < end { +- visibleSlice = allLines[m.scrollOffset:end] +- } ++ start := clamp(m.scrollOffset, 0, maxScroll) ++ end := clamp(start+vpHeight, start, totalLines) ++ visibleSlice = allLines[start:end] ++ m.Viewport.SetContent(strings.Join(visibleSlice, " +")) +@@ -485,6 +491,10 @@ func (m ChatModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { ++ case tea.KeyPgUp: ++ m.scrollOffset = max(0, m.scrollOffset-m.Viewport.Height) ++ m.refreshViewportContent() ++ return m, nil` + + diff2 := `@@ -65,6 +65,12 @@ func (r TranscriptRenderer) RenderToolTrace ++ if flags.Diffs { ++ b.WriteString(r.RenderDiff(ch.Diff, width)) ++ }` + + return &daemon.ToolTrace{ + Activities: []daemon.ToolActivity{ + {Kind: "search", Target: "refreshViewportContent"}, + {Kind: "read", Target: "cli/internal/tui/chat.go"}, + {Kind: "diff", Target: "git diff HEAD"}, + }, + Changes: []daemon.FileChange{ + { + Path: "cli/internal/tui/chat.go", + Kind: "diff", + Added: 12, + Removed: 5, + Diff: diff1, + }, + { + Path: "cli/internal/tui/transcript.go", + Kind: "diff", + Added: 6, + Removed: 0, + Diff: diff2, + }, + }, + } +} + +func generateCJKFixture() string { + return `## 多言語表示・端末セル幅検証 (CJK Width & Unicode uniseg) + +日本語の長いテキスト: +吾輩は猫である。名前はまだ無い。どこで生れたかとんと見当がつかぬ。何でも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。吾輩はここで始めて人間というものを見た。 + +中文测试段落: +道可道,非常道。名可名,非常名。无名天地之始;有名万物之母。故常无欲,以观其妙;常有欲,以观其徼。此两者,同出而异名,同谓之玄。 + +한국어 성능 테스트 문場: +동해 물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라 만세. 무궁화 삼천리 화려 강산 대한 사람 대한으로 길이 보전하세. +` +} + +func generateAnsiFixture() string { + return "\x1b[38;5;196m[FATAL ERROR]\x1b[0m \x1b[1;33mExecution halted:\x1b[0m check /var/log/kernel.log for details.\n" + + "\x1b[38;5;46m[SUCCESS]\x1b[0m \x1b[32mRendered\x1b[0m 1024 frames in 8.12ms (123.15 Hz).\n" + + "\x1b[38;5;39m[INFO]\x1b[0m Memory stable at 4.2MB heap in-use.\n" +} + +// buildRealisticHistory populates ChatModel with entries exceeding MaxSettledLines +// and MaxSettledLinesBytes with fully expanded flags and deterministic timestamps. +func buildRealisticHistory(m *ChatModel) (appendedCount int, totalBytesAppended int64) { + // Enable ALL visual elements to guarantee worst-case rendering complexity + m.Flags = DisplayFlags{ + Thinking: true, + Tools: true, + Diffs: true, + Compaction: true, + } + + fixtures := []struct { + kind EntryKind + text string + }{ + {EntryUser, "Show me the architectural diff for the scrollback engine, fenced code, and include CJK tests."}, + {EntryThinking, "Analyzing viewport slice performance, rune width metrics, and ANSI diffing overhead across viewports..."}, + {EntryAssistant, generateMarkdownFixture()}, + {EntryTool, "Executed git diff with multi-file inspection"}, + {EntryAssistant, generateFencedCodeFixture()}, + {EntryAssistant, generateCJKFixture()}, + {EntryNote, generateAnsiFixture()}, + {EntryCompacted, "Historical conversation summary checkpoint"}, + } + + // Deterministic base timestamp in milliseconds (2024-03-10 12:00:00 UTC) + baseTimestampMs := int64(1710072000000) + + for { + item := fixtures[appendedCount%len(fixtures)] + entry := HistoryEntry{ + Kind: item.kind, + Speaker: "albedo", + Text: fmt.Sprintf("[%d] %s", appendedCount+1, item.text), + Timestamp: baseTimestampMs + int64(appendedCount*60000), // fixed deterministic 1-minute increments + } + if item.kind == EntryTool { + entry.ToolName = "git_diff" + entry.ToolTrace = generateMultiFileToolTrace() + entry.ToolResult = "diff complete: 2 files changed, 18 insertions(+), 5 deletions(-)" + } + + m.appendSettledEntry(entry) + appendedCount++ + totalBytesAppended += int64(len(entry.Text)) + + // Stop when history has exceeded the retention bounds and dropped lines + if m.droppedSettledLines > 0 && len(m.settledLines) >= MaxSettledLines { + break + } + if appendedCount > 500 { + break + } + } + return appendedCount, totalBytesAppended +} + +type LatencyDistribution struct { + Count int `json:"count"` + Min time.Duration `json:"min_ns"` + Mean time.Duration `json:"mean_ns"` + Median time.Duration `json:"p50_ns"` + P90 time.Duration `json:"p90_ns"` + P95 time.Duration `json:"p95_ns"` + P99 time.Duration `json:"p99_ns"` + Max time.Duration `json:"max_ns"` + StdDev time.Duration `json:"stddev_ns"` + PctUnder120 float64 `json:"pct_under_120hz"` + PctUnder60 float64 `json:"pct_under_60hz"` +} + +func calcDistribution(samples []time.Duration) LatencyDistribution { + n := len(samples) + if n == 0 { + return LatencyDistribution{} + } + sorted := make([]time.Duration, n) + copy(sorted, samples) + sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] }) + + var sum int64 + var under120, under60 int + budget120 := 8333333 * time.Nanosecond + budget60 := 16666667 * time.Nanosecond + + for _, s := range sorted { + sum += int64(s) + if s <= budget120 { + under120++ + } + if s <= budget60 { + under60++ + } + } + mean := time.Duration(sum / int64(n)) + + var varianceSum float64 + for _, s := range sorted { + diff := float64(s - mean) + varianceSum += diff * diff + } + stdDev := time.Duration(math.Sqrt(varianceSum / float64(n))) + + p := func(pct float64) time.Duration { + idx := int(float64(n-1) * pct) + return sorted[idx] + } + + return LatencyDistribution{ + Count: n, + Min: sorted[0], + Mean: mean, + Median: p(0.50), + P90: p(0.90), + P95: p(0.95), + P99: p(0.99), + Max: sorted[n-1], + StdDev: stdDev, + PctUnder120: float64(under120) * 100.0 / float64(n), + PctUnder60: float64(under60) * 100.0 / float64(n), + } +} + +type ScenarioResult struct { + Name string `json:"name"` + Width int `json:"width"` + Height int `json:"height"` + Streaming bool `json:"streaming"` + RetainedLines int `json:"retained_lines"` + RetainedBytes int64 `json:"retained_bytes"` + DroppedLines int `json:"dropped_lines"` + AppendedEntries int `json:"appended_entries"` + UniqueViewHashes int `json:"unique_view_hashes"` + UniqueOffsetsVisited int `json:"unique_offsets_visited"` + TotalScrollSteps int `json:"total_scroll_steps"` + MovingSteps int `json:"moving_steps"` + ContentChangedSteps int `json:"content_changed_steps"` + MovingFrameRatio float64 `json:"moving_frame_ratio"` + ContentChangeRatio float64 `json:"content_change_ratio"` + NonVacuous bool `json:"non_vacuous"` + ScrollUpdateLatencies LatencyDistribution `json:"scroll_update_latencies"` + StreamUpdateLatencies LatencyDistribution `json:"stream_update_latencies,omitempty"` + ViewLatencies LatencyDistribution `json:"view_latencies"` + PureScrollLatencies LatencyDistribution `json:"pure_scroll_latencies"` + InterleavedFrameLatencies LatencyDistribution `json:"interleaved_frame_latencies,omitempty"` + PrimaryGateLatencies LatencyDistribution `json:"primary_gate_latencies"` + Passes120HzGate bool `json:"passes_120hz_gate"` + GateReason string `json:"gate_reason"` + AllocsPerOp uint64 `json:"allocs_per_op"` + BytesPerOp uint64 `json:"bytes_per_op"` +} + +type MemorySnapshot struct { + AllocBytes uint64 `json:"alloc_bytes"` + TotalAllocBytes uint64 `json:"total_alloc_bytes"` + SysBytes uint64 `json:"sys_bytes"` + HeapAllocBytes uint64 `json:"heap_alloc_bytes"` + HeapInuseBytes uint64 `json:"heap_inuse_bytes"` + NumGC uint32 `json:"num_gc"` + PauseTotalNs uint64 `json:"pause_total_ns"` +} + +func readMem() MemorySnapshot { + var m runtime.MemStats + runtime.ReadMemStats(&m) + return MemorySnapshot{ + AllocBytes: m.Alloc, + TotalAllocBytes: m.TotalAlloc, + SysBytes: m.Sys, + HeapAllocBytes: m.HeapAlloc, + HeapInuseBytes: m.HeapInuse, + NumGC: m.NumGC, + PauseTotalNs: m.PauseTotalNs, + } +} + +func hashString(s string) string { + h := sha256.Sum256([]byte(s)) + return hex.EncodeToString(h[:8]) +} + +func runScrollScenario(width, height int, streaming bool, sampleCount int) ScenarioResult { + session := &daemon.Session{ID: "perf-bench-sess", Workspace: "/workspace/bench"} + m := NewChatModel(session, nil) + m.SetSize(width, height) + + appendedCount, _ := buildRealisticHistory(&m) + + retainedLines := len(m.settledLines) + retainedBytes := m.settledLinesBytes + droppedLines := m.droppedSettledLines + + // Scroll direction state for dynamic triangle-wave traversal across entire scrollback + scrollDirection := -1 // start by scrolling upward from bottom + + // Warmup + for i := 0; i < 20; i++ { + m, _ = m.Update(tea.MouseMsg{Button: tea.MouseButtonWheelUp}) + _ = m.View() + } + + scrollUpdateDurs := make([]time.Duration, sampleCount) + var streamUpdateDurs []time.Duration + if streaming { + streamUpdateDurs = make([]time.Duration, 0, sampleCount) + } + viewDurs := make([]time.Duration, sampleCount) + pureScrollDurs := make([]time.Duration, sampleCount) + var interleavedFrameDurs []time.Duration + if streaming { + interleavedFrameDurs = make([]time.Duration, 0, sampleCount) + } + + seenHashes := make(map[string]struct{}) + seenOffsets := make(map[int]struct{}) + lastOffset := m.scrollOffset + lastHash := "" + movingSteps := 0 + contentChangedSteps := 0 + + for i := 0; i < sampleCount; i++ { + var streamDur time.Duration + isStreamInterleaved := false + + // Interleave active token stream every 2 steps if streaming is enabled + if streaming && (i%2 == 0) { + isStreamInterleaved = true + streamMsg := ChatStreamEventMsg{ + SessionID: m.SessionID, + Generation: m.Generation, + Event: daemon.StreamEvent{ + Type: daemon.EventText, + Text: fmt.Sprintf(" tok_%d", i), + }, + } + tStream0 := time.Now() + m, _ = m.Update(streamMsg) + streamDur = time.Since(tStream0) + streamUpdateDurs = append(streamUpdateDurs, streamDur) + } + + // Dynamically generate action to guarantee continuous motion across full buffer + var act tea.Msg + maxScroll := max(0, len(m.settledLines)-m.Viewport.Height) + if scrollDirection < 0 { + if m.scrollOffset <= 0 { + scrollDirection = 1 + act = tea.MouseMsg{Button: tea.MouseButtonWheelDown} + } else if i%25 == 0 { + act = tea.KeyMsg{Type: tea.KeyPgUp} + } else { + act = tea.MouseMsg{Button: tea.MouseButtonWheelUp} + } + } else { + if m.scrollOffset >= maxScroll { + scrollDirection = -1 + act = tea.MouseMsg{Button: tea.MouseButtonWheelUp} + } else if i%25 == 0 { + act = tea.KeyMsg{Type: tea.KeyPgDown} + } else { + act = tea.MouseMsg{Button: tea.MouseButtonWheelDown} + } + } + + t0 := time.Now() + var cmd tea.Cmd + m, cmd = m.Update(act) + _ = cmd + uDur := time.Since(t0) + + t1 := time.Now() + vStr := m.View() + vDur := time.Since(t1) + + scrollUpdateDurs[i] = uDur + viewDurs[i] = vDur + pureScrollDurs[i] = uDur + vDur + + if isStreamInterleaved { + interleavedFrameDurs = append(interleavedFrameDurs, streamDur+uDur+vDur) + } + + h := hashString(vStr) + if m.scrollOffset != lastOffset { + movingSteps++ + lastOffset = m.scrollOffset + } + if h != lastHash { + contentChangedSteps++ + lastHash = h + } + seenHashes[h] = struct{}{} + seenOffsets[m.scrollOffset] = struct{}{} + } + + uDist := calcDistribution(scrollUpdateDurs) + vDist := calcDistribution(viewDurs) + pureDist := calcDistribution(pureScrollDurs) + + var streamDist, interleavedDist LatencyDistribution + primaryGateDist := pureDist + + if streaming && len(streamUpdateDurs) > 0 { + streamDist = calcDistribution(streamUpdateDurs) + interleavedDist = calcDistribution(interleavedFrameDurs) + // For streaming scenarios, the primary gate assesses the interleaved frame budget (stream+scroll+view) + primaryGateDist = interleavedDist + } + + // Measure real allocations and bytes per op on a representative scroll op + allocSampleModel := m + var memBefore, memAfter runtime.MemStats + benchRuns := 100 + runtime.GC() + runtime.ReadMemStats(&memBefore) + allocs := testing.AllocsPerRun(benchRuns, func() { + testM, _ := allocSampleModel.Update(tea.KeyMsg{Type: tea.KeyPgUp}) + _ = testM.View() + }) + runtime.ReadMemStats(&memAfter) + bytesPerOp := uint64(0) + if memAfter.TotalAlloc > memBefore.TotalAlloc { + bytesPerOp = (memAfter.TotalAlloc - memBefore.TotalAlloc) / uint64(benchRuns) + } + + name := fmt.Sprintf("%dx%d_%s", width, height, map[bool]string{false: "settled", true: "streaming"}[streaming]) + budget8ms := 8333333 * time.Nanosecond + passes := primaryGateDist.P95 <= budget8ms && primaryGateDist.P99 <= budget8ms + + reason := "PASS: p95 & p99 within 8.333ms budget" + if !passes { + if primaryGateDist.P95 > budget8ms { + reason = fmt.Sprintf("FAIL: p95 (%v) exceeds 8.333ms", primaryGateDist.P95) + } else { + reason = fmt.Sprintf("FAIL: p99 (%v) exceeds 8.333ms (tail jitter)", primaryGateDist.P99) + } + } + + movingFrameRatio := float64(movingSteps) / float64(sampleCount) + contentChangeRatio := float64(contentChangedSteps) / float64(sampleCount) + uniqueOffsets := len(seenOffsets) + // Rigorous non-vacuous requirement: + // 1. At least 90% of steps must actively move the scroll offset. + // 2. At least 90% of steps must produce rendered content different from the previous step. + // 3. At least 100 distinct buffer offsets must be traversed (avoiding trivial tight oscillating loops). + nonVacuous := movingFrameRatio >= 0.90 && contentChangeRatio >= 0.90 && uniqueOffsets >= 100 + + return ScenarioResult{ + Name: name, + Width: width, + Height: height, + Streaming: streaming, + RetainedLines: retainedLines, + RetainedBytes: retainedBytes, + DroppedLines: droppedLines, + AppendedEntries: appendedCount, + UniqueViewHashes: len(seenHashes), + UniqueOffsetsVisited: uniqueOffsets, + TotalScrollSteps: sampleCount, + MovingSteps: movingSteps, + ContentChangedSteps: contentChangedSteps, + MovingFrameRatio: movingFrameRatio, + ContentChangeRatio: contentChangeRatio, + NonVacuous: nonVacuous, + ScrollUpdateLatencies: uDist, + StreamUpdateLatencies: streamDist, + ViewLatencies: vDist, + PureScrollLatencies: pureDist, + InterleavedFrameLatencies: interleavedDist, + PrimaryGateLatencies: primaryGateDist, + Passes120HzGate: passes, + GateReason: reason, + AllocsPerOp: uint64(allocs), + BytesPerOp: bytesPerOp, + } +} + +// osSinkRecordingWriter wraps a real OS file descriptor (e.g. os.Pipe) and records +// actual kernel write() syscall counts, latencies, and byte volume. +// NOTE: os.Pipe is an OS kernel pipe, NOT a physical terminal or PTY device. +// write_calls includes all writes (startup ANSI, frame updates, and cleanup sequences). +type osSinkRecordingWriter struct { + mu sync.Mutex + sinkFile *os.File + sinkName string + isTerminal bool + totalBytes int64 + writeCalls int + writeDurations []time.Duration +} + +func (w *osSinkRecordingWriter) Write(p []byte) (n int, err error) { + t0 := time.Now() + n, err = w.sinkFile.Write(p) + dur := time.Since(t0) + + w.mu.Lock() + w.totalBytes += int64(n) + w.writeCalls++ + w.writeDurations = append(w.writeDurations, dur) + w.mu.Unlock() + + return n, err +} + +type OutputSyscallResult struct { + SinkName string `json:"sink_name"` + IsTerminal bool `json:"is_terminal"` + SinkFd int `json:"sink_fd"` + EventsDispatched int `json:"events_dispatched"` + WriteCalls int `json:"write_calls"` + ElapsedDuration string `json:"elapsed_duration"` + ElapsedSeconds float64 `json:"elapsed_seconds"` + DispatchRateHz float64 `json:"dispatch_rate_hz"` + WriteCallRateHz float64 `json:"write_call_rate_hz"` + TotalBytesEmitted int64 `json:"total_bytes_emitted"` + ThroughputKBps float64 `json:"throughput_kb_per_sec"` + ThroughputMBps float64 `json:"throughput_mb_per_sec"` + PerWriteSyscallLatency LatencyDistribution `json:"per_write_syscall_latency"` +} + +func runBubbleTeaProgramEmissionTest() (OutputSyscallResult, error) { + session := &daemon.Session{ID: "perf-prog-sess", Workspace: "/workspace/prog"} + m := NewChatModel(session, nil) + m.SetSize(120, 40) + buildRealisticHistory(&m) + + var sinkFile *os.File + var sinkName string + var cleanup func() + + // Check if stdout is an actual terminal / PTY and opt-in flag is enabled + if isatty.IsTerminal(os.Stdout.Fd()) && os.Getenv("ALBEDO_TEST_USE_STDOUT_PTY") == "1" { + sinkFile = os.Stdout + sinkName = fmt.Sprintf("terminal PTY (stdout fd %d)", os.Stdout.Fd()) + cleanup = func() {} + } else { + // Use real OS kernel pipe with active draining reader. + // NOTE: os.Pipe is an OS kernel pipe, NOT a terminal PTY. + pr, pw, err := os.Pipe() + if err != nil { + return OutputSyscallResult{}, fmt.Errorf("failed to create os.Pipe: %w", err) + } + sinkFile = pw + sinkName = fmt.Sprintf("os.Pipe (kernel syscall stream fd %d, not a PTY)", pw.Fd()) + doneDrain := make(chan struct{}) + go func() { + defer close(doneDrain) + buf := make([]byte, 64*1024) + for { + _, err := pr.Read(buf) + if err != nil { + return + } + } + }() + cleanup = func() { + _ = pw.Close() + _ = pr.Close() + <-doneDrain + } + } + defer cleanup() + + isTerm := isatty.IsTerminal(sinkFile.Fd()) + writer := &osSinkRecordingWriter{ + sinkFile: sinkFile, + sinkName: sinkName, + isTerminal: isTerm, + } + + totalEvents := 120 + wrapper := bubbleTeaBenchmarkWrapper{ + chat: m, + eventsLeft: totalEvents, + } + + inBuf := &bytes.Buffer{} + p := tea.NewProgram( + wrapper, + tea.WithInput(inBuf), + tea.WithOutput(writer), + tea.WithFPS(120), + tea.WithoutSignals(), + tea.WithoutSignalHandler(), + tea.WithoutCatchPanics(), + ) + + errCh := make(chan error, 1) + go func() { + _, err := p.Run() + errCh <- err + }() + + ticker := time.NewTicker(time.Second / 120) + defer ticker.Stop() + + t0 := time.Now() + for i := 0; i < totalEvents; i++ { + <-ticker.C + if i%2 == 0 { + p.Send(tea.KeyMsg{Type: tea.KeyPgUp}) + } else { + p.Send(tea.KeyMsg{Type: tea.KeyPgDown}) + } + } + + select { + case err := <-errCh: + if err != nil { + return OutputSyscallResult{}, err + } + case <-time.After(4 * time.Second): + p.Kill() + return OutputSyscallResult{}, fmt.Errorf("bubble tea program run timed out") + } + elapsed := time.Since(t0) + + writer.mu.Lock() + calls := writer.writeCalls + totalBytes := writer.totalBytes + durs := make([]time.Duration, len(writer.writeDurations)) + copy(durs, writer.writeDurations) + writer.mu.Unlock() + + sec := elapsed.Seconds() + dispatchRate := float64(totalEvents) / sec + writeCallRate := float64(calls) / sec + kbps := float64(totalBytes) / sec / 1024.0 + mbps := float64(totalBytes) / sec / (1024.0 * 1024.0) + + return OutputSyscallResult{ + SinkName: sinkName, + IsTerminal: isTerm, + SinkFd: int(sinkFile.Fd()), + EventsDispatched: totalEvents, + WriteCalls: calls, + ElapsedDuration: elapsed.String(), + ElapsedSeconds: sec, + DispatchRateHz: dispatchRate, + WriteCallRateHz: writeCallRate, + TotalBytesEmitted: totalBytes, + ThroughputKBps: kbps, + ThroughputMBps: mbps, + PerWriteSyscallLatency: calcDistribution(durs), + }, nil +} + +type AcceptanceReport struct { + Timestamp string `json:"timestamp"` + TotalElapsed string `json:"total_elapsed"` + StrictGateMode bool `json:"strict_gate_mode"` + MemBefore MemorySnapshot `json:"mem_before"` + MemAfter MemorySnapshot `json:"mem_after"` + NumGC int64 `json:"num_gc"` + LastGCPause string `json:"last_gc_pause"` + OutputSyscallProfile OutputSyscallResult `json:"output_syscall_profile"` + Results []ScenarioResult `json:"results"` +} + +func TestScrollPerf_AcceptanceGate(t *testing.T) { + // Skip unless explicitly opt-in to keep standard unit and race test suites fast + if os.Getenv("ALBEDO_SCROLL_PERF") != "1" && os.Getenv("ALBEDO_PERF_STRICT") != "1" { + t.Skip("skipping scroll perf acceptance gate; set ALBEDO_SCROLL_PERF=1 or ALBEDO_PERF_STRICT=1 to run") + } + + memBefore := readMem() + t0 := time.Now() + + scenarios := []struct { + w, h int + streaming bool + }{ + {120, 40, false}, + {120, 40, true}, + {180, 60, false}, + {180, 60, true}, + } + + strictGate := os.Getenv("ALBEDO_PERF_STRICT") == "1" + results := make([]ScenarioResult, len(scenarios)) + + for i, sc := range scenarios { + res := runScrollScenario(sc.w, sc.h, sc.streaming, 500) + results[i] = res + + if !res.NonVacuous { + msg := fmt.Sprintf("Scenario %s failed non-vacuous check: moving frames=%.1f%%, content changed=%.1f%%, unique offsets=%d", + res.Name, res.MovingFrameRatio*100, res.ContentChangeRatio*100, res.UniqueOffsetsVisited) + if strictGate { + t.Errorf("%s", msg) + } else { + t.Logf("WARN: %s", msg) + } + } + + if res.RetainedLines > MaxSettledLines { + t.Errorf("Scenario %s retained lines (%d) exceeded MaxSettledLines (%d)", res.Name, res.RetainedLines, MaxSettledLines) + } + + if strictGate && !res.Passes120HzGate { + t.Errorf("Scenario %s failed 120Hz acceptance gate: %s", res.Name, res.GateReason) + } + + t.Logf("=== SCENARIO: %s ===", res.Name) + t.Logf(" Retained: %d lines (%d bytes), Dropped: %d lines", res.RetainedLines, res.RetainedBytes, res.DroppedLines) + t.Logf(" Motion: %d moving frames (%.1f%%), %d content changed (%.1f%%), %d unique offsets, %d unique digests", + res.MovingSteps, res.MovingFrameRatio*100, res.ContentChangedSteps, res.ContentChangeRatio*100, res.UniqueOffsetsVisited, res.UniqueViewHashes) + t.Logf(" Scroll Update: p50=%v, p95=%v, p99=%v", res.ScrollUpdateLatencies.Median, res.ScrollUpdateLatencies.P95, res.ScrollUpdateLatencies.P99) + if res.Streaming { + t.Logf(" Stream Update: p50=%v, p95=%v, p99=%v", res.StreamUpdateLatencies.Median, res.StreamUpdateLatencies.P95, res.StreamUpdateLatencies.P99) + } + t.Logf(" View Latency: p50=%v, p95=%v, p99=%v", res.ViewLatencies.Median, res.ViewLatencies.P95, res.ViewLatencies.P99) + t.Logf(" Primary Gate Latency (p50=%v, p95=%v, p99=%v, max=%v): %.1f%% under 120Hz", + res.PrimaryGateLatencies.Median, res.PrimaryGateLatencies.P95, res.PrimaryGateLatencies.P99, res.PrimaryGateLatencies.Max, + res.PrimaryGateLatencies.PctUnder120) + t.Logf(" Allocs/op: %d, Bytes/op: %d", res.AllocsPerOp, res.BytesPerOp) + t.Logf(" Verdict: %s", res.GateReason) + } + + // Real Bubble Tea output write syscall measurement + syscallResult, err := runBubbleTeaProgramEmissionTest() + if err != nil { + t.Fatalf("Bubble Tea program output syscall run failed: %v", err) + } + t.Logf("=== BUBBLE TEA OUTPUT SYSCALL PROFILE ===") + t.Logf(" Sink: %s (isTerminal=%v, fd=%d; note: os.Pipe != PTY)", syscallResult.SinkName, syscallResult.IsTerminal, syscallResult.SinkFd) + t.Logf(" Dispatched: %d events in %.2fs (%.1f Hz input rate)", syscallResult.EventsDispatched, syscallResult.ElapsedSeconds, syscallResult.DispatchRateHz) + t.Logf(" Raw Write Syscalls: %d calls (%.1f calls/sec; includes setup/diff/cleanup writes)", syscallResult.WriteCalls, syscallResult.WriteCallRateHz) + t.Logf(" Bytes Written: %d bytes (%.2f KB/s, %.2f MB/s)", syscallResult.TotalBytesEmitted, syscallResult.ThroughputKBps, syscallResult.ThroughputMBps) + t.Logf(" Per-Write Syscall Latency (file.Write): p50=%v, p95=%v, p99=%v, max=%v", + syscallResult.PerWriteSyscallLatency.Median, syscallResult.PerWriteSyscallLatency.P95, + syscallResult.PerWriteSyscallLatency.P99, syscallResult.PerWriteSyscallLatency.Max) + + memAfter := readMem() + totalElapsed := time.Since(t0) + + var gcStats debug.GCStats + debug.ReadGCStats(&gcStats) + + report := AcceptanceReport{ + Timestamp: time.Now().UTC().Format(time.RFC3339), + TotalElapsed: totalElapsed.String(), + StrictGateMode: strictGate, + MemBefore: memBefore, + MemAfter: memAfter, + NumGC: gcStats.NumGC, + OutputSyscallProfile: syscallResult, + Results: results, + } + if len(gcStats.Pause) > 0 { + report.LastGCPause = gcStats.Pause[0].String() + } + + data, err := json.MarshalIndent(report, "", " ") + if err == nil { + _ = os.WriteFile("/tmp/albedo-scroll-perf-data.json", data, 0644) + } +} + +// bubbleTeaBenchmarkWrapper wraps ChatModel as a tea.Model for program-level testing. +type bubbleTeaBenchmarkWrapper struct { + chat ChatModel + eventsLeft int +} + +func (w bubbleTeaBenchmarkWrapper) Init() tea.Cmd { + return nil +} + +func (w bubbleTeaBenchmarkWrapper) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + if _, ok := msg.(tea.KeyMsg); ok { + w.eventsLeft-- + if w.eventsLeft <= 0 { + return w, tea.Quit + } + } + newChat, cmd := w.chat.Update(msg) + w.chat = newChat + return w, cmd +} + +func (w bubbleTeaBenchmarkWrapper) View() string { + return w.chat.View() +} + +// Standard Go Benchmarks + +func BenchmarkScroll_UpdateView_120x40_Settled(b *testing.B) { + session := &daemon.Session{ID: "bench-sess", Workspace: "/workspace"} + m := NewChatModel(session, nil) + m.SetSize(120, 40) + buildRealisticHistory(&m) + + upMsg := tea.KeyMsg{Type: tea.KeyPgUp} + downMsg := tea.KeyMsg{Type: tea.KeyPgDown} + + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if i%2 == 0 { + m, _ = m.Update(upMsg) + } else { + m, _ = m.Update(downMsg) + } + _ = m.View() + } +} + +func BenchmarkScroll_UpdateView_180x60_Settled(b *testing.B) { + session := &daemon.Session{ID: "bench-sess", Workspace: "/workspace"} + m := NewChatModel(session, nil) + m.SetSize(180, 60) + buildRealisticHistory(&m) + + upMsg := tea.KeyMsg{Type: tea.KeyPgUp} + downMsg := tea.KeyMsg{Type: tea.KeyPgDown} + + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if i%2 == 0 { + m, _ = m.Update(upMsg) + } else { + m, _ = m.Update(downMsg) + } + _ = m.View() + } +} + +func BenchmarkScroll_UpdateView_120x40_Streaming(b *testing.B) { + session := &daemon.Session{ID: "bench-sess", Workspace: "/workspace"} + m := NewChatModel(session, nil) + m.SetSize(120, 40) + buildRealisticHistory(&m) + + upMsg := tea.KeyMsg{Type: tea.KeyPgUp} + downMsg := tea.KeyMsg{Type: tea.KeyPgDown} + + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if i%2 == 0 { + m, _ = m.Update(ChatStreamEventMsg{ + SessionID: m.SessionID, + Generation: m.Generation, + Event: daemon.StreamEvent{Type: daemon.EventText, Text: " tok"}, + }) + } + if i%2 == 0 { + m, _ = m.Update(upMsg) + } else { + m, _ = m.Update(downMsg) + } + _ = m.View() + } +} + +func BenchmarkScroll_UpdateView_180x60_Streaming(b *testing.B) { + session := &daemon.Session{ID: "bench-sess", Workspace: "/workspace"} + m := NewChatModel(session, nil) + m.SetSize(180, 60) + buildRealisticHistory(&m) + + upMsg := tea.KeyMsg{Type: tea.KeyPgUp} + downMsg := tea.KeyMsg{Type: tea.KeyPgDown} + + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if i%2 == 0 { + m, _ = m.Update(ChatStreamEventMsg{ + SessionID: m.SessionID, + Generation: m.Generation, + Event: daemon.StreamEvent{Type: daemon.EventText, Text: " tok"}, + }) + } + if i%2 == 0 { + m, _ = m.Update(upMsg) + } else { + m, _ = m.Update(downMsg) + } + _ = m.View() + } +} diff --git a/cli/internal/tui/selection.go b/cli/internal/tui/selection.go new file mode 100644 index 000000000..99ce06272 --- /dev/null +++ b/cli/internal/tui/selection.go @@ -0,0 +1,91 @@ +package tui + +import ( + "strings" + + "github.com/charmbracelet/x/ansi" + "github.com/rivo/uniseg" +) + +type Point struct { + Row int + Col int +} +type Selection struct { + Anchor Point + Head Point +} + +func (s Selection) IsEmpty() bool { return s.Anchor == s.Head } +func (s Selection) Normalized() (Point, Point) { + if s.Anchor.Row < s.Head.Row || (s.Anchor.Row == s.Head.Row && s.Anchor.Col <= s.Head.Col) { + return s.Anchor, s.Head + } + return s.Head, s.Anchor +} + +func selectedRange(line string, from, to int) (plain string, before string, selected string, after string) { + plain = ansi.Strip(line) + var chosen, prefix, suffix strings.Builder + col := 0 + for len(plain) > 0 { + cluster, rest, _, _ := uniseg.FirstGraphemeClusterInString(plain, -1) + width := ansi.StringWidth(cluster) + switch { + case col+width > from && col < to: + chosen.WriteString(cluster) + case col < from: + prefix.WriteString(cluster) + default: + suffix.WriteString(cluster) + } + plain = rest + col += width + } + return ansi.Strip(line), prefix.String(), chosen.String(), suffix.String() +} + +func SelectedText(lines []string, sel Selection) string { + if sel.IsEmpty() || len(lines) == 0 { + return "" + } + start, end := sel.Normalized() + if start.Row >= len(lines) { + return "" + } + var rows []string + for row := max(0, start.Row); row <= end.Row && row < len(lines); row++ { + from, to := 0, ansi.StringWidth(lines[row]) + if row == start.Row { + from = start.Col + } + if row == end.Row { + to = end.Col + } + _, _, text, _ := selectedRange(lines[row], from, to) + rows = append(rows, text) + } + return strings.Join(rows, "\n") +} + +func HighlightSelection(lines []string, sel Selection) []string { + if sel.IsEmpty() { + return lines + } + start, end := sel.Normalized() + out := append([]string(nil), lines...) + for row := max(0, start.Row); row <= end.Row && row < len(out); row++ { + from, to := 0, ansi.StringWidth(out[row]) + if row == start.Row { + from = start.Col + } + if row == end.Row { + to = end.Col + } + _, before, text, after := selectedRange(out[row], from, to) + if text != "" { + out[row] = before + "\x1b[7m" + text + "\x1b[0m" + after + } + } + return out +} diff --git a/cli/internal/tui/styles.go b/cli/internal/tui/styles.go new file mode 100644 index 000000000..9fb4465ac --- /dev/null +++ b/cli/internal/tui/styles.go @@ -0,0 +1,63 @@ +package tui + +import "github.com/charmbracelet/lipgloss" + +type Styles struct { + Faint lipgloss.Style + Dim lipgloss.Style + Bold lipgloss.Style + Prompt lipgloss.Style + PromptBright lipgloss.Style + Error lipgloss.Style + Warning lipgloss.Style + ChatWarning lipgloss.Style + ChatSuccess lipgloss.Style + Success lipgloss.Style + Header lipgloss.Style + Selected lipgloss.Style + Unselected lipgloss.Style + Detail lipgloss.Style + Thinking lipgloss.Style + ToolName lipgloss.Style + ToolDetail lipgloss.Style + DiffAdd lipgloss.Style + DiffRemove lipgloss.Style + DiffHeader lipgloss.Style + BadgePlain lipgloss.Style + BadgeActive lipgloss.Style + BadgeWarning lipgloss.Style + BadgeMuted lipgloss.Style + Footer lipgloss.Style + GlanceTitle lipgloss.Style + GlanceBorder lipgloss.Style +} + +var DefaultStyles = Styles{ + Faint: lipgloss.NewStyle().Foreground(lipgloss.Color("8")), + Dim: lipgloss.NewStyle().Faint(true), + Bold: lipgloss.NewStyle().Bold(true), + Prompt: lipgloss.NewStyle().Foreground(lipgloss.Color("6")), + PromptBright: lipgloss.NewStyle().Foreground(lipgloss.Color("14")), + Error: lipgloss.NewStyle().Foreground(lipgloss.Color("9")), + Warning: lipgloss.NewStyle().Foreground(lipgloss.Color("11")), + ChatWarning: lipgloss.NewStyle().Foreground(lipgloss.Color("3")), + ChatSuccess: lipgloss.NewStyle().Foreground(lipgloss.Color("2")), + Success: lipgloss.NewStyle().Foreground(lipgloss.Color("10")), + Header: lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("15")), + Selected: lipgloss.NewStyle().Reverse(true), + Unselected: lipgloss.NewStyle(), + Detail: lipgloss.NewStyle().Foreground(lipgloss.Color("245")), + Thinking: lipgloss.NewStyle().Foreground(lipgloss.Color("244")).Italic(true), + ToolName: lipgloss.NewStyle().Foreground(lipgloss.Color("12")).Bold(true), + ToolDetail: lipgloss.NewStyle().Foreground(lipgloss.Color("242")), + DiffAdd: lipgloss.NewStyle().Foreground(lipgloss.Color("10")), + DiffRemove: lipgloss.NewStyle().Foreground(lipgloss.Color("9")), + DiffHeader: lipgloss.NewStyle().Foreground(lipgloss.Color("14")).Bold(true), + BadgePlain: lipgloss.NewStyle().Foreground(lipgloss.Color("15")), + BadgeActive: lipgloss.NewStyle().Foreground(lipgloss.Color("10")).Bold(true), + BadgeWarning: lipgloss.NewStyle().Foreground(lipgloss.Color("11")), + BadgeMuted: lipgloss.NewStyle().Foreground(lipgloss.Color("242")), + Footer: lipgloss.NewStyle().Foreground(lipgloss.Color("8")), + GlanceTitle: lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("13")), + GlanceBorder: lipgloss.NewStyle().Foreground(lipgloss.Color("238")), +} diff --git a/cli/internal/tui/transcript.go b/cli/internal/tui/transcript.go new file mode 100644 index 000000000..4f857e4d7 --- /dev/null +++ b/cli/internal/tui/transcript.go @@ -0,0 +1,365 @@ +package tui + +import ( + "albedo/cli/internal/daemon" + "fmt" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + "regexp" + "strconv" + "strings" + "time" +) + +type DisplayFlags struct { + Thinking bool + Tools bool + Diffs bool + Compaction bool +} + +type TranscriptRenderer struct { + Styles Styles + HeadingWidth int + BodyWidth int +} + +func NewTranscriptRenderer() TranscriptRenderer { + return TranscriptRenderer{Styles: DefaultStyles} +} + +func formatClock(timestamp int64) string { + if timestamp <= 0 { + return "" + } + t := time.UnixMilli(timestamp) + return t.Format("15:04:05") +} + +func (r TranscriptRenderer) RenderHeading(label string, width int, timestamp int64) string { + clock := formatClock(timestamp) + if width < len(clock)+3 { + clock = "" + } + name := label + if width < len([]rune(name))+len(clock)+1 && width > len(clock)+1 { + runes := []rune(name) + name = string(runes[:max(0, width-len(clock)-2)]) + "…" + } + heading := r.Styles.Bold.Render(name) + if clock != "" { + heading += strings.Repeat(" ", max(1, width-len([]rune(name))-len(clock))) + r.Styles.Faint.Render(clock) + } + return heading +} + +var diffHunk = regexp.MustCompile(`^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@`) + +func (r TranscriptRenderer) RenderDiff(diff string, width int) string { + return r.renderDiffPath(diff, "", width) +} + +func (r TranscriptRenderer) renderDiffPath(diff, path string, width int) string { + if width < 8 { + return "…" + } + var rows []string + oldLine, newLine := 0, 0 + lang := "text" + switch path[strings.LastIndex(path, ".")+1:] { + case "ts", "tsx": + lang = "typescript" + case "js", "jsx": + lang = "javascript" + case "py": + lang = "python" + case "rs": + lang = "rust" + case "sh": + lang = "bash" + } + clean := func(text string) string { + return strings.Map(func(ch rune) rune { + if ch == '\t' { + return ' ' + } + if ch < 32 || ch == 127 { + return ' ' + } + return ch + }, text) + } + row := func(gutter, content, bg string, syntax bool) { + body := "\x1b[90m" + content + "\x1b[39m" + if syntax { + body = HighlightCode(content, lang) + body = strings.ReplaceAll(body, "\x1b[0m", "\x1b[39;22;23m") + } + for i, part := range strings.Split(ansi.Hardwrap(body, max(1, width-ansi.StringWidth(gutter)), true), "\n") { + prefix := gutter + if i > 0 { + prefix = strings.Repeat(" ", ansi.StringWidth(gutter)) + } + cell := prefix + part + rows = append(rows, bg+cell+strings.Repeat(" ", max(0, width-ansi.StringWidth(cell)))+"\x1b[0m") + } + } + panel, add, remove := "\x1b[48;2;37;40;50m", "\x1b[48;2;24;53;39m", "\x1b[48;2;59;35;40m" + row(" ", clean(path), panel, false) + for _, line := range strings.Split(diff, "\n") { + if line == "" || strings.HasPrefix(line, "--- ") || strings.HasPrefix(line, "+++ ") { + continue + } + if hunk := diffHunk.FindStringSubmatch(line); hunk != nil { + oldLine, _ = strconv.Atoi(hunk[1]) + newLine, _ = strconv.Atoi(hunk[2]) + row(" ⋮ ", clean(line), panel, false) + continue + } + switch line[0] { + case '+': + row(fmt.Sprintf("\x1b[32m%4d + \x1b[39m", newLine), clean(line[1:]), add, true) + newLine++ + case '-': + row(fmt.Sprintf("\x1b[31m%4d - \x1b[39m", oldLine), clean(line[1:]), remove, true) + oldLine++ + case ' ': + row(fmt.Sprintf("\x1b[90m%4d \x1b[39m", newLine), clean(line[1:]), panel, true) + newLine++ + oldLine++ + default: + row(" ⋮ ", clean(line), panel, false) + } + } + return strings.Join(rows, "\n") +} + +func toolSummary(entry HistoryEntry) string { + arg := func(key string) string { + if entry.ToolArgs == nil { + return "" + } + return fmt.Sprint(entry.ToolArgs[key]) + } + switch entry.ToolName { + case "python": + return fmt.Sprintf("python · %d lines", strings.Count(arg("code"), "\n")+1) + case "shell": + return "$ " + arg("command") + case "read_file": + return "read " + arg("path") + case "write_file": + return "write " + arg("path") + case "edit_file": + return "edit " + arg("path") + default: + return entry.ToolName + } +} + +func (r TranscriptRenderer) RenderToolTrace(trace *daemon.ToolTrace, flags DisplayFlags, width int) string { + if trace == nil { + return "" + } + var rows []string + if !flags.Tools { + edited := map[string]bool{} + for _, change := range trace.Changes { + edited[change.Path] = true + } + for _, activity := range trace.Activities { + if activity.Kind == "read" && edited[activity.Target] { + continue + } + label := activity.Kind + if activity.Failed { + label += " failed" + } + style := r.Styles.Prompt + if activity.Failed { + style = r.Styles.Error + } + rows = append(rows, style.Render(label+" "+activity.Target)) + } + for _, change := range trace.Changes { + label := "edited " + change.Path + for _, activity := range trace.Activities { + if activity.Kind == "read" && activity.Target == change.Path { + label = "read + " + label + break + } + } + if change.Kind == "diff" { + label += fmt.Sprintf(" +%d −%d", change.Added, change.Removed) + } + rows = append(rows, r.Styles.Prompt.Render(label)) + if flags.Diffs { + if change.Kind == "diff" { + rows = append(rows, r.renderDiffPath(change.Diff, change.Path, width)) + } else { + rows = append(rows, r.Styles.Faint.Render(change.Reason)) + } + } + } + if trace.Truncated { + rows = append(rows, r.Styles.Faint.Render("activity capture limited · /v expand")) + } + return strings.Join(rows, "\n") + } + if len(trace.Activities) > 0 { + verb := "explored" + for _, act := range trace.Activities { + if act.Kind == "run" { + verb = "executed" + break + } + } + rows = append(rows, r.Styles.Bold.Render(verb)) + for _, act := range trace.Activities { + style := r.Styles.Prompt + label := act.Kind + if act.Failed { + style = r.Styles.Error + label += " failed" + } + rows = append(rows, " "+style.Render(label)+" "+act.Target) + } + } + for _, change := range trace.Changes { + line := r.Styles.Bold.Render("edited " + change.Path) + if change.Kind == "diff" { + line += fmt.Sprintf(" %s %s", lipgloss.NewStyle().Foreground(lipgloss.Color("2")).Render(fmt.Sprintf("+%d", change.Added)), lipgloss.NewStyle().Foreground(lipgloss.Color("1")).Render(fmt.Sprintf("−%d", change.Removed))) + } + rows = append(rows, line) + if flags.Diffs { + if change.Kind == "diff" { + rows = append(rows, r.renderDiffPath(change.Diff, change.Path, width)) + } else { + rows = append(rows, r.Styles.Faint.Render(change.Reason)) + } + } + } + if trace.Truncated { + rows = append(rows, r.Styles.Faint.Render("activity capture limited; some operations are not shown")) + } + return strings.Join(rows, "\n") +} + +func (r TranscriptRenderer) faintMarkdownRows(text string, width int) []string { + var rows []string + for _, line := range strings.Split(RenderMarkdownAnsi(text, width), "\n") { + for _, wrapped := range wrapOrChunkLine(line, width) { + rows = append(rows, r.Styles.Faint.Render(wrapped)) + } + } + return rows +} + +func (r TranscriptRenderer) RenderEntry(entry HistoryEntry, flags DisplayFlags, width int) string { + if r.BodyWidth > 0 { + width = r.BodyWidth + } + var rows []string + switch entry.Kind { + case EntryUser, EntryAssistant: + speaker := entry.Speaker + if speaker == "" { + if entry.Kind == EntryUser { + speaker = "You" + } else { + speaker = "albedo" + } + } + headingWidth := width + if r.HeadingWidth > 0 { + headingWidth = r.HeadingWidth + } + heading := r.RenderHeading(speaker, headingWidth, entry.Timestamp) + if entry.Kind == EntryUser { + clock := formatClock(entry.Timestamp) + if clock != "" && headingWidth >= len([]rune(speaker))+len(clock)+2 { + heading = "\x1b[96m" + strings.ToLower(speaker) + "\x1b[0m" + strings.Repeat(" ", headingWidth-len([]rune(speaker))-len(clock)) + r.Styles.Faint.Render(clock) + } else { + heading = "\x1b[96m" + strings.ToLower(speaker) + "\x1b[0m" + } + } + rows = []string{heading, RenderMarkdownAnsi(entry.Text, width)} + case EntryThinking: + rows = []string{r.Styles.Faint.Render("thinking")} + if flags.Thinking { + rows = append(rows, r.faintMarkdownRows(entry.Text, width)...) + } else { + rows = append(rows, r.Styles.Faint.Render("hidden · /t show")) + } + case EntryTool: + trace := entry.ToolTrace + hasTrace := trace != nil && (len(trace.Activities) > 0 || len(trace.Changes) > 0) + failed := strings.Contains(strings.ToLower(entry.ToolResult), "error:") || strings.Contains(strings.ToLower(entry.ToolResult), "cancelled:") || strings.Contains(strings.ToLower(entry.ToolResult), "traceback (most recent call last):") + if !hasTrace || flags.Tools || failed { + style := r.Styles.Faint + if failed { + style = r.Styles.Error + } + label := toolSummary(entry) + if failed { + label += " · failed" + } + rows = append(rows, style.Render(label)) + } + if hasTrace { + rows = append(rows, r.RenderToolTrace(trace, flags, width)) + if !flags.Tools && !failed { + break + } + } + if flags.Tools && entry.ToolName == "python" { + if code, ok := entry.ToolArgs["code"].(string); ok { + rows = append(rows, RenderMarkdownAnsi("```python\n"+code+"\n```", width)) + } + } + if flags.Tools || failed || !hasTrace { + output := strings.TrimRight(entry.ToolResult, "\n") + if output == "" { + output = "(no output)" + } + lines := strings.Split(output, "\n") + if !flags.Tools && len(lines) > 3 { + if failed { + lines = append([]string{r.Styles.Faint.Render(fmt.Sprintf("… %d rows hidden · /v expand", len(lines)-3))}, lines[len(lines)-3:]...) + } + if !failed { + lines = append(lines[:3], r.Styles.Faint.Render(fmt.Sprintf("… %d rows hidden · /v expand", len(lines)-3))) + } + } + rows = append(rows, lines...) + } + case EntryNote: + rows = []string{r.Styles.Faint.Render(entry.Text)} + case EntryError: + rows = []string{r.Styles.Error.Render("error: " + entry.Text)} + case EntryCompacted: + action := "view" + if flags.Compaction { + action = "hide" + } + rows = []string{r.Styles.Faint.Render(fmt.Sprintf("compaction done · %d items summarized · ctrl+k %s summary", entry.Evicted, action))} + if flags.Compaction { + rows = append(rows, r.faintMarkdownRows(entry.Text, width)...) + } + } + return strings.Join(rows, "\n") +} + +func (r TranscriptRenderer) RenderHistory(history *BoundedHistory, flags DisplayFlags, width int) string { + var rows []string + if notice := history.TruncationNotice(); notice != "" { + rows = append(rows, r.Styles.Warning.Render(notice), "") + } + for _, entry := range history.Entries() { + if len(rows) > 0 { + rows = append(rows, "") + } + rows = append(rows, r.RenderEntry(entry, flags, width)) + } + return strings.Join(rows, "\n") +} diff --git a/cli/internal/tui/tree_picker.go b/cli/internal/tui/tree_picker.go new file mode 100644 index 000000000..234ba4e9d --- /dev/null +++ b/cli/internal/tui/tree_picker.go @@ -0,0 +1,308 @@ +package tui + +import ( + "albedo/cli/internal/daemon" + "context" + "errors" + "fmt" + "github.com/charmbracelet/lipgloss" + "regexp" + "strings" + + tea "github.com/charmbracelet/bubbletea" +) + +var whitespaceRegex = regexp.MustCompile(`[\p{Cc}\p{Cf}\p{Z}]+`) + +func readablePreview(value string) string { + clean := strings.TrimSpace(whitespaceRegex.ReplaceAllString(value, " ")) + if clean == "" { + return "(empty)" + } + runes := []rune(clean) + if len(runes) <= 96 { + return clean + } + return string(runes[:95]) + "…" +} + +type TreeCheckpoint struct { + ID int `json:"id"` + Type string `json:"type"` + Preview string `json:"preview"` + Timestamp *int64 `json:"timestamp,omitempty"` +} + +type TreeCancelMsg struct{} + +type TreeForkSuccessMsg struct { + Session daemon.Session +} + +type treeLoadedMsg struct { + Items []TreeCheckpoint + NextCursor *int + HasMore bool + Err error + Gen int +} + +type treeForkedMsg struct { + Session daemon.Session + Err error + Gen int +} + +type TreePickerModel struct { + Conn *daemon.Connection + SessionID string + Cursors []int + PageIndex int + Checkpoints []TreeCheckpoint + NextCursor *int + HasMore bool + Cursor int + Confirming bool + Forking bool + Loading bool + Error string + ForkError string + Generation int + Width int + Height int + Styles Styles +} + +func NewTreePickerModel(conn *daemon.Connection, sessionID string) TreePickerModel { + return TreePickerModel{ + Conn: conn, + SessionID: sessionID, + Cursors: []int{0}, + PageIndex: 0, + Loading: true, + Styles: DefaultStyles, + } +} + +func (m *TreePickerModel) SetSize(width, height int) { + m.Width = width + m.Height = height +} + +func (m TreePickerModel) Init() tea.Cmd { + return m.loadTreeCmd(0, m.Generation) +} + +func (m TreePickerModel) loadTreeCmd(after int, gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil { + return treeLoadedMsg{Err: errors.New("daemon connection unavailable"), Gen: gen} + } + + // Check capability + health, err := daemon.Request[struct { + Capabilities []string `json:"capabilities"` + }](context.Background(), m.Conn, "/health", nil) + if err != nil { + return treeLoadedMsg{Err: err, Gen: gen} + } + hasCap := false + for _, c := range health.Capabilities { + if c == "session_tree" { + hasCap = true + break + } + } + if !hasCap { + return treeLoadedMsg{ + Err: errors.New("daemon upgrade needed for /tree; when ready, run albedo daemon --stop, then albedo (this clears python variables)"), + Gen: gen, + } + } + + type treeResp struct { + Items []TreeCheckpoint `json:"items"` + NextCursor *int `json:"nextCursor"` + HasMore bool `json:"hasMore"` + } + path := fmt.Sprintf("/sessions/%s/tree?after=%d&limit=50", m.SessionID, after) + resp, err := daemon.Request[treeResp](context.Background(), m.Conn, path, nil) + if err != nil { + return treeLoadedMsg{Err: err, Gen: gen} + } + return treeLoadedMsg{ + Items: resp.Items, + NextCursor: resp.NextCursor, + HasMore: resp.HasMore, + Gen: gen, + } + } +} + +func (m TreePickerModel) forkCmd(checkpointID int, gen int) tea.Cmd { + return func() tea.Msg { + if m.Conn == nil { + return treeForkedMsg{Err: errors.New("daemon connection unavailable"), Gen: gen} + } + path := fmt.Sprintf("/sessions/%s/fork", m.SessionID) + body := map[string]int{"checkpoint": checkpointID} + branch, err := daemon.Request[daemon.Session](context.Background(), m.Conn, path, body) + return treeForkedMsg{Session: branch, Err: err, Gen: gen} + } +} + +func (m TreePickerModel) Update(msg tea.Msg) (TreePickerModel, tea.Cmd) { + switch msg := msg.(type) { + case treeLoadedMsg: + if msg.Gen != m.Generation { + return m, nil + } + m.Loading = false + if msg.Err != nil { + m.Error = msg.Err.Error() + return m, nil + } + m.Checkpoints = msg.Items + m.NextCursor = msg.NextCursor + m.HasMore = msg.HasMore + m.Cursor = 0 + m.Confirming = false + m.ForkError = "" + m.Error = "" + return m, nil + + case treeForkedMsg: + if msg.Gen != m.Generation { + return m, nil + } + m.Forking = false + if msg.Err != nil { + m.ForkError = msg.Err.Error() + return m, nil + } + branch := msg.Session + return m, func() tea.Msg { + return TreeForkSuccessMsg{Session: branch} + } + + case tea.KeyMsg: + if msg.Type == tea.KeyEsc || msg.Type == tea.KeyCtrlC || msg.Type == tea.KeyCtrlD { + if m.Confirming { + m.Confirming = false + m.Error = "" + return m, nil + } + return m, func() tea.Msg { return TreeCancelMsg{} } + } + + if m.Forking || m.Loading { + return m, nil + } + + if m.Confirming { + if msg.Type == tea.KeyEnter && len(m.Checkpoints) > m.Cursor { + cp := m.Checkpoints[m.Cursor] + m.Forking = true + m.ForkError = "" + m.Error = "" + m.Generation++ + return m, m.forkCmd(cp.ID, m.Generation) + } + return m, nil + } + + switch msg.Type { + case tea.KeyUp, tea.KeyCtrlP: + if m.Cursor > 0 { + m.Cursor-- + } + case tea.KeyDown, tea.KeyCtrlN: + if m.Cursor < len(m.Checkpoints)-1 { + m.Cursor++ + } + case tea.KeyLeft, tea.KeyPgUp: + if m.PageIndex > 0 { + m.PageIndex-- + m.Loading = true + m.Error = "" + m.Generation++ + return m, m.loadTreeCmd(m.Cursors[m.PageIndex], m.Generation) + } + case tea.KeyRight, tea.KeyPgDown: + if m.HasMore && m.NextCursor != nil { + next := *m.NextCursor + m.Cursors = append(m.Cursors[:m.PageIndex+1], next) + m.PageIndex++ + m.Loading = true + m.Error = "" + m.Generation++ + return m, m.loadTreeCmd(next, m.Generation) + } + case tea.KeyEnter: + if len(m.Checkpoints) > 0 && m.Cursor < len(m.Checkpoints) { + m.ForkError = "" + m.Confirming = true + } + } + } + return m, nil +} + +func (m TreePickerModel) View() string { + var b strings.Builder + + b.WriteString("albedo /tree · branch history") + b.WriteString("\n") + b.WriteString(m.Styles.Dim.Render(inkWrap("choose the checkpoint the new session should end after", m.Width))) + b.WriteString("\n") + + if m.Error != "" { + b.WriteString(inkRed.Render("Error: " + m.Error)) + b.WriteByte('\n') + } + if m.Loading || len(m.Checkpoints) == 0 { + if m.Error == "" && !m.Loading { + b.WriteString(m.Styles.Dim.Render("no branchable history in this session")) + b.WriteByte('\n') + } + if m.Error == "" && m.Loading { + b.WriteString(m.Styles.Dim.Render("loading history…")) + b.WriteByte('\n') + } + b.WriteString(m.Styles.Dim.Render("enter confirm · esc cancel")) + return b.String() + } + + lines := make([]string, len(m.Checkpoints)) + for i, cp := range m.Checkpoints { + lines[i] = lipgloss.NewStyle().Faint(true).Render(fmt.Sprintf("%-9s", cp.Type)) + " " + readablePreview(cp.Preview) + } + b.WriteString(selectableRows(lines, m.Cursor, m.Height, m.Height, m.Width, m.Styles)) + b.WriteByte('\n') + + if m.Confirming && m.Cursor < len(m.Checkpoints) { + current := m.Checkpoints[m.Cursor] + b.WriteString("\n") + b.WriteString(inkYellow.Render(fmt.Sprintf("branch after %s · %s?", current.Type, readablePreview(current.Preview)))) + b.WriteString("\n") + b.WriteString("new session · fresh python namespace · workspace files stay unchanged\n") + if m.ForkError != "" { + b.WriteString(inkRed.Render(m.ForkError)) + b.WriteByte('\n') + } + } + + if m.Forking { + b.WriteString(m.Styles.Dim.Render("creating branch…")) + } else if m.Confirming { + confirmAction := "enter confirm" + if m.ForkError != "" { + confirmAction = "enter retry" + } + b.WriteString(m.Styles.Dim.Render(fmt.Sprintf("%s · esc cancel", confirmAction))) + } else { + b.WriteString(m.Styles.Dim.Render(inkWrap("↑↓ select · ←→/pgup/pgdn page · enter branch · esc return to chat", m.Width))) + } + + return b.String() +} diff --git a/cli/package-lock.json b/cli/package-lock.json index a05d9a9ce..52577805a 100644 --- a/cli/package-lock.json +++ b/cli/package-lock.json @@ -701,7 +701,6 @@ "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", "devOptional": true, "license": "MIT", - "peer": true, "dependencies": { "csstype": "^3.2.2" } @@ -1660,7 +1659,6 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz", "integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==", "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } diff --git a/cli/test/manual/VISUAL_PARITY.md b/cli/test/manual/VISUAL_PARITY.md new file mode 100644 index 000000000..50cb20133 --- /dev/null +++ b/cli/test/manual/VISUAL_PARITY.md @@ -0,0 +1,25 @@ +# visual parity capture (manual, opt-in) + +This is not a UI test suite or a golden-image CI gate. It launches the real TypeScript CLI and the real Go CLI in isolated PTYs, records raw terminal bytes, decodes each with project-local `@xterm/headless`, and renders PNGs using the same fixed font, palette, dimensions, and timing. The fixture HTTP daemon binds **127.0.0.1 only** and rejects unknown routes. Per-run temporary `ALBEDO_HOME` is removed after capture. No real daemon, profile, provider, browser, or clipboard is accessed. The TS preload blocks external HTTP(S); Codex token exchange is fake-only. Go Codex token exchange MUST NOT be exercised through the shipped CLI: use the separate manual real-model driver with an injected fake exchange function. + +Requires `uv`, Node, installed `cli/node_modules` (including `@xterm/headless`), and an installed monospace font. `uv` provides Pillow through this script's PEP 723 metadata; do **not** run through the agent kernel environment. On macOS it defaults to SFNSMono/Hiragino. On Linux it uses DejaVuSansMono/Noto CJK where installed. Set `ALBEDO_VISUAL_FONT` and `ALBEDO_VISUAL_CJK_FONT` explicitly if necessary; paths are recorded beside each capture. + +Capture TS and immutable Go-before under the same label: + +```sh +uv run --no-project --script cli/test/manual/visual_parity.py --binary ts --side ts --label markdown-80x24 --scenario markdown --cols 80 --rows 24 --snap initial:1.0 --expect 'initial:heading' --expect-request GET:/sessions/deadbeef12345678/stream --timeout 1.5 +uv run --no-project --script cli/test/manual/visual_parity.py --binary /tmp/albedo-visual-parity/albedo-before --side before --label markdown-80x24 --scenario markdown --cols 80 --rows 24 --snap initial:1.0 --expect 'initial:heading' --timeout 1.5 +``` + +Once parent supplies one final Go build, capture `--side after --binary /tmp/albedo-visual-parity/albedo-final` with the *same* scenario, variant, action sequence, snapshot labels and timings. Go binaries are copied into content-addressed `/tmp/albedo-visual-parity/binaries/` before launch. Do not use a mutable worktree Go binary as before. Relevant keys: `--action 1.0:/model --action 1.3:enter --snap picker:1.8 --expect 'picker:session model' --expect-request GET:/models/openai`. Supported symbolic keys include `enter,esc,up,down,left,right,pgup,pgdn,shift-enter,alt-enter,ctrl-j,ctrl-k,ctrl-home,ctrl-end,backspace,tab,ctrl-c`. `--expect-exit 0 --expect-reset` requires a real normal quit/cancel and terminal mode restoration, not a screenshot terminated by the harness. During Codex auth avoid overlapping captures because the local fake callback server uses port 1455. + +Outputs are `/tmp/albedo-visual-parity/atlas/