diff --git a/cmd/conch/completion.go b/cmd/conch/completion.go index 6ce36602..084bc084 100644 --- a/cmd/conch/completion.go +++ b/cmd/conch/completion.go @@ -40,6 +40,7 @@ var compCommands = []compItem{ {"send", "type into a pane"}, {"wait", "wait until an agent is done"}, {"close", "close a pane"}, + {"desktop", "the bridge a desktop app talks to"}, {"rename", "name a pane"}, {"redraw", "draw a pane's screen again"}, {"view", "what the terminal is showing"}, diff --git a/cmd/conch/desktop.go b/cmd/conch/desktop.go new file mode 100644 index 00000000..e7d52095 --- /dev/null +++ b/cmd/conch/desktop.go @@ -0,0 +1,92 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "os" + "os/signal" + "sync" + "time" + + "github.com/Amitgb14/conch/internal/client" + "github.com/Amitgb14/conch/internal/config" + "github.com/Amitgb14/conch/internal/desktop" + "github.com/Amitgb14/conch/internal/fleet" + "github.com/Amitgb14/conch/internal/proto" +) + +// `conch desktop` is the bridge a desktop app runs and talks to over this +// process's stdin and stdout (internal/desktop): the Linux and Windows +// apps, and in time Conch.app. It is a command rather than a server of its +// own because the app is what decides it is needed, and because a pipe +// crosses into WSL (`wsl.exe -d Ubuntu conch desktop`) and over ssh with +// nothing listening and nothing to authenticate. Like `conch bridge`, +// stdout carries only the protocol: anything to say goes to stderr. + +const desktopUsage = "usage: conch desktop [-every DURATION]" + +func runDesktop(args []string) error { + return runDesktopOn(args, os.Stdin, os.Stdout) +} + +func runDesktopOn(args []string, in io.Reader, out io.Writer) error { + fs := flag.NewFlagSet("desktop", flag.ContinueOnError) + fs.SetOutput(os.Stderr) + every := fs.Duration("every", time.Second, "how often the servers are read for changes") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() > 0 { + return errors.New(desktopUsage) + } + if *every <= 0 { + return fmt.Errorf("-every must be more than 0, not %s", *every) + } + sock := config.SocketPath() + if err := client.EnsureServer(sock, config.ServerLogPath()); err != nil { + return err + } + self, err := os.Executable() + if err != nil { + return err + } + + // This computer's connection, made again if it drops (the server + // reloading closes it), as the phone gateway's is. + var mu sync.Mutex + var shared *client.Client + local := func() (*client.Client, error) { + mu.Lock() + defer mu.Unlock() + if shared != nil && shared.Err() == nil { + return shared, nil + } + c, err := client.Dial(sock, "conch-desktop") + if err != nil { + return nil, err + } + shared = c + return c, nil + } + pool := fleet.New(fleet.Options{ + Local: local, + DialLocal: func() (*client.Client, error) { return client.Dial(sock, "conch-desktop") }, + }) + defer pool.Close() + defer func() { + mu.Lock() + if shared != nil { + shared.Close() + } + mu.Unlock() + }() + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + return desktop.Serve(ctx, in, out, desktop.Options{ + Machines: pool, Conch: self, Version: proto.Version, Every: *every, + }) +} diff --git a/cmd/conch/desktop_test.go b/cmd/conch/desktop_test.go new file mode 100644 index 00000000..2800e148 --- /dev/null +++ b/cmd/conch/desktop_test.go @@ -0,0 +1,104 @@ +package main + +import ( + "bufio" + "encoding/json" + "io" + "os" + "strings" + "testing" + "time" + + "github.com/Amitgb14/conch/internal/client" + "github.com/Amitgb14/conch/internal/config" + "github.com/Amitgb14/conch/internal/desktop" + "github.com/Amitgb14/conch/internal/server" +) + +func TestDesktopArgs(t *testing.T) { + a4Env(t) + for _, args := range [][]string{{"extra"}, {"-every", "0s"}, {"-every", "-1s"}, {"-nope"}} { + if err := runDesktopOn(args, strings.NewReader(""), io.Discard); err == nil { + t.Errorf("%q was taken", args) + } + } +} + +// TestDesktopOverARealServer runs the command as an app would: hello in, +// hello and the snapshot of this computer out, and the bridge ending when +// the app closes its end. +func TestDesktopOverARealServer(t *testing.T) { + dir := a4Env(t) + srv := server.New(config.SocketPath(), dir) + go srv.Run() + t.Cleanup(srv.StopAndWait) + for i := 0; ; i++ { + if c, err := client.Dial(config.SocketPath(), "test"); err == nil { + c.Close() + break + } + if i == 200 { + t.Fatal("server did not start") + } + time.Sleep(20 * time.Millisecond) + } + + inR, inW := io.Pipe() + outR, outW := io.Pipe() + done := make(chan error, 1) + go func() { + done <- runDesktopOn([]string{"-every", "50ms"}, inR, outW) + outW.Close() + }() + if _, err := inW.Write([]byte(`{"type":"hello","data":{"app":"test"}}` + "\n")); err != nil { + t.Fatal(err) + } + lines := bufio.NewReader(outR) + read := func() desktop.Message { + t.Helper() + got := make(chan desktop.Message, 1) + go func() { + line, err := lines.ReadBytes('\n') + var m desktop.Message + if err == nil { + err = json.Unmarshal(line, &m) + } + if err != nil { + m.Error = "read: " + err.Error() + } + got <- m + }() + select { + case m := <-got: + return m + case <-time.After(15 * time.Second): + t.Fatal("timed out reading conch desktop") + } + return desktop.Message{} + } + if m := read(); m.Type != desktop.TypeHello { + t.Fatalf("first: %+v", m) + } + m := read() + var st desktop.State + if err := json.Unmarshal(m.Data, &st); err != nil || m.Type != desktop.TypeSnapshot { + t.Fatalf("second: %+v %v", m, err) + } + if len(st.Machines) == 0 || st.Machines[0].ID != "local" || st.Machines[0].State != "online" { + t.Errorf("snapshot: %+v", st.Machines) + } + + inW.Close() + go io.Copy(io.Discard, outR) + select { + case err := <-done: + if err != nil { + t.Errorf("an app closing its end is not an error: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("conch desktop did not end with its input") + } + if _, err := os.Stat(config.SocketPath()); err != nil { + t.Errorf("the server went with the bridge: %v", err) + } +} diff --git a/cmd/conch/main.go b/cmd/conch/main.go index 27935ce3..3bab6ce3 100644 --- a/cmd/conch/main.go +++ b/cmd/conch/main.go @@ -87,6 +87,9 @@ Usage: terminal the program's own output to draw, not conch's screen; -view (with -raw) never resizes the pane or takes its size conch close ID close a pane + conch desktop [-every D] the bridge a desktop app talks to on stdin and stdout: every + machine's panes and agents as JSON lines (the Linux and + Windows apps); -every is how often it looks for changes conch rename ID [NAME] name a pane; without NAME it gets its own back. Every command taking a pane ID takes its name too conch redraw ID draw a pane's screen again (after a program left stale text) @@ -503,6 +506,8 @@ func main() { err = runSandbox(args) case "bridge": err = runBridge() + case "desktop": + err = runDesktop(args) case "update": err = runUpdate(args) case "upload": diff --git a/cmd/conch/sandbox.go b/cmd/conch/sandbox.go index 306d3cfe..4d584de7 100644 --- a/cmd/conch/sandbox.go +++ b/cmd/conch/sandbox.go @@ -8,7 +8,6 @@ import ( "fmt" "os" "os/exec" - "runtime" "strconv" "strings" "sync" @@ -17,6 +16,7 @@ import ( "github.com/Amitgb14/conch/internal/client" "github.com/Amitgb14/conch/internal/config" + "github.com/Amitgb14/conch/internal/desktop" "github.com/Amitgb14/conch/internal/proto" "github.com/Amitgb14/conch/internal/remote" "github.com/Amitgb14/conch/internal/sandbox" @@ -697,13 +697,7 @@ func periodWhat(p sandbox.UsagePeriod) string { // openInBrowser hands a link to the desktop. A variable so tests can check // what would open without a window appearing on whoever runs them. -var openInBrowser = func(url string) error { - tool := "xdg-open" - if runtime.GOOS == "darwin" { - tool = "open" - } - return exec.Command(tool, url).Start() -} +var openInBrowser = desktop.Open // sandboxUsage prints what a sandbox has cost, and where it went. func sandboxUsage(args []string) error { diff --git a/docs/plans/desktop-windows-linux.md b/docs/plans/desktop-windows-linux.md new file mode 100644 index 00000000..599dcbff --- /dev/null +++ b/docs/plans/desktop-windows-linux.md @@ -0,0 +1,232 @@ +# Plan: Conch desktop app on Linux and Windows + +Status: plan and design (2026-11-15). Target: the next release. +Phases 0 and 1 are built (the bridge is `internal/desktop` and `conch +desktop`); the Linux and Windows apps are being started on branches of +their own. Decided: each OS gets its own native app; Electron and Tauri +stay out. Open decisions are listed at the end. + +## Goal + +What Conch.app is on the Mac — a native window onto conch's server, with +the tree, tabs and splits, waiting agents, the git tab and sessions — on +Linux and on Windows, without writing conch's logic three times. + +## Design: three layers + +``` + ┌────────────────┐ ┌──────────────────┐ ┌───────────────────┐ + │ Conch.app │ │ conch for Linux │ │ conch for Windows │ 1. UI, one per OS + │ Swift, AppKit │ │ GTK 4 + VTE │ │ WinUI 3 + terminal│ draws, sends intents + └───────┬────────┘ └────────┬─────────┘ └─────────┬─────────┘ + │ stdio, JSON lines │ │ wsl.exe -d D … + ┌───────▼────────────────────▼──────────────────────▼─────────┐ + │ conch desktop (Go, inside the conch binary) │ 2. bridge, written once + │ machines · tree · counts · layout · notify · capabilities │ decides + └───────┬──────────────────────────────────────────┬──────────┘ + │ conch protocol (unix socket / ssh bridge)│ + ┌───────▼────────┐ ┌─────────▼─────────┐ + │ conch server │ this computer │ conch server │ 3. servers, unchanged + │ (WSL on Win.) │ │ on each machine │ own the panes + └────────────────┘ └───────────────────┘ + + Each pane: the UI's terminal widget runs the command the bridge names, + e.g. `conch attach -raw machine|p3` (or `wsl.exe -d D conch attach …`). +``` + +### Layer 3: conch server + +No change. It owns the pseudo-terminals, so agents keep running when a +window closes or the app updates — the same split Herdr (herdr-core) and +T3 Code (its Node server) make. On Windows it runs in WSL 2 to begin +with (phase 3); a native Windows server is phase 5, optional. + +### Layer 2: the bridge, `conch desktop` + +A subcommand of the `conch` binary the app starts and talks to over its +own stdin and stdout, one bridge per window process. Written once, in Go, +tested by the race suite on Linux and macOS like the rest of conch. + +Why stdio: no port, no token, nothing listening; it crosses into WSL as +`wsl.exe -d conch desktop` and into a remote host as ssh does, +which is how Conch.app already reaches machines (`Connection(command:)`, +`conch machine bridge`). Why Go: what it does is what `internal/fleet` +and `internal/phone` already do for the phone gateway — a client per +machine reached in the background, a machine that cannot be reached +carrying why, panes named `machine:pane`, each machine's capabilities +checked against its own handshake. + +**It owns** (moved out of the UIs, so none of them writes it): + +- the machine list and connections (`internal/fleet`) +- the tree: machines → projects → branches → agents and terminals, with + counts and agent states +- search, and the ⌘K palette's results +- the tab/split layout of each window, and which window holds a pane + (a pane is shown in one place, as in the TUI and Conch.app) +- when to notify (the UI only delivers it) +- capability checks, said as text the UI shows as it is +- how to attach to a pane: the command line a terminal widget runs + +**It does not carry terminal bytes.** Each pane's terminal runs its own +`conch attach` (`-raw` where the widget can take the program's own +output, `-view` for previews), as Conch.app does today. A busy pane +cannot slow the tree, and the attach path is already proven. + +#### Messages + +Newline-delimited JSON, the same framing as conch's protocol. The bridge +sends state; the UI sends intents and never edits state itself. + +| Direction | Message | What | +| --- | --- | --- | +| UI → bridge | `hello` | UI name, version, OS, what its terminal can do (`raw`, `images`) | +| bridge → UI | `hello` | protocol version, capabilities, `conch` version | +| bridge → UI | `snapshot` | the whole state: machines, tree, agents, windows and layout | +| bridge → UI | `patch` | changes since the last, by id (`set`, `remove`), with a sequence number | +| bridge → UI | `notify` | an agent waiting, done or failed: title, body, the pane to show | +| bridge → UI | `attach` | the argv a pane's terminal runs, and its size rules (letterbox or not) | +| UI → bridge | `intent` | `pane.new`, `pane.close`, `pane.show`, `split`, `tab.move`, `agent.answer`, `prompt.send`, `branch.new`, `task.start`, … each with an id | +| bridge → UI | `result` | the intent's id, ok or an error to show | +| UI → bridge | `ask` | a one-off read: diff of a branch, sessions, file list, system stats | + +Rules carried over from conch's protocol: every field after the first +release is optional; a new message or intent comes with a capability +string; an older UI ignores what it does not know, and a newer UI asks +`hello` before using something. A Go test pins every message's shape +(as `internal/phone/api.go`'s test does), and the shapes reuse the +phone's types (`Agent`, `Pane`, `Question`, `Project`) where they fit. + +### Layer 1: a native app per OS + +Each app is a renderer of the bridge's state plus the parts that only an +OS can do: windows, menus, keys, notifications, secrets, its terminal +widget, its installer. + +| | macOS | Linux | Windows | +| --- | --- | --- | --- | +| Language, toolkit | Swift, AppKit + SwiftUI (exists) | Rust, GTK 4 + libadwaita (gtk4-rs) | C#, WinUI 3 (Windows App SDK, .NET 8) | +| Pane terminal | libghostty, SwiftTerm fallback | VTE 4 (vte4-rs) | Windows Terminal's control (`Microsoft.Terminal.Control` via a wrapper); libghostty-vt as the alternative | +| Notifications | UserNotifications | libnotify / portal | app notifications (toasts) | +| Secrets | Keychain | libsecret | Credential Manager | +| Browser pane | WebKit | WebKitGTK 6 | WebView2 | +| Global hotkey (scratch) | Carbon | GlobalShortcuts portal where offered | `RegisterHotKey` | + +Settings need no UI of their own on any OS: the existing settings page +(`internal/configweb`) opens in the browser pane. + +Each terminal widget sits behind one interface (Conch.app's +`TerminalHost.swift` is the model), so a better widget can replace it — +on Windows especially, where no embeddable terminal is official. + +### Windows: WSL first, native later + +- **Phase 3 (WSL):** the app is a native Windows program; the bridge + and server run in a WSL 2 distribution. The app starts + `wsl.exe -d conch desktop`, and the bridge's `attach` argv is + `wsl.exe -d conch attach …`. Paths cross with `wslpath`. + Projects should live in the distribution's filesystem: changes made + from Windows under `/mnt/c` are not seen by inotify. T3 Code ships a + WSL backend the same way. +- **Phase 5 (native, optional):** a Windows `conch` server on ConPTY + (charmbracelet `x/xpty`), Job Objects for process groups, the peer pid + for agent scoping (`SIO_AF_UNIX_GETPEERPID`; `peer_other.go`'s 0 would + leave every agent unscoped), and **no hot reload** — Herdr ships + Windows without its live handoff too. Then a distribution is one more + machine, not a requirement. + +## Packaging and updates + +- **Linux:** a tarball and the existing install script (it already adds + `conch app` to the desktop), then `.deb`, `.rpm` and AppImage. Not + Flatpak: its sandbox fights starting agents and shells. +- **Windows:** Herdr's pattern — a PowerShell installer + (`irm …/install.ps1 | iex`) into `%LOCALAPPDATA%\Programs\conch`, a + Start-menu entry, no admin rights; it checks WSL 2 and installs + `conch` in the chosen distribution. Signed with Azure Artifact Signing + in CI. winget and an MSIX later. +- **Updates:** the app downloads its new version beside the running one + and switches on next launch; the server keeps the panes (already how + conch updates). The bridge comes with `conch`, so a server update + updates it. + +## Testing + +- **Bridge:** Go tests with real servers (`startServer`), fake machines + (`sshtest`), and the contract test pinning every message. Recorded + sessions (`snapshot`, `patch`, `notify` sequences) are kept as + fixtures. +- **Each app:** its own unit tests against a fake bridge that replays + those fixtures — `cargo test` on a Linux runner, `dotnet test` on a + Windows runner — so no UI test needs a server, an agent or WSL. +- **End to end:** rows in `docs/testing/end-to-end.md` for each app on + a real desktop (GNOME and KDE, Wayland and X11; Windows 11 with WSL 2); + 9.189–9.190 already cover phase 0. + +## Phases + +| # | What | Done when | +| --- | --- | --- | +| 0 | This plan; links under WSL open in Windows' browser (`internal/desktop`) | merged with this branch | +| 1 | `conch desktop`: hello, snapshot, patch, notify, and the intents pane.new, pane.close and pane.attach, over `internal/fleet`; contract test (`TestBridgeContract`). **Built.** Tab and layout intents wait on open decision 3 | a script can watch the tree change and open panes through it | +| 2 | Linux app MVP: tree, tabs and splits, VTE panes, answering a waiting agent, notifications, install | daily use on Linux without the TUI | +| 3 | Windows app MVP against WSL: the same, with the installer | the same on Windows 11 | +| 4 | Parity in order of use: git tab (hunks, commits, reviews), sessions, tasks, System Monitor; scenes last or never | each feature moved into the bridge first, then drawn | +| 5 | Native Windows server (optional) | Windows without WSL, minus hot reload | +| 6 | Conch.app moves its logic into the bridge, a piece at a time (tree, counts, search, layout) | ConchKit only draws and connects | + +## Risks + +- **Three front ends to keep in step.** Every Conch.app feature costs + up to three times its UI. The bridge keeps the logic single; the + drawing is still triple. Mitigation: features land in the bridge first, + and the Linux and Windows apps may lag on decorative ones. +- **Windows terminal widget.** Windows Terminal's control is not a + supported public component. Keep it behind the seam; libghostty-vt + plus a renderer of our own is the fallback (Herdr draws libghostty-vt + with GPUI on all three platforms). +- **WSL limits.** Startup cost of `wsl.exe`, `/mnt/c` without file + events, the distribution chosen by the person. Say each in `conch + doctor` rather than fail quietly. +- **Layout moving into the bridge** changes where Conch.app's windows + are saved (its preferences today). Phase 6 has to load the old place. + +## Open decisions + +1. **Linux toolkit:** Rust + GTK 4 + VTE (recommended: the most mature + bindings, the native look on GNOME) — or one Rust/GPUI app with + libghostty-vt for Linux *and* Windows, as Herdr does, which halves the + UI work but rests on GPUI before 1.0. +2. **Windows terminal widget:** Windows Terminal's control (mature + rendering, unofficial packaging) or libghostty-vt with our own + renderer (same emulator as the Mac, more work). +3. **Does the bridge own the layout?** Recommended yes, so the three apps + agree; the cost is phase 6's migration on the Mac. +4. **Native Windows server (phase 5):** do it, or stay WSL-only. + +## Where things stand today + +- **Linux:** the `conch` binary is fully supported (released for amd64 + and arm64, race suite in CI), and `conch app install` already puts + conch in the desktop's applications in ghostty, kitty, foot or + alacritty. Only Conch.app's own features are missing. +- **Windows:** `GOOS=windows go build ./...` fails at the first Unix + calls (`internal/config/omzpreview.go`, `internal/detect/process.go`); + about thirty files use them. conch runs under WSL 2 from Windows + Terminal, which the installation page now says. +- **Conch.app:** `ConchKit` (~16k lines) imports only Foundation and + would mostly build off the Mac; `ConchApp` (~29k lines) is AppKit and + SwiftUI throughout and cannot. The bridge takes over ConchKit's job + for the other two apps rather than porting it. + +## Prior art read for this + +- Herdr: the app is Rust on GPUI with libghostty-vt for terminals, one + codebase for all three OSes, over herdr-core (Rust, ConPTY on + Windows, protocol over stdio with `hc connect`); Windows installed by a + PowerShell script, signed with Azure Artifact Signing, no live handoff + on Windows. +- T3 Code: Electron over a Node server (`node-pty`, ConPTY); a WSL + backend that copies the server into the distribution and talks to it + on loopback; NSIS installer, Azure Trusted Signing, `electron-updater`, + winget; AppImage and `.deb` on Linux. diff --git a/docs/testing/end-to-end.md b/docs/testing/end-to-end.md index 0696e99d..648f250e 100644 --- a/docs/testing/end-to-end.md +++ b/docs/testing/end-to-end.md @@ -430,6 +430,8 @@ What it carries, and what is left over in each row: | 9.186 💳🌐 | The autopilot's activity in Conch.app | With the autopilot on (auto_fix, auto_merge, auto_resolve, a check) for a real GitHub repository and a real agent on a task branch: open **Commit Graph** → **Autopilot** and leave it open; break a test so CI fails, let the agent fix it, let the pull request merge; then quit everything, reload the server, and open it again | Each step appears in *What it did* as it happens (CI sent to the agent, pushed, merged), marked by kind, under Today, with the branch a link to its commits; *Minding now* follows the branch; the rules match Settings; after the reload the feed is all still there | ☐ | | 9.187 💳 | Review and push a resolved rebase in Conch.app | A task branch pushed with a pull request, then the base changed on the same lines: open **Commit Graph**, **Ask an agent to resolve** with a real agent, wait for it to finish the rebase | The banner turns green (*rebased onto master*), the branch's card lists each commit old → new with the conflicted one marked *resolved*; **Review the resolution** shows the agent's own lines as + / −; **Push (with lease)** replaces the old branch on GitHub and the pull request updates; on a second run, **Undo the rebase** puts the branch back and the conflict returns; with a commit pushed from elsewhere in between, the push is refused rather than overwriting it | ☐ | | 9.188 💳 | Watch an agent resolve a conflict in Conch.app | A task branch whose rebase onto master stopped on a conflict: open **Commit Graph**, **Ask an agent to resolve** with a real agent; then once more with `auto_resolve` on and the autopilot asking | While the agent works the banner turns blue (*Claude is resolving the conflict with master*, *N of M files left · you asked …*, or *the autopilot asked*), the branch reads *resolving*, and **Show Claude** opens its pane; when the agent asks a permission question the banner says it is waiting on you; it turns green once the rebase is finished; closing the agent's pane mid-way turns it red (*has ended*) with **Ask again**; after `conch server reload` an agent still working in the stopped worktree still reads *resolving* | ☐ | +| 9.189 🖥 | Links open from conch under WSL 2 | On Windows 11, in Windows Terminal, run conch inside a WSL 2 distribution; open a pull request link and the settings page (`,` then `e`) from the TUI, once with wslu installed and once without (`sudo apt remove wslu`). | Each link opens in Windows' default browser both times; nothing is printed into the pane. (Fakes only choose the command: `internal/desktop`) | ☐ | +| 9.190 🖥 | `conch app install` on GNOME and KDE | On a Linux desktop with ghostty or kitty installed, under Wayland and then X11: `conch app install`, find conch in the launcher and start it; `conch app remove`. | The entry and icon appear in the launcher, open conch in its own window with conch's theme, and are gone after remove. | ☐ | Everything else marked 💳 wants a model: the brain's providers (1.x), an agent's own state hooks and usage (2.1-2.5, 9.1, 9.21, 9.22, 9.70), saved diff --git a/internal/desktop/api.go b/internal/desktop/api.go new file mode 100644 index 00000000..1cf4b778 --- /dev/null +++ b/internal/desktop/api.go @@ -0,0 +1,182 @@ +package desktop + +import ( + "encoding/json" + "time" +) + +// The bridge's wire format: what `conch desktop` says to a desktop app +// and what the app says back, one JSON object a line on the bridge's +// stdin and stdout (docs/plans/desktop-windows-linux.md). Three apps are +// written against it — Conch.app, the Linux app, the Windows app — in +// three languages, so its shapes are a contract: TestBridgeContract +// pins them, a field once released stays, and anything new is optional +// and announced by a capability. + +// Protocol is the bridge's version: raised only for a change an older +// app could not read. New messages and fields come with a capability. +const Protocol = 1 + +// Capabilities are what this bridge offers, said in its hello. +var Capabilities = []string{CapBridge} + +// CapBridge is the first set: hello, snapshot, patch, notify, and the +// intents pane.new, pane.close and pane.attach. +const CapBridge = "desktop.v1" + +// Message types. +const ( + TypeHello = "hello" // both ways, first + TypeSnapshot = "snapshot" // bridge → app: the whole State + TypePatch = "patch" // bridge → app: a Patch on the last state + TypeNotify = "notify" // bridge → app: something to tell the person + TypeIntent = "intent" // app → bridge: do something + TypeResult = "result" // bridge → app: how an intent went +) + +// Intents an app may send. +const ( + IntentPaneNew = "pane.new" + IntentPaneClose = "pane.close" + IntentPaneAttach = "pane.attach" +) + +// Message is one line either way. Which fields are set depends on Type: +// an intent has ID, Intent and Data; its result the same ID, OK, and +// Error or Data; a snapshot or patch has Seq and Data. A result and the +// patch its intent causes come in either order, so an app goes by the +// patch for the state and by the result only for success or the error. +type Message struct { + Type string `json:"type"` + ID string `json:"id,omitempty"` + Seq int `json:"seq,omitempty"` + Intent string `json:"intent,omitempty"` + OK bool `json:"ok,omitempty"` + Error string `json:"error,omitempty"` + Data json.RawMessage `json:"data,omitempty"` +} + +// AppHello is what an app says first. +type AppHello struct { + App string `json:"app"` // "conch-linux", "conch-windows", "conch-mac" + Version string `json:"version,omitempty"` // the app's own + OS string `json:"os,omitempty"` + // Raw says the app's terminal draws the program's own output, so + // attach is given -raw (Ghostty does; VTE and most widgets do not). + Raw bool `json:"raw,omitempty"` + // Wrap goes in front of every command the bridge hands back to run, + // because the app may not run where the bridge does: a Windows app + // whose bridge is in WSL sends ["wsl.exe", "-d", "Ubuntu"]. + Wrap []string `json:"wrap,omitempty"` +} + +// BridgeHello is the bridge's answer. +type BridgeHello struct { + Protocol int `json:"protocol"` + Conch string `json:"conch"` // the conch version the bridge is + Capabilities []string `json:"capabilities"` +} + +// State is everything an app draws its tree from. +type State struct { + Machines []Machine `json:"machines"` + Projects []Project `json:"projects"` + Panes []Pane `json:"panes"` +} + +// Machine is this computer or one of the catalog's. +type Machine struct { + ID string `json:"id"` // "local" for this computer + Label string `json:"label"` + State string `json:"state"` // online, connecting, offline + Detail string `json:"detail,omitempty"` // why it is not online +} + +// Project is a project on a machine. Key is unique across machines. +type Project struct { + Key string `json:"key"` // machine:id + Machine string `json:"machine"` + ID string `json:"id"` + Name string `json:"name"` + Path string `json:"path"` +} + +// Pane is a terminal on a machine, with the agent in it if there is one. +// Key is unique across machines and is what intents name. +type Pane struct { + Key string `json:"key"` // machine:id + Machine string `json:"machine"` + ID string `json:"id"` + Name string `json:"name"` + Title string `json:"title,omitempty"` + Project string `json:"project,omitempty"` // a Project's Key + Branch string `json:"branch,omitempty"` + State string `json:"state"` // running, exited + ExitCode int `json:"exit_code,omitempty"` + Agent *Agent `json:"agent,omitempty"` +} + +// Agent is the agent detected in a pane. +type Agent struct { + Name string `json:"name"` + State string `json:"state"` // idle, working, waiting, done + Since time.Time `json:"since"` + Failed bool `json:"failed,omitempty"` +} + +// Agent states, in the app's words. +const ( + AgentIdle = "idle" + AgentWorking = "working" + AgentWaiting = "waiting" + AgentDone = "done" +) + +// Patch is what changed since the last snapshot or patch: items set +// (added or changed, whole) and keys removed, per list. An app applies +// it by replacing each item set where it already is, adding a new one at +// the end, then dropping the keys removed. A machine that goes offline +// takes its projects and panes with it, since they can no longer be +// known. testdata/session.jsonl is a recorded session and +// testdata/final.json the state it ends in, for an app's own tests. +type Patch struct { + Machines *Changes[Machine] `json:"machines,omitempty"` + Projects *Changes[Project] `json:"projects,omitempty"` + Panes *Changes[Pane] `json:"panes,omitempty"` +} + +// Changes is one list's part of a patch. +type Changes[T any] struct { + Set []T `json:"set,omitempty"` + Remove []string `json:"remove,omitempty"` +} + +// Notify is something the person should hear about: an agent that +// started waiting, finished, or failed. The app decides how to say it. +type Notify struct { + Kind string `json:"kind"` // waiting, done, failed + Pane string `json:"pane"` // a Pane's Key + Title string `json:"title"` + Body string `json:"body,omitempty"` +} + +// PaneNew starts a pane: an agent, a command, or the machine's shell. +type PaneNew struct { + Machine string `json:"machine,omitempty"` // "" is local + Agent string `json:"agent,omitempty"` + Prompt string `json:"prompt,omitempty"` + Command []string `json:"command,omitempty"` + Cwd string `json:"cwd,omitempty"` + Name string `json:"name,omitempty"` +} + +// PaneRef names a pane by its Key. +type PaneRef struct { + Pane string `json:"pane"` +} + +// Attach is how an app's terminal shows a pane: the command to run in it. +type Attach struct { + Argv []string `json:"argv"` + Raw bool `json:"raw,omitempty"` // the pane is drawn at the server's size +} diff --git a/internal/desktop/bridge.go b/internal/desktop/bridge.go new file mode 100644 index 00000000..711af518 --- /dev/null +++ b/internal/desktop/bridge.go @@ -0,0 +1,447 @@ +package desktop + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "reflect" + "sort" + "sync" + "time" + + "github.com/Amitgb14/conch/internal/client" + "github.com/Amitgb14/conch/internal/fleet" + "github.com/Amitgb14/conch/internal/proto" +) + +// The bridge: what `conch desktop` runs between a desktop app and every +// machine's conch server. It owns the state the app draws — machines, +// projects, panes and their agents — and sends it whole once, then only +// what changed, so three apps in three languages draw the same tree and +// none of them works it out itself. It carries no terminal output: each +// pane's terminal runs the `conch attach` the bridge names for it. + +// Machines is where the bridge gets its machines: a fleet.Pool. +type Machines interface { + Machines() []fleet.Machine +} + +// Options configures Serve. +type Options struct { + Machines Machines + // Conch is the conch binary the attach commands run: this one. + Conch string + // Version is the conch version said in the bridge's hello. + Version string + // Every is how often the servers are read for changes (1 s). + Every time.Duration + // Wait bounds one read of one machine (5 s), so a machine that stops + // answering does not hold up the others' changes. + Wait time.Duration +} + +// errNoHello is the answer to anything an app sends before its hello. +var errNoHello = errors.New("say hello first") + +// Serve runs the bridge on in and out until in ends (the app went), ctx +// is done, or out cannot be written. An app that closes its end is the +// normal way out and returns nil. +func Serve(ctx context.Context, in io.Reader, out io.Writer, o Options) error { + if o.Every <= 0 { + o.Every = time.Second + } + if o.Wait <= 0 { + o.Wait = 5 * time.Second + } + ctx, cancel := context.WithCancel(ctx) + defer cancel() + b := &bridge{o: o, w: json.NewEncoder(out), last: map[string]machineRead{}} + + msgs := make(chan Message) + readErr := make(chan error, 1) + go func() { + sc := bufio.NewScanner(in) + sc.Buffer(make([]byte, 64*1024), 4*1024*1024) + for sc.Scan() { + var m Message + if err := json.Unmarshal(sc.Bytes(), &m); err != nil { + _ = b.send(Message{Type: TypeResult, Error: "not a message: " + err.Error()}) + continue + } + select { + case msgs <- m: + case <-ctx.Done(): + return + } + } + readErr <- sc.Err() + }() + + // Nothing but hello until hello. + for b.hello == nil { + select { + case <-ctx.Done(): + return ctx.Err() + case err := <-readErr: + return err + case m := <-msgs: + if m.Type != TypeHello { + if err := b.send(Message{Type: TypeResult, ID: m.ID, Error: errNoHello.Error()}); err != nil { + return err + } + continue + } + var h AppHello + if err := json.Unmarshal(m.Data, &h); err != nil { + if err := b.send(Message{Type: TypeResult, Error: "hello: " + err.Error()}); err != nil { + return err + } + continue + } + b.hello = &h + } + } + if err := b.sendData(Message{Type: TypeHello}, BridgeHello{Protocol: Protocol, Conch: o.Version, Capabilities: Capabilities}); err != nil { + return err + } + + cur := b.read(ctx) + if err := b.sendData(Message{Type: TypeSnapshot, Seq: b.next()}, cur); err != nil { + return err + } + + tick := time.NewTicker(o.Every) + defer tick.Stop() + again := make(chan struct{}, 1) // an intent changed something: look now + var wg sync.WaitGroup + defer wg.Wait() + defer cancel() + for { + select { + case <-ctx.Done(): + return nil + case err := <-readErr: + return err + case m := <-msgs: + wg.Add(1) + go func() { + defer wg.Done() + if b.intent(ctx, m) { + select { + case again <- struct{}{}: + default: + } + } + }() + continue + case <-tick.C: + case <-again: + } + next := b.read(ctx) + if p, changed := diff(cur, next); changed { + if err := b.sendData(Message{Type: TypePatch, Seq: b.next()}, p); err != nil { + return err + } + } + for _, n := range notices(cur, next) { + if err := b.sendData(Message{Type: TypeNotify}, n); err != nil { + return err + } + } + cur = next + } +} + +type bridge struct { + o Options + hello *AppHello + + wmu sync.Mutex + w *json.Encoder + seq int + + // last is each machine's last good read, kept so a machine whose + // read fails once does not have every pane removed and set again. + last map[string]machineRead +} + +type machineRead struct { + projects []Project + panes []Pane +} + +func (b *bridge) next() int { b.seq++; return b.seq } + +func (b *bridge) send(m Message) error { + b.wmu.Lock() + defer b.wmu.Unlock() + return b.w.Encode(m) +} + +func (b *bridge) sendData(m Message, v any) error { + data, err := json.Marshal(v) + if err != nil { + return err + } + m.Data = data + return b.send(m) +} + +// read asks every machine that is online for its projects and panes. +func (b *bridge) read(ctx context.Context) State { + s := State{Machines: []Machine{}, Projects: []Project{}, Panes: []Pane{}} + for _, m := range b.o.Machines.Machines() { + s.Machines = append(s.Machines, Machine{ID: m.ID, Label: m.Label, State: m.State, Detail: m.Detail}) + c := m.Client() + if c == nil { + continue // its panes are not knowable now, so not shown + } + r, err := readMachine(ctx, b.o.Wait, m.ID, c) + if err != nil { + r = b.last[m.ID] + } else { + b.last[m.ID] = r + } + s.Projects = append(s.Projects, r.projects...) + s.Panes = append(s.Panes, r.panes...) + } + return s +} + +func readMachine(ctx context.Context, wait time.Duration, machine string, c *client.Client) (machineRead, error) { + ctx, cancel := context.WithTimeout(ctx, wait) + defer cancel() + var pl proto.ProjectList + if err := c.Call(ctx, proto.MethodProjectList, nil, &pl); err != nil { + return machineRead{}, err + } + var panes proto.PaneList + if err := c.Call(ctx, proto.MethodPaneList, nil, &panes); err != nil { + return machineRead{}, err + } + var r machineRead + for _, p := range pl.Projects { + r.projects = append(r.projects, Project{Key: fleet.ComposePaneID(machine, p.ID), Machine: machine, ID: p.ID, Name: p.Name, Path: p.Path}) + } + for _, p := range panes.Panes { + r.panes = append(r.panes, paneOf(machine, p)) + } + return r, nil +} + +// paneOf is a server's pane in the app's words. +func paneOf(machine string, p proto.PaneInfo) Pane { + out := Pane{ + Key: fleet.ComposePaneID(machine, p.ID), Machine: machine, ID: p.ID, + Name: p.Name, Title: p.Title, Branch: p.Branch, State: p.State, ExitCode: p.ExitCode, + } + if p.ProjectID != "" { + out.Project = fleet.ComposePaneID(machine, p.ProjectID) + } + if p.Agent != nil { + out.Agent = &Agent{Name: p.Agent.Name, State: agentState(p.Agent.State), Since: p.Agent.Since.UTC(), Failed: p.Agent.Failed} + } + return out +} + +func agentState(s string) string { + switch s { + case proto.AgentBlocked: + return AgentWaiting + case proto.AgentWorking: + return AgentWorking + case proto.AgentDone: + return AgentDone + } + return AgentIdle +} + +// diff is the patch that takes a to b, and whether there is one. +func diff(a, b State) (Patch, bool) { + var p Patch + p.Machines = changes(a.Machines, b.Machines, func(m Machine) string { return m.ID }) + p.Projects = changes(a.Projects, b.Projects, func(x Project) string { return x.Key }) + p.Panes = changes(a.Panes, b.Panes, func(x Pane) string { return x.Key }) + return p, p.Machines != nil || p.Projects != nil || p.Panes != nil +} + +func changes[T any](a, b []T, key func(T) string) *Changes[T] { + was := make(map[string]T, len(a)) + for _, x := range a { + was[key(x)] = x + } + var c Changes[T] + seen := make(map[string]bool, len(b)) + for _, x := range b { + k := key(x) + seen[k] = true + if old, ok := was[k]; !ok || !reflect.DeepEqual(old, x) { + c.Set = append(c.Set, x) + } + } + for _, x := range a { + if k := key(x); !seen[k] { + c.Remove = append(c.Remove, k) + } + } + if len(c.Set) == 0 && len(c.Remove) == 0 { + return nil + } + sort.Strings(c.Remove) + return &c +} + +// notices are what the person should hear about between two states: an +// agent that has started waiting, finished, or failed. An agent seen for +// the first time says nothing — it was not a change anybody missed. +func notices(a, b State) []Notify { + was := make(map[string]*Agent, len(a.Panes)) + for _, p := range a.Panes { + was[p.Key] = p.Agent + } + var out []Notify + for _, p := range b.Panes { + old, ok := was[p.Key] + if !ok || old == nil || p.Agent == nil { + continue + } + name := p.Name + if name == "" { + name = p.Agent.Name + } + switch { + case p.Agent.Failed && !old.Failed: + out = append(out, Notify{Kind: "failed", Pane: p.Key, Title: name + " failed", Body: p.Title}) + case p.Agent.State == AgentWaiting && old.State != AgentWaiting: + out = append(out, Notify{Kind: AgentWaiting, Pane: p.Key, Title: name + " is waiting for you", Body: p.Title}) + case p.Agent.State == AgentDone && old.State != AgentDone: + out = append(out, Notify{Kind: AgentDone, Pane: p.Key, Title: name + " is done", Body: p.Title}) + } + } + return out +} + +// intent does what an app asked and answers it. It says whether the +// state may have changed, so the caller looks again at once. +func (b *bridge) intent(ctx context.Context, m Message) bool { + reply := func(data any, err error) { + r := Message{Type: TypeResult, ID: m.ID} + if err != nil { + r.Error = err.Error() + _ = b.send(r) + return + } + r.OK = true + if data != nil { + _ = b.sendData(r, data) + return + } + _ = b.send(r) + } + if m.Type != TypeIntent { + reply(nil, fmt.Errorf("the bridge takes intents, not %q", m.Type)) + return false + } + switch m.Intent { + case IntentPaneAttach: + var ref PaneRef + if err := json.Unmarshal(m.Data, &ref); err != nil { + reply(nil, err) + return false + } + a, err := b.attach(ref.Pane) + reply(a, err) + return false + case IntentPaneNew: + var req PaneNew + if err := json.Unmarshal(m.Data, &req); err != nil { + reply(nil, err) + return false + } + machine := req.Machine + if machine == "" { + machine = fleet.Local + } + c, err := b.client(machine) + if err != nil { + reply(nil, err) + return false + } + ctx, cancel := context.WithTimeout(ctx, b.o.Wait) + defer cancel() + var info proto.PaneInfo + err = c.Call(ctx, proto.MethodPaneCreate, proto.PaneCreateParams{ + Name: req.Name, Agent: req.Agent, Prompt: req.Prompt, Command: req.Command, Cwd: req.Cwd, + NoProject: req.Cwd == "", + }, &info) + if err != nil { + reply(nil, err) + return false + } + reply(PaneRef{Pane: fleet.ComposePaneID(machine, info.ID)}, nil) + return true + case IntentPaneClose: + var ref PaneRef + if err := json.Unmarshal(m.Data, &ref); err != nil { + reply(nil, err) + return false + } + machine, id, err := fleet.SplitPaneID(ref.Pane) + if err != nil { + reply(nil, err) + return false + } + c, err := b.client(machine) + if err != nil { + reply(nil, err) + return false + } + ctx, cancel := context.WithTimeout(ctx, b.o.Wait) + defer cancel() + err = c.Call(ctx, proto.MethodPaneClose, proto.PaneRef{ID: id}, nil) + reply(nil, err) + return err == nil + } + reply(nil, fmt.Errorf("unknown intent %q", m.Intent)) + return false +} + +// client is a machine's connection while it is online. +func (b *bridge) client(machine string) (*client.Client, error) { + for _, m := range b.o.Machines.Machines() { + if m.ID != machine { + continue + } + if c := m.Client(); c != nil { + return c, nil + } + if m.Detail != "" { + return nil, fmt.Errorf("%s is %s: %s", m.Label, m.State, m.Detail) + } + return nil, fmt.Errorf("%s is %s", m.Label, m.State) + } + return nil, fmt.Errorf("no machine %q", machine) +} + +// attach is the command that shows a pane in the app's terminal: this +// conch's attach, through -m for another machine — the same command +// Conch.app runs — behind whatever the app said to wrap commands in. +func (b *bridge) attach(key string) (Attach, error) { + machine, id, err := fleet.SplitPaneID(key) + if err != nil { + return Attach{}, err + } + argv := append([]string{}, b.hello.Wrap...) + argv = append(argv, b.o.Conch) + if machine != fleet.Local { + argv = append(argv, "-m", machine) + } + argv = append(argv, "attach") + if b.hello.Raw { + argv = append(argv, "-raw") + } + return Attach{Argv: append(argv, id), Raw: b.hello.Raw}, nil +} diff --git a/internal/desktop/bridge_test.go b/internal/desktop/bridge_test.go new file mode 100644 index 00000000..46394192 --- /dev/null +++ b/internal/desktop/bridge_test.go @@ -0,0 +1,414 @@ +package desktop + +import ( + "bufio" + "context" + "encoding/json" + "io" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/Amitgb14/conch/internal/client" + "github.com/Amitgb14/conch/internal/fleet" + "github.com/Amitgb14/conch/internal/remote" + "github.com/Amitgb14/conch/internal/server" +) + +// TestBridgeContract pins the wire shapes three apps are written against. +// A key renamed here breaks Conch.app, the Linux app and the Windows app +// at once, in three languages, silently — so it has to fail a test first. +func TestBridgeContract(t *testing.T) { + since := time.Date(2026, 11, 15, 12, 0, 0, 0, time.UTC) + for _, c := range []struct { + name string + v any + want string + }{ + {"message", Message{Type: TypeResult, ID: "7", OK: true, Data: json.RawMessage(`{}`)}, + `{"type":"result","id":"7","ok":true,"data":{}}`}, + {"patch message", Message{Type: TypePatch, Seq: 3, Data: json.RawMessage(`{}`)}, + `{"type":"patch","seq":3,"data":{}}`}, + {"intent", Message{Type: TypeIntent, ID: "1", Intent: IntentPaneNew, Data: json.RawMessage(`{}`)}, + `{"type":"intent","id":"1","intent":"pane.new","data":{}}`}, + {"error", Message{Type: TypeResult, ID: "2", Error: "no"}, + `{"type":"result","id":"2","error":"no"}`}, + {"app hello", AppHello{App: "conch-windows", Version: "0.1", OS: "windows", Raw: true, Wrap: []string{"wsl.exe", "-d", "Ubuntu"}}, + `{"app":"conch-windows","version":"0.1","os":"windows","raw":true,"wrap":["wsl.exe","-d","Ubuntu"]}`}, + {"bridge hello", BridgeHello{Protocol: 1, Conch: "0.2.1", Capabilities: []string{"desktop.v1"}}, + `{"protocol":1,"conch":"0.2.1","capabilities":["desktop.v1"]}`}, + {"empty state", State{Machines: []Machine{}, Projects: []Project{}, Panes: []Pane{}}, + `{"machines":[],"projects":[],"panes":[]}`}, + {"machine", Machine{ID: "busybox", Label: "busybox", State: "offline", Detail: "no route"}, + `{"id":"busybox","label":"busybox","state":"offline","detail":"no route"}`}, + {"project", Project{Key: "local:x1", Machine: "local", ID: "x1", Name: "conch", Path: "/src/conch"}, + `{"key":"local:x1","machine":"local","id":"x1","name":"conch","path":"/src/conch"}`}, + {"pane", Pane{Key: "local:p3", Machine: "local", ID: "p3", Name: "claude", Title: "t", Project: "local:x1", Branch: "b", + State: "exited", ExitCode: 2, Agent: &Agent{Name: "claude", State: AgentWaiting, Since: since, Failed: true}}, + `{"key":"local:p3","machine":"local","id":"p3","name":"claude","title":"t","project":"local:x1","branch":"b","state":"exited","exit_code":2,"agent":{"name":"claude","state":"waiting","since":"2026-11-15T12:00:00Z","failed":true}}`}, + {"bare pane", Pane{Key: "local:p1", Machine: "local", ID: "p1", State: "running"}, + `{"key":"local:p1","machine":"local","id":"p1","name":"","state":"running"}`}, + {"patch", Patch{Panes: &Changes[Pane]{Remove: []string{"local:p1"}}}, + `{"panes":{"remove":["local:p1"]}}`}, + {"notify", Notify{Kind: "waiting", Pane: "local:p3", Title: "claude is waiting for you", Body: "b"}, + `{"kind":"waiting","pane":"local:p3","title":"claude is waiting for you","body":"b"}`}, + {"pane.new", PaneNew{Machine: "busybox", Agent: "claude", Prompt: "hi", Command: []string{"sh"}, Cwd: "/w", Name: "n"}, + `{"machine":"busybox","agent":"claude","prompt":"hi","command":["sh"],"cwd":"/w","name":"n"}`}, + {"pane ref", PaneRef{Pane: "local:p1"}, `{"pane":"local:p1"}`}, + {"attach", Attach{Argv: []string{"conch", "attach", "p1"}, Raw: true}, `{"argv":["conch","attach","p1"],"raw":true}`}, + } { + t.Run(c.name, func(t *testing.T) { + got, err := json.Marshal(c.v) + if err != nil { + t.Fatal(err) + } + if string(got) != c.want { + t.Errorf("got %s\nwant %s", got, c.want) + } + }) + } + if Protocol != 1 || !reflect.DeepEqual(Capabilities, []string{"desktop.v1"}) { + t.Errorf("protocol %d, capabilities %q: an app reads these to decide what to use", Protocol, Capabilities) + } +} + +func TestDiff(t *testing.T) { + a := State{ + Machines: []Machine{{ID: "local", State: "online"}}, + Panes: []Pane{{Key: "local:p1", State: "running"}, {Key: "local:p2", State: "running"}}, + } + if _, changed := diff(a, a); changed { + t.Error("the same state is a change") + } + b := State{ + Machines: []Machine{{ID: "local", State: "online"}, {ID: "box", State: "connecting"}}, + Panes: []Pane{{Key: "local:p1", State: "exited"}, {Key: "local:p3", State: "running"}}, + } + p, changed := diff(a, b) + if !changed { + t.Fatal("no change seen") + } + if p.Projects != nil { + t.Errorf("projects did not change but came as %+v", p.Projects) + } + if got := p.Machines; got == nil || len(got.Set) != 1 || got.Set[0].ID != "box" || got.Remove != nil { + t.Errorf("machines = %+v", got) + } + var set []string + for _, x := range p.Panes.Set { + set = append(set, x.Key) + } + if !reflect.DeepEqual(set, []string{"local:p1", "local:p3"}) || !reflect.DeepEqual(p.Panes.Remove, []string{"local:p2"}) { + t.Errorf("panes set %q remove %q", set, p.Panes.Remove) + } + // Everything gone. + p, _ = diff(b, State{}) + if p.Machines == nil || len(p.Machines.Remove) != 2 || len(p.Panes.Remove) != 2 { + t.Errorf("emptied: %+v %+v", p.Machines, p.Panes) + } +} + +func TestNotices(t *testing.T) { + agent := func(state string, failed bool) *Agent { return &Agent{Name: "claude", State: state, Failed: failed} } + pane := func(key, name string, a *Agent) Pane { return Pane{Key: key, Name: name, Agent: a} } + a := State{Panes: []Pane{ + pane("local:p1", "", agent(AgentWorking, false)), + pane("local:p2", "fixer", agent(AgentWorking, false)), + pane("local:p3", "", agent(AgentWorking, false)), + pane("local:p4", "", agent(AgentWaiting, false)), + pane("local:p5", "", nil), + }} + b := State{Panes: []Pane{ + pane("local:p1", "", agent(AgentWaiting, false)), + pane("local:p2", "fixer", agent(AgentDone, false)), + pane("local:p3", "", agent(AgentWorking, true)), + pane("local:p4", "", agent(AgentWaiting, false)), // still waiting: said once + pane("local:p5", "", agent(AgentWaiting, false)), // an agent just detected + pane("local:p6", "", agent(AgentWaiting, false)), // a pane just seen + }} + got := notices(a, b) + want := []Notify{ + {Kind: "waiting", Pane: "local:p1", Title: "claude is waiting for you"}, + {Kind: "done", Pane: "local:p2", Title: "fixer is done"}, + {Kind: "failed", Pane: "local:p3", Title: "claude failed"}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("notices\n got %+v\nwant %+v", got, want) + } + if n := notices(b, b); n != nil { + t.Errorf("no change, yet %+v", n) + } +} + +func TestAttachCommand(t *testing.T) { + b := &bridge{o: Options{Conch: "/opt/conch"}, hello: &AppHello{}} + got, err := b.attach("local:p4") + if err != nil || !reflect.DeepEqual(got.Argv, []string{"/opt/conch", "attach", "p4"}) || got.Raw { + t.Errorf("local: %+v %v", got, err) + } + // A bare pane is this computer's, as everywhere else. + if got, _ := b.attach("p4"); !reflect.DeepEqual(got.Argv, []string{"/opt/conch", "attach", "p4"}) { + t.Errorf("bare: %q", got.Argv) + } + b.hello = &AppHello{Raw: true, Wrap: []string{"wsl.exe", "-d", "Ubuntu"}} + got, err = b.attach("busybox:p2") + want := []string{"wsl.exe", "-d", "Ubuntu", "/opt/conch", "-m", "busybox", "attach", "-raw", "p2"} + if err != nil || !reflect.DeepEqual(got.Argv, want) || !got.Raw { + t.Errorf("remote, wrapped: %+v %v", got, err) + } + // The wrap is copied, not appended to in place. + if len(b.hello.Wrap) != 3 { + t.Errorf("wrap changed: %q", b.hello.Wrap) + } + for _, bad := range []string{"", "local:", "Box:p1", "local:p1; rm -rf ~", "a:b:c"} { + if _, err := b.attach(bad); err == nil { + t.Errorf("%q gave an attach command", bad) + } + } +} + +// offline is a machine list with one machine that cannot be reached. +type offline struct{} + +func (offline) Machines() []fleet.Machine { + return []fleet.Machine{{ID: "box", Label: "box", State: fleet.Offline, Detail: "connection refused"}} +} + +// session is a bridge served over pipes, read and written by a test. +type session struct { + t *testing.T + in *io.PipeWriter + out *bufio.Reader + done chan error +} + +func serve(t *testing.T, o Options) *session { + t.Helper() + inR, inW := io.Pipe() + outR, outW := io.Pipe() + s := &session{t: t, in: inW, out: bufio.NewReader(outR), done: make(chan error, 1)} + go func() { + err := Serve(context.Background(), inR, outW, o) + outW.Close() + s.done <- err + }() + t.Cleanup(func() { + inW.Close() + go io.Copy(io.Discard, outR) // let a last write finish + select { + case <-s.done: + case <-time.After(10 * time.Second): + t.Error("the bridge did not end when its input did") + } + }) + return s +} + +func (s *session) send(m Message) { + s.t.Helper() + b, _ := json.Marshal(m) + if _, err := s.in.Write(append(b, '\n')); err != nil { + s.t.Fatal(err) + } +} + +func (s *session) intent(id, intent string, v any) { + data, _ := json.Marshal(v) + s.send(Message{Type: TypeIntent, ID: id, Intent: intent, Data: data}) +} + +// next reads messages until one passes keep, failing after a timeout. +func (s *session) next(keep func(Message) bool) Message { + s.t.Helper() + got := make(chan Message, 1) + errs := make(chan error, 1) + go func() { + for { + line, err := s.out.ReadBytes('\n') + if err != nil { + errs <- err + return + } + var m Message + if err := json.Unmarshal(line, &m); err != nil { + errs <- err + return + } + if keep(m) { + got <- m + return + } + } + }() + select { + case m := <-got: + return m + case err := <-errs: + s.t.Fatalf("reading the bridge: %v", err) + case <-time.After(15 * time.Second): + s.t.Fatal("timed out waiting for the bridge") + } + return Message{} +} + +func ofType(typ string) func(Message) bool { return func(m Message) bool { return m.Type == typ } } + +func resultFor(id string) func(Message) bool { + return func(m Message) bool { return m.Type == TypeResult && m.ID == id } +} + +func TestBridgeWantsHelloFirst(t *testing.T) { + s := serve(t, Options{Machines: offline{}, Conch: "conch"}) + s.intent("1", IntentPaneAttach, PaneRef{Pane: "local:p1"}) + if r := s.next(resultFor("1")); r.Error != errNoHello.Error() || r.OK { + t.Errorf("before hello: %+v", r) + } + s.send(Message{Type: TypeHello, Data: json.RawMessage(`"not an object"`)}) + if r := s.next(ofType(TypeResult)); !strings.HasPrefix(r.Error, "hello:") { + t.Errorf("a bad hello: %+v", r) + } + s.in.Write([]byte("not json\n")) + if r := s.next(ofType(TypeResult)); !strings.HasPrefix(r.Error, "not a message") { + t.Errorf("a line that is not JSON: %+v", r) + } + s.send(Message{Type: TypeHello, Data: json.RawMessage(`{"app":"test"}`)}) + var h BridgeHello + json.Unmarshal(s.next(ofType(TypeHello)).Data, &h) + if h.Protocol != Protocol || !reflect.DeepEqual(h.Capabilities, Capabilities) { + t.Errorf("hello: %+v", h) + } + var st State + json.Unmarshal(s.next(ofType(TypeSnapshot)).Data, &st) + if len(st.Machines) != 1 || st.Machines[0].Detail != "connection refused" || len(st.Panes) != 0 { + t.Errorf("snapshot with a machine offline: %+v", st) + } + // Asking an offline machine says why it cannot. + s.intent("2", IntentPaneNew, PaneNew{Machine: "box"}) + if r := s.next(resultFor("2")); !strings.Contains(r.Error, "connection refused") { + t.Errorf("pane.new on an offline machine: %+v", r) + } + s.intent("3", IntentPaneClose, PaneRef{Pane: "nowhere:p1"}) + if r := s.next(resultFor("3")); !strings.Contains(r.Error, `no machine "nowhere"`) { + t.Errorf("pane.close on no machine: %+v", r) + } + s.intent("4", "pane.fly", nil) + if r := s.next(resultFor("4")); !strings.Contains(r.Error, "unknown intent") { + t.Errorf("an unknown intent: %+v", r) + } + s.send(Message{Type: TypeSnapshot, ID: "5"}) + if r := s.next(resultFor("5")); !strings.Contains(r.Error, "takes intents") { + t.Errorf("a snapshot sent to the bridge: %+v", r) + } + s.intent("6", IntentPaneClose, json.RawMessage(`[1]`)) + if r := s.next(resultFor("6")); r.Error == "" { + t.Errorf("malformed data: %+v", r) + } +} + +// startServer runs a real conch server on a short socket path (macOS caps +// them near 104 bytes), in a home of its own. +func startServer(t *testing.T) string { + t.Helper() + t.Setenv("CONCH_SOCKET", "") + t.Setenv("CONCH_PANE_ID", "") + dir, err := os.MkdirTemp("", "dk") + if err != nil { + t.Fatal(err) + } + dir, _ = filepath.EvalSymlinks(dir) + t.Setenv("HOME", dir) + t.Setenv("CONCH_HOME", filepath.Join(dir, ".conch")) + t.Setenv("SHELL", "/bin/sh") + sock := filepath.Join(dir, "s.sock") + srv := server.New(sock, dir) + go srv.Run() + t.Cleanup(func() { srv.StopAndWait(); os.RemoveAll(dir) }) + for range 200 { + if c, err := client.Dial(sock, "probe"); err == nil { + c.Close() + return sock + } + time.Sleep(20 * time.Millisecond) + } + t.Fatal("server did not start") + return "" +} + +// TestBridgeOverARealServer is the whole round: hello, the snapshot, a +// pane started through the bridge arriving as a patch, the command that +// would show it, and closing it taking it away again. +func TestBridgeOverARealServer(t *testing.T) { + sock := startServer(t) + local, err := client.Dial(sock, "test") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { local.Close() }) + pool := fleet.New(fleet.Options{ + Local: func() (*client.Client, error) { return local, nil }, + Catalog: func() ([]remote.Machine, error) { return nil, nil }, + }) + t.Cleanup(pool.Close) + + s := serve(t, Options{Machines: pool, Conch: "/bin/conch", Version: "test", Every: 50 * time.Millisecond}) + s.send(Message{Type: TypeHello, Data: json.RawMessage(`{"app":"test","wrap":["wsl.exe"]}`)}) + s.next(ofType(TypeHello)) + var st State + json.Unmarshal(s.next(ofType(TypeSnapshot)).Data, &st) + if len(st.Machines) != 1 || st.Machines[0].ID != fleet.Local || st.Machines[0].State != fleet.Online || len(st.Panes) != 0 { + t.Fatalf("snapshot: %+v", st) + } + + s.intent("n", IntentPaneNew, PaneNew{Command: []string{"/bin/sh", "-c", "sleep 30"}, Name: "sleeper"}) + r := s.next(resultFor("n")) + var made PaneRef + json.Unmarshal(r.Data, &made) + if !r.OK || !strings.HasPrefix(made.Pane, "local:p") { + t.Fatalf("pane.new: %+v", r) + } + s.next(func(m Message) bool { + if m.Type != TypePatch { + return false + } + var p Patch + json.Unmarshal(m.Data, &p) + return p.Panes != nil && len(p.Panes.Set) == 1 && p.Panes.Set[0].Key == made.Pane && p.Panes.Set[0].Name == "sleeper" + }) + + s.intent("a", IntentPaneAttach, made) + r = s.next(resultFor("a")) + var a Attach + json.Unmarshal(r.Data, &a) + _, id, _ := fleet.SplitPaneID(made.Pane) + if want := []string{"wsl.exe", "/bin/conch", "attach", id}; !r.OK || !reflect.DeepEqual(a.Argv, want) { + t.Errorf("pane.attach: %+v %q", r, a.Argv) + } + + // The result and the patch it causes come in either order: the + // refresh may see the pane gone before the close returns. + s.intent("c", IntentPaneClose, made) + closed, removed := false, false + for !closed || !removed { + s.next(func(m Message) bool { + switch { + case m.Type == TypeResult && m.ID == "c": + if !m.OK { + t.Fatalf("pane.close: %+v", m) + } + closed = true + return true + case m.Type == TypePatch: + var p Patch + json.Unmarshal(m.Data, &p) + if p.Panes != nil && reflect.DeepEqual(p.Panes.Remove, []string{made.Pane}) { + removed = true + return true + } + } + return false + }) + } +} diff --git a/internal/desktop/open.go b/internal/desktop/open.go new file mode 100644 index 00000000..1c321f7a --- /dev/null +++ b/internal/desktop/open.go @@ -0,0 +1,89 @@ +// Package desktop is conch's side of the desktop: which program opens a +// link on the desktop it runs on (the TUI and the commands both open +// links, and each had its own copy of the choice), and the bridge that +// desktop apps talk to (`conch desktop`, bridge.go). +package desktop + +import ( + "os" + "os/exec" + "runtime" + "strings" +) + +// Host is what the choice depends on, so a test can be any machine. +type Host struct { + GOOS string + Getenv func(string) string + Release func() string // the kernel release, as /proc reports it + LookPath func(string) bool +} + +// Local is the machine conch is running on. +func Local() Host { + return Host{ + GOOS: runtime.GOOS, + Getenv: os.Getenv, + Release: func() string { return readFile("/proc/sys/kernel/osrelease") }, + LookPath: func(name string) bool { + _, err := exec.LookPath(name) + return err == nil + }, + } +} + +func readFile(path string) string { + b, err := os.ReadFile(path) + if err != nil { + return "" + } + return string(b) +} + +// IsWSL says whether this is Linux under Windows' Subsystem for Linux: +// the distribution's variable, which WSL sets for what it starts, or the +// kernel's release, which names Microsoft in both WSL 1 and 2 — the +// variable is not passed on by everything (a service, sudo). +func (h Host) IsWSL() bool { + if h.GOOS != "linux" { + return false + } + if h.Getenv("WSL_DISTRO_NAME") != "" { + return true + } + return strings.Contains(strings.ToLower(h.Release()), "microsoft") +} + +// OpenCommand is the command that opens url in the desktop's browser. +// +// On WSL the Linux way usually leads nowhere: xdg-open is there, but no +// browser is installed in the distribution, so a link conch opened did +// nothing. Windows' own browser is reached through wslview where wslu is +// installed, else through the URL handler every Windows has — rundll32 +// rather than `cmd /c start`, which reads & in a link as its own. +func (h Host) OpenCommand(url string) []string { + if h.GOOS == "darwin" { + return []string{"open", url} + } + if h.IsWSL() { + if h.LookPath("wslview") { + return []string{"wslview", url} + } + if h.LookPath("rundll32.exe") { + return []string{"rundll32.exe", "url.dll,FileProtocolHandler", url} + } + } + return []string{"xdg-open", url} +} + +// Open opens url in the browser of the machine conch runs on, without +// waiting for it. +func Open(url string) error { + argv := Local().OpenCommand(url) + cmd := exec.Command(argv[0], argv[1:]...) + if err := cmd.Start(); err != nil { + return err + } + go func() { _ = cmd.Wait() }() + return nil +} diff --git a/internal/desktop/open_test.go b/internal/desktop/open_test.go new file mode 100644 index 00000000..da1c167e --- /dev/null +++ b/internal/desktop/open_test.go @@ -0,0 +1,119 @@ +package desktop + +import ( + "os" + "path/filepath" + "reflect" + "testing" +) + +// host builds a Host from what is on its PATH, with no environment and no +// kernel release unless the test gives one. +func host(goos string, onPath ...string) Host { + have := map[string]bool{} + for _, p := range onPath { + have[p] = true + } + return Host{ + GOOS: goos, + Getenv: func(string) string { return "" }, + Release: func() string { return "" }, + LookPath: func(name string) bool { return have[name] }, + } +} + +func TestOpenCommand(t *testing.T) { + const url = "https://example.com/a?b=1&c=2" + wsl := func(h Host) Host { + h.Getenv = func(k string) string { + if k == "WSL_DISTRO_NAME" { + return "Ubuntu" + } + return "" + } + return h + } + cases := []struct { + name string + h Host + want []string + }{ + {"mac", host("darwin"), []string{"open", url}}, + {"linux", host("linux", "xdg-open"), []string{"xdg-open", url}}, + // Nothing found is still xdg-open, so the error names what is missing. + {"linux with nothing", host("linux"), []string{"xdg-open", url}}, + {"wsl with wslu", wsl(host("linux", "wslview", "xdg-open", "rundll32.exe")), []string{"wslview", url}}, + // xdg-open is usually there on WSL with no browser behind it, so + // Windows' own handler comes first. + {"wsl without wslu", wsl(host("linux", "xdg-open", "rundll32.exe")), []string{"rundll32.exe", "url.dll,FileProtocolHandler", url}}, + // Interop turned off: no Windows programs on PATH, so the Linux way. + {"wsl without interop", wsl(host("linux", "xdg-open")), []string{"xdg-open", url}}, + {"wsl by kernel release", func() Host { + h := host("linux", "rundll32.exe") + h.Release = func() string { return "5.15.167.4-microsoft-standard-WSL2\n" } + return h + }(), []string{"rundll32.exe", "url.dll,FileProtocolHandler", url}}, + // A Windows program on PATH is not WSL by itself (Wine, a mount). + {"linux with a stray rundll32", host("linux", "xdg-open", "rundll32.exe"), []string{"xdg-open", url}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := c.h.OpenCommand(url); !reflect.DeepEqual(got, c.want) { + t.Errorf("OpenCommand = %q, want %q", got, c.want) + } + }) + } +} + +func TestIsWSL(t *testing.T) { + for _, c := range []struct { + name, goos, env, release string + want bool + }{ + {"distro variable", "linux", "Ubuntu", "", true}, + {"wsl2 kernel", "linux", "", "5.15.167.4-microsoft-standard-WSL2", true}, + {"wsl1 kernel", "linux", "", "4.4.0-19041-Microsoft", true}, + {"plain linux", "linux", "", "6.8.0-45-generic", false}, + {"empty release", "linux", "", "", false}, + // The variable can be inherited through ssh into a Mac; it is not WSL. + {"mac with the variable", "darwin", "Ubuntu", "", false}, + } { + t.Run(c.name, func(t *testing.T) { + h := host(c.goos) + h.Getenv = func(k string) string { + if k == "WSL_DISTRO_NAME" { + return c.env + } + return "" + } + h.Release = func() string { return c.release } + if got := h.IsWSL(); got != c.want { + t.Errorf("IsWSL = %v, want %v", got, c.want) + } + }) + } +} + +func TestReadRelease(t *testing.T) { + f := filepath.Join(t.TempDir(), "osrelease") + if err := os.WriteFile(f, []byte("5.15.0-microsoft-standard-WSL2\n"), 0o644); err != nil { + t.Fatal(err) + } + if got := readFile(f); got != "5.15.0-microsoft-standard-WSL2\n" { + t.Errorf("readFile = %q", got) + } + if got := readFile(filepath.Join(t.TempDir(), "missing")); got != "" { + t.Errorf("missing file read as %q", got) + } +} + +func TestLocalHostIsComplete(t *testing.T) { + h := Local() + if h.GOOS == "" || h.Getenv == nil || h.Release == nil || h.LookPath == nil { + t.Fatalf("Local() left a field empty: %+v", h) + } + // Whatever this machine is, it must name a program. + if cmd := h.OpenCommand("https://example.com"); len(cmd) < 2 || cmd[len(cmd)-1] != "https://example.com" { + t.Errorf("OpenCommand = %q", cmd) + } +} diff --git a/internal/desktop/session_test.go b/internal/desktop/session_test.go new file mode 100644 index 00000000..b1b7fa85 --- /dev/null +++ b/internal/desktop/session_test.go @@ -0,0 +1,171 @@ +package desktop + +import ( + "bufio" + "bytes" + "encoding/json" + "os" + "reflect" + "testing" +) + +// testdata/session.jsonl is a recorded session between an app and the +// bridge, and testdata/final.json the state an app holds at its end. The +// Linux and Windows apps replay the same two files as their fake bridge, +// in Rust and C#, so this test is what keeps them telling the truth: every +// line must be exactly what these types write, and applying the session +// must give exactly the final state. + +// line is one line of the recording. +type line struct { + From string `json:"from"` // app or bridge + Message Message `json:"message"` +} + +// apply is how an app keeps its state: a snapshot replaces it; a patch +// replaces each item it sets where it already is, adds a new one at the +// end, and drops the keys it removes. +func apply(s State, p Patch) State { + if p.Machines != nil { + s.Machines = applyList(s.Machines, p.Machines, func(m Machine) string { return m.ID }) + } + if p.Projects != nil { + s.Projects = applyList(s.Projects, p.Projects, func(x Project) string { return x.Key }) + } + if p.Panes != nil { + s.Panes = applyList(s.Panes, p.Panes, func(x Pane) string { return x.Key }) + } + return s +} + +func applyList[T any](list []T, c *Changes[T], key func(T) string) []T { + out := append([]T{}, list...) + for _, x := range c.Set { + i := 0 + for i < len(out) && key(out[i]) != key(x) { + i++ + } + if i < len(out) { + out[i] = x + } else { + out = append(out, x) + } + } + gone := map[string]bool{} + for _, k := range c.Remove { + gone[k] = true + } + kept := out[:0] + for _, x := range out { + if !gone[key(x)] { + kept = append(kept, x) + } + } + return kept +} + +// strict decodes data into v refusing unknown fields, and says whether +// writing v back gives the same bytes: a field the recording has that the +// types do not, or spells differently, fails here. +func strict(t *testing.T, n int, data json.RawMessage, v any) { + t.Helper() + d := json.NewDecoder(bytes.NewReader(data)) + d.DisallowUnknownFields() + if err := d.Decode(v); err != nil { + t.Fatalf("line %d: %v in %s", n, err, data) + } + again, _ := json.Marshal(reflect.ValueOf(v).Elem().Interface()) + var want bytes.Buffer + _ = json.Compact(&want, data) + if !bytes.Equal(again, want.Bytes()) { + t.Errorf("line %d is not what the bridge writes:\n got %s\n want %s", n, want.Bytes(), again) + } +} + +func TestRecordedSession(t *testing.T) { + f, err := os.Open("testdata/session.jsonl") + if err != nil { + t.Fatal(err) + } + defer f.Close() + var state State + seq := 0 + intents := map[string]string{} // id → intent + sc := bufio.NewScanner(f) + for n := 1; sc.Scan(); n++ { + var l line + d := json.NewDecoder(bytes.NewReader(sc.Bytes())) + d.DisallowUnknownFields() + if err := d.Decode(&l); err != nil { + t.Fatalf("line %d: %v", n, err) + } + m := l.Message + if again, _ := json.Marshal(m); !bytes.Contains(sc.Bytes(), again) { + t.Errorf("line %d's envelope is not what the bridge writes: %s", n, again) + } + switch { + case l.From == "app" && m.Type == TypeHello: + strict(t, n, m.Data, &AppHello{}) + case l.From == "app" && m.Type == TypeIntent: + intents[m.ID] = m.Intent + switch m.Intent { + case IntentPaneNew: + strict(t, n, m.Data, &PaneNew{}) + case IntentPaneClose, IntentPaneAttach: + strict(t, n, m.Data, &PaneRef{}) + default: + t.Errorf("line %d: intent %q is not one the bridge takes", n, m.Intent) + } + case l.From == "bridge" && m.Type == TypeHello: + strict(t, n, m.Data, &BridgeHello{}) + case l.From == "bridge" && (m.Type == TypeSnapshot || m.Type == TypePatch): + if m.Seq != seq+1 { + t.Errorf("line %d: seq %d after %d", n, m.Seq, seq) + } + seq = m.Seq + if m.Type == TypeSnapshot { + state = State{} + strict(t, n, m.Data, &state) + continue + } + var p Patch + strict(t, n, m.Data, &p) + state = apply(state, p) + case l.From == "bridge" && m.Type == TypeNotify: + strict(t, n, m.Data, &Notify{}) + case l.From == "bridge" && m.Type == TypeResult: + intent, ok := intents[m.ID] + if !ok { + t.Errorf("line %d: a result for %q, which no intent had", n, m.ID) + } + if m.OK == (m.Error != "") { + t.Errorf("line %d: a result is ok or has an error, not both or neither", n) + } + switch { + case m.Data == nil: + case intent == IntentPaneNew: + strict(t, n, m.Data, &PaneRef{}) + case intent == IntentPaneAttach: + strict(t, n, m.Data, &Attach{}) + default: + t.Errorf("line %d: %s answers with no data", n, intent) + } + default: + t.Errorf("line %d: %s does not send %q", n, l.From, m.Type) + } + } + if err := sc.Err(); err != nil { + t.Fatal(err) + } + + raw, err := os.ReadFile("testdata/final.json") + if err != nil { + t.Fatal(err) + } + var want State + strict(t, 0, raw, &want) + if !reflect.DeepEqual(state, want) { + got, _ := json.MarshalIndent(state, "", " ") + t.Errorf("the session ends in\n%s\nnot testdata/final.json", got) + } +} diff --git a/internal/desktop/testdata/final.json b/internal/desktop/testdata/final.json new file mode 100644 index 00000000..73cf8572 --- /dev/null +++ b/internal/desktop/testdata/final.json @@ -0,0 +1,12 @@ +{ + "machines": [ + {"id": "local", "label": "this computer", "state": "online"}, + {"id": "busybox", "label": "busybox", "state": "offline", "detail": "connection refused"} + ], + "projects": [ + {"key": "local:x1", "machine": "local", "id": "x1", "name": "conch", "path": "/home/amit/conch"} + ], + "panes": [ + {"key": "local:p2", "machine": "local", "id": "p2", "name": "claude", "title": "✳ Fix the parser", "project": "local:x1", "branch": "fix-parser", "state": "running", "agent": {"name": "claude", "state": "waiting", "since": "2026-11-15T12:01:00Z"}} + ] +} diff --git a/internal/desktop/testdata/session.jsonl b/internal/desktop/testdata/session.jsonl new file mode 100644 index 00000000..9efdc3fa --- /dev/null +++ b/internal/desktop/testdata/session.jsonl @@ -0,0 +1,17 @@ +{"from":"app","message":{"type":"hello","data":{"app":"conch-linux","version":"0.1.0","os":"linux"}}} +{"from":"bridge","message":{"type":"hello","data":{"protocol":1,"conch":"0.2.1","capabilities":["desktop.v1"]}}} +{"from":"bridge","message":{"type":"snapshot","seq":1,"data":{"machines":[{"id":"local","label":"this computer","state":"online"},{"id":"busybox","label":"busybox","state":"connecting"}],"projects":[{"key":"local:x1","machine":"local","id":"x1","name":"conch","path":"/home/amit/conch"}],"panes":[{"key":"local:p1","machine":"local","id":"p1","name":"zsh","state":"running"},{"key":"local:p2","machine":"local","id":"p2","name":"claude","title":"✳ Fix the parser","project":"local:x1","branch":"fix-parser","state":"running","agent":{"name":"claude","state":"working","since":"2026-11-15T12:00:00Z"}}]}}} +{"from":"bridge","message":{"type":"patch","seq":2,"data":{"machines":{"set":[{"id":"busybox","label":"busybox","state":"online"}]},"projects":{"set":[{"key":"busybox:x1","machine":"busybox","id":"x1","name":"api","path":"/srv/api"}]},"panes":{"set":[{"key":"busybox:p1","machine":"busybox","id":"p1","name":"codex","project":"busybox:x1","branch":"main","state":"running","agent":{"name":"codex","state":"idle","since":"2026-11-15T12:00:05Z"}}]}}}} +{"from":"bridge","message":{"type":"patch","seq":3,"data":{"panes":{"set":[{"key":"local:p2","machine":"local","id":"p2","name":"claude","title":"✳ Fix the parser","project":"local:x1","branch":"fix-parser","state":"running","agent":{"name":"claude","state":"waiting","since":"2026-11-15T12:01:00Z"}}]}}}} +{"from":"bridge","message":{"type":"notify","data":{"kind":"waiting","pane":"local:p2","title":"claude is waiting for you","body":"✳ Fix the parser"}}} +{"from":"app","message":{"type":"intent","id":"1","intent":"pane.attach","data":{"pane":"local:p2"}}} +{"from":"bridge","message":{"type":"result","id":"1","ok":true,"data":{"argv":["/usr/local/bin/conch","attach","p2"]}}} +{"from":"app","message":{"type":"intent","id":"2","intent":"pane.new","data":{"machine":"busybox","command":["/bin/sh"]}}} +{"from":"bridge","message":{"type":"patch","seq":4,"data":{"panes":{"set":[{"key":"busybox:p2","machine":"busybox","id":"p2","name":"sh","state":"running"}]}}}} +{"from":"bridge","message":{"type":"result","id":"2","ok":true,"data":{"pane":"busybox:p2"}}} +{"from":"app","message":{"type":"intent","id":"3","intent":"pane.close","data":{"pane":"local:p1"}}} +{"from":"bridge","message":{"type":"result","id":"3","ok":true}} +{"from":"bridge","message":{"type":"patch","seq":5,"data":{"panes":{"remove":["local:p1"]}}}} +{"from":"app","message":{"type":"intent","id":"4","intent":"pane.new","data":{"machine":"gone"}}} +{"from":"bridge","message":{"type":"result","id":"4","error":"no machine \"gone\""}} +{"from":"bridge","message":{"type":"patch","seq":6,"data":{"machines":{"set":[{"id":"busybox","label":"busybox","state":"offline","detail":"connection refused"}]},"projects":{"remove":["busybox:x1"]},"panes":{"remove":["busybox:p1","busybox:p2"]}}}} diff --git a/internal/tui/clipboard.go b/internal/tui/clipboard.go index 5b2942c6..bfd18c8a 100644 --- a/internal/tui/clipboard.go +++ b/internal/tui/clipboard.go @@ -9,6 +9,7 @@ import ( "strings" "unicode/utf8" + "github.com/Amitgb14/conch/internal/desktop" tea "github.com/charmbracelet/bubbletea" ) @@ -78,10 +79,4 @@ func openURL(url string) tea.Cmd { // openInBrowser hands a link to the desktop. A variable for the same // reason as putClipboard: tests must not open windows. -var openInBrowser = func(url string) error { - tool := "xdg-open" - if runtime.GOOS == "darwin" { - tool = "open" - } - return exec.Command(tool, url).Start() -} +var openInBrowser = desktop.Open diff --git a/web/src/app/docs/cli/page.mdx b/web/src/app/docs/cli/page.mdx index 245ca29c..bf8fc903 100644 --- a/web/src/app/docs/cli/page.mdx +++ b/web/src/app/docs/cli/page.mdx @@ -125,6 +125,15 @@ conch -m busybox attach p3 # one on another machine With `-raw` the terminal gets what the program wrote rather than conch's screen of it, so it draws the pane itself: its own scrollback, selection, search, images and cursor shapes. This is how the Mac app's Ghostty shows a pane. It starts with output that rebuilds the history and screen, then follows the program as it writes. The questions conch already answers for the program — where the cursor is, what the terminal is, its colours — are taken out, so the program is not answered twice; the ones only this terminal can answer, such as whether it draws images, still reach it. The pane's size is still settled by the server between everyone showing it: this terminal draws the output at the pane's size, and typing here makes it this terminal's. Its own answers and the pointer just moving take nothing. `-view` (with `-raw`) only looks: it never resizes the pane or takes its size. Against a server too old for it, `-raw` is the plain attach. +### desktop + +```sh +conch desktop # the bridge a desktop app runs, on stdin and stdout +wsl.exe -d Ubuntu conch desktop # the same, started by an app on Windows +``` + +`conch desktop` is what a desktop app starts and talks to: JSON lines on its stdin and stdout, never a port. It makes sure this computer's server runs and reaches every machine, then sends the app every machine's projects and panes with their agents, followed by only what changes, and a notice when an agent waits, finishes or fails. The app starts, closes and shows panes through it; showing one is the `conch attach` command the bridge hands back, run in the app's own terminal. It ends when the app closes its end. It is for the Linux and Windows apps that are planned, not something to type. + ### When an agent runs these commands An agent in a conch pane can drive conch with the same commands — start a reviewer, prompt it, read its answer. `conch agent skill -apply` teaches it how, and when to stop and ask you; [Agents working together](/docs/agents-together) walks through it with examples. What it may *change* is kept to its own work: @@ -599,6 +608,7 @@ These are run by conch itself, not by you: | Command | Used by | | --- | --- | | `conch bridge` | a remote client over ssh: connects stdio to this machine's server, starting it if needed | +| `conch desktop` | a desktop app: the bridge it talks to on stdio, every machine's panes and agents as JSON lines | | `conch report` | agent hooks and plugins, to report state to the server | ## Conch Cloud commands diff --git a/web/src/app/docs/installation/page.mdx b/web/src/app/docs/installation/page.mdx index 46450bf2..5526e0ab 100644 --- a/web/src/app/docs/installation/page.mdx +++ b/web/src/app/docs/installation/page.mdx @@ -10,6 +10,10 @@ conch is a single binary for macOS and Linux; install it one of four ways and up +On Linux, `conch app install` puts conch in the desktop's applications, opening in a terminal of its own (ghostty, kitty, foot or alacritty). On Windows, run the Linux binary inside WSL 2 from Windows Terminal: conch has no native Windows build, since it rests on Unix pseudo-terminals. + +Under WSL, links conch opens go to Windows' browser (through `wslview` if wslu is installed); copying uses the terminal's own clipboard escape, which Windows Terminal honours. + ## Install script Installs `~/.local/bin/conch` and adds conch to your desktop's applications (`CONCH_APP=no` skips that).