diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c66aa62..3321247d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,15 @@ and listed with their assets on the ## [Unreleased] +### Added + +- **"Add a stack" clones with your Git client** (ADR-0046, amendment + 2026-11-24). Below the folder field: "Not cloned yet? Clone it with + [GitHub Desktop] · Manage programs…", the Git clients checked in the path + menu's programs. Paste a repository's `https://` address instead of a + folder, and its clone dialog opens with it filled in; then paste the + folder it was cloned to. New: `POST /hub/clone`. + ### Changed - **A service's memory is what its processes own** (ADR-0119). Shared diff --git a/crates/devstack-desktop/src/lib.rs b/crates/devstack-desktop/src/lib.rs index f3c55149..9700d9f6 100644 --- a/crates/devstack-desktop/src/lib.rs +++ b/crates/devstack-desktop/src/lib.rs @@ -242,6 +242,12 @@ pub fn github_desktop_open(exe: &Path, path: &str) -> Result<(), String> { os::github_desktop_open(exe, path) } +/// GitHub Desktop (`exe` from [`github_desktop`]) on its own, with no folder: +/// to clone a repository there. +pub fn github_desktop_start(exe: &Path) -> Result<(), String> { + os::github_desktop_start(exe) +} + /// Orca's CLI: on `PATH`, or in its install folder. pub fn orca() -> Option { os::orca() diff --git a/crates/devstack-desktop/src/linux.rs b/crates/devstack-desktop/src/linux.rs index 37a76ac1..8b8fbb5d 100644 --- a/crates/devstack-desktop/src/linux.rs +++ b/crates/devstack-desktop/src/linux.rs @@ -350,6 +350,10 @@ pub fn github_desktop_open(_exe: &Path, _path: &str) -> Result<(), String> { Err("no GitHub Desktop on Linux".into()) } +pub fn github_desktop_start(_exe: &Path) -> Result<(), String> { + Err("no GitHub Desktop on Linux".into()) +} + /// Start `cmd` and let it go; a thread waits for it, so it leaves no /// zombie behind. fn detach(mut cmd: Command, what: &str) -> Result<(), String> { diff --git a/crates/devstack-desktop/src/macos.rs b/crates/devstack-desktop/src/macos.rs index 188b1f7f..25c86617 100644 --- a/crates/devstack-desktop/src/macos.rs +++ b/crates/devstack-desktop/src/macos.rs @@ -313,6 +313,13 @@ pub fn github_desktop_open(bundle: &Path, path: &str) -> Result<(), String> { run(cmd, "open GitHub Desktop") } +/// `open `: started, or the running one brought to the front. +pub fn github_desktop_start(bundle: &Path) -> Result<(), String> { + let mut cmd = Command::new("open"); + cmd.arg(bundle); + run(cmd, "open GitHub Desktop") +} + pub fn orca() -> Option { on_path("orca").or_else(|| { let p = app("Orca")?.join("Contents/Resources/bin/orca"); diff --git a/crates/devstack-desktop/src/windows.rs b/crates/devstack-desktop/src/windows.rs index 8050410a..7d890322 100644 --- a/crates/devstack-desktop/src/windows.rs +++ b/crates/devstack-desktop/src/windows.rs @@ -314,6 +314,16 @@ pub fn github_desktop_open(exe: &Path, path: &str) -> Result<(), String> { .map_err(|e| format!("start GitHub Desktop: {e}")) } +pub fn github_desktop_start(exe: &Path) -> Result<(), String> { + Command::new(exe) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .map(drop) + .map_err(|e| format!("start GitHub Desktop: {e}")) +} + pub fn orca() -> Option { on_path("orca").or_else(|| { let p = PathBuf::from(std::env::var_os("LOCALAPPDATA")?) diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index 078c9dd1..f84b380e 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -676,6 +676,7 @@ fn router(state: AppState) -> axum::Router { .route("/hub/openers", get(openers)) .route("/hub/openers/{id}/icon", get(opener_icon)) .route("/hub/open", post(open_tree)) + .route("/hub/clone", post(clone_with)) .route("/hub/prompt", get(prompt)) .route("/hub/agent", post(agent)) .route("/hub/stacks/add", post(stack_add)) @@ -2215,6 +2216,51 @@ async fn open_tree(State(s): State, Json(q): Json) -> Respo } } +#[derive(Deserialize)] +struct CloneQuery { + with: String, + #[serde(default)] + url: Option, +} + +/// `POST /hub/clone {with, url?}`: start a Git client `GET /hub/openers` +/// lists to clone a repository not on this machine yet; with an `https://` +/// address, its clone dialog with it filled in. No folder: the clone is the +/// user's, in the client (ADR-0046, amendment 2026-11-24). +async fn clone_with(Json(q): Json) -> Response { + let url = match q.url.as_deref().map(str::trim).filter(|u| !u.is_empty()) { + None => None, + Some(u) => match open::clone_url(u) { + Some(u) => Some(u.to_string()), + None => { + return err( + StatusCode::BAD_REQUEST, + "an https:// address of a repository", + ); + } + }, + }; + let started = tokio::task::spawn_blocking(move || { + open::clone(&q.with, url.as_deref()).map_err(|e| (q.with, e)) + }) + .await; + match started { + Ok(Ok(())) => StatusCode::NO_CONTENT.into_response(), + Ok(Err((with, e))) => { + let (status, msg) = match e { + open::OpenError::Failed(why) => (StatusCode::BAD_GATEWAY, why), + _ => ( + StatusCode::BAD_REQUEST, + format!("{with} is not a Git client found on this machine"), + ), + }; + diag::warn("clone_failed", serde_json::json!({ "error": msg })); + err(status, msg) + } + Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + // ------------------------------------------------- a prompt for an agent // // The page names a prompt and its target; the hub writes it (ADR-0046, diff --git a/crates/devstack-hub/src/open.rs b/crates/devstack-hub/src/open.rs index a165cfd7..aabab1f7 100644 --- a/crates/devstack-hub/src/open.rs +++ b/crates/devstack-hub/src/open.rs @@ -209,6 +209,38 @@ pub fn open(id: &str, tree: &Path, repo: &Path, stack_file: &Path) -> Result<(), .map_err(OpenError::Failed) } +/// Start the Git client `id` to clone a repository that is not on this +/// machine yet (ADR-0046, amendment 2026-11-24): with `url` (checked by +/// [`clone_url`]) its clone dialog, the address filled in; without, the +/// program alone. Where the clone goes, the user chooses there. +pub fn clone(id: &str, url: Option<&str>) -> Result<(), OpenError> { + let f = found() + .into_iter() + .find(|f| f.opener.id == id && f.opener.kind == Kind::Git) + .ok_or(OpenError::Unknown)?; + let _front = devstack_desktop::Front::take(); + match (&f.how, url) { + // Its own link: `openRepo/` opens the clone dialog. + (How::GitHubDesktop(_), Some(url)) => { + devstack_desktop::shell_open(&format!("x-github-client://openRepo/{url}")) + } + (How::GitHubDesktop(exe), None) => devstack_desktop::github_desktop_start(exe), + _ => return Err(OpenError::Unknown), + } + .map_err(OpenError::Failed) +} + +/// A repository's address as it may be handed to a Git client: `https://`, a +/// host, and only the characters of a path. No query or fragment, which the +/// client's link would read as its own parameters (`?branch=`). +pub fn clone_url(s: &str) -> Option<&str> { + let s = s.trim(); + let rest = s.strip_prefix("https://")?; + let host = rest.split('/').next()?; + let allowed = |c: char| c.is_ascii_alphanumeric() || "-._~/:@%+".contains(c); + (!host.is_empty() && s.len() <= 2048 && rest.chars().all(allowed)).then_some(s) +} + /// Start the agent `id` in `tree` with `prompt` (written by the hub, never by /// the page): a link that fills its input, or Orca's agent, which starts on /// it at once. @@ -408,6 +440,25 @@ mod tests { assert_eq!(serde_json::to_value(Kind::Git).unwrap(), "git"); } + #[test] + fn a_clone_url_is_https_and_a_plain_path() { + assert_eq!( + clone_url(" https://github.com/acme/shop.git "), + Some("https://github.com/acme/shop.git") + ); + assert_eq!( + clone_url("https://git.example.com:8443/team/shop"), + Some("https://git.example.com:8443/team/shop") + ); + assert_eq!(clone_url("http://github.com/acme/shop"), None); + assert_eq!(clone_url("git@github.com:acme/shop.git"), None); + assert_eq!(clone_url("https:///acme/shop"), None); + assert_eq!(clone_url("https://github.com/acme/shop?branch=x"), None); + assert_eq!(clone_url("https://github.com/acme/shop#x"), None); + assert_eq!(clone_url("https://github.com/acme/my shop"), None); + assert_eq!(clone_url("https://github.com/a\"b"), None); + } + #[test] fn display_drops_the_verbatim_prefix() { if cfg!(windows) { diff --git a/crates/devstack/tests/hub.rs b/crates/devstack/tests/hub.rs index e25615f6..aef44e9a 100644 --- a/crates/devstack/tests/hub.rs +++ b/crates/devstack/tests/hub.rs @@ -1770,6 +1770,32 @@ fn a_push_needs_the_hubs_own_page_and_reaches_the_remote() { assert_eq!(s, 400); } +/// Cloning starts only a Git client, and hands it only an `https://` address +/// (ADR-0046, amendment 2026-11-24): a file manager or an address with more +/// in it is refused before anything starts. +#[test] +fn clone_starts_only_a_git_client_with_a_plain_address() { + let h = start(); + let clone = |body: &str| { + http( + h.port, + &format!( + "POST /hub/clone HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nAuthorization: Bearer {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + h.port, + token(&h), + body.len() + ), + ) + }; + let (s, _, body) = clone(r#"{"with":"files"}"#); + assert_eq!(s, 400, "{body}"); + assert!(body.contains("not a Git client"), "{body}"); + let (s, _, body) = + clone(r#"{"with":"github-desktop","url":"https://github.com/acme/shop?branch=x"}"#); + assert_eq!(s, 400, "{body}"); + assert!(body.contains("https://"), "{body}"); +} + /// A program's icon (ADR-0046, addendum 2026-11-23): a PNG for a program /// found here, cached by the browser; 404 for one that is not, which the /// page answers with the kind's icon. Explorer is on every Windows desktop; diff --git a/docs/adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md b/docs/adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md index 3ea4e2af..698f66b2 100644 --- a/docs/adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md +++ b/docs/adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md @@ -1,6 +1,6 @@ # ADR-0046: The hub opens a stack's worktree in the user's own programs, from a fixed list -- **Status:** Accepted (2026-10-21), amended 2026-10-21 (the program opens in front on Windows; GitHub Desktop), amended 2026-10-22 (an agent started with a prompt the hub writes; the upgrade goes by `[stack] reviewed`) +- **Status:** Accepted (2026-10-21), amended 2026-10-21 (the program opens in front on Windows; GitHub Desktop), amended 2026-10-22 (an agent started with a prompt the hub writes; the upgrade goes by `[stack] reviewed`), amended 2026-11-24 (a Git client started to clone a repository) - **Date:** 2026-10-21 - **Deciders:** project owner - **Related:** [ADR-0011](0011-platform-windows-native-first.md), [ADR-0019](0019-control-api-security.md), [ADR-0021](0021-a-hub-serves-the-dashboard.md), [ADR-0024](0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md), [ADR-0040](0040-a-shared-lane-can-be-watched-like-ones-own.md) @@ -179,6 +179,37 @@ conversation on 2026-11-23 (all five): 5. **In its own colours** (term), beside the label; the dialog still names the kind in words. +## Amendment 2026-11-24: a Git client started to clone a repository + +"Add a stack" takes a repository's folder. A repository that is not on this +machine yet has none; cloning it is a Git client's (ADR-0047 point 8), and +the list already knows one. Points approved by the owner on 2026-11-24: + +1. **A request of its own.** `POST /hub/clone {with, url?}` starts a + program of the kind `git` from `GET /hub/openers` without a folder. + `/hub/open` keeps its check (point 3 above): only a stack's own trees. +2. **The page names the program, not a command.** Without `url` the + program starts as from the start menu (GitHub Desktop: its launcher, + no arguments). +3. **An https address goes to the clone dialog.** With `url`, GitHub + Desktop's own link `x-github-client://openRepo/` opens its clone + dialog with the address filled in; the user confirms the clone there. + The hub takes only `https://`, a host and the characters of a path + (letters, digits, `-._~/:@%+`), at most 2048 characters: no query or + fragment, which the link would read as its own parameters (`?branch=`), + no space or quote. Anything else is refused (`400`). +4. **In "Add a stack".** Below the folder field, and in the note "No folder + at …": "Not cloned yet? Clone it with [client] · Manage programs…". An + address pasted into the field is not checked as a folder: an `https://` + one is handed to the client, another (`git@…`, `http://`) is not, and + the dialog says to paste it into the client's dialog. +5. **The path menu's choice.** The clients offered are the Git clients + checked in "Manage programs…" (in this browser); none found, no line; + all unchecked, only "Manage programs…". +6. **The folder is the user's.** Where the clone goes, the user chooses in + the client and pastes the folder afterwards; the hub does not watch for + it. + ## Consequences - The hub starts programs on request of the page. Narrowed by point 3: a @@ -212,6 +243,9 @@ conversation on 2026-11-23 (all five): `/hub/agent`). - `crates/devstack-hub/src/prompts.rs` (the prompts), `ui/src/components/AgentPrompt.vue` (copy, show, start). +- `open::clone` and `open::clone_url`, route `/hub/clone`; + `ui/src/components/CloneWith.vue` in `AddStackDialog.vue`; + `crates/devstack/tests/hub.rs` (`clone_starts_only_a_git_client_with_a_plain_address`). ## What this ADR does not say diff --git a/docs/adr/README.md b/docs/adr/README.md index af2b149f..b7bf2031 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -128,7 +128,7 @@ stay. | [0043](0043-a-dev-servers-fixed-port-is-devstacks.md) | A dev server's fixed port is devstack's, forwarded to its instance | Accepted | | [0044](0044-a-lanes-prepared-directories-can-be-linked-into-its-worktree.md) | A lane's prepared directories can be linked into its worktree | Accepted; point 5 replaced for lanes on a node by ADR-0063; `link` ⊆ `outputs` by ADR-0062 | | [0045](0045-the-hub-notifies-the-desktop.md) | The hub notifies the desktop of what needs attention, without a tray | Accepted, amended 2026-10-21 (`guest_lane`), amended 2026-11-20 (`machine_asks`, ADR-0116) | -| [0046](0046-the-hub-opens-a-worktree-in-the-users-programs.md) | The hub opens a stack's worktree in the user's own programs, from a fixed list | Accepted, amended 2026-10-21 (the program opens in front on Windows; GitHub Desktop), 2026-10-22 (an agent started with a prompt the hub writes), 2026-11-23 (each program's own icon) | +| [0046](0046-the-hub-opens-a-worktree-in-the-users-programs.md) | The hub opens a stack's worktree in the user's own programs, from a fixed list | Accepted, amended 2026-10-21 (the program opens in front on Windows; GitHub Desktop), 2026-10-22 (an agent started with a prompt the hub writes), 2026-11-23 (each program's own icon), 2026-11-24 (a Git client started to clone a repository) | | [0047](0047-the-dashboard-makes-a-lane-from-a-branch.md) | The dashboard makes a lane from a branch; the main tree's checkout stays the user's | Accepted; a branch without a stack file by ADR-0055; ahead and behind by ADR-0088; push by ADR-0117 | | [0048](0048-a-containers-main-port-can-move-with-the-main-slot.md) | A container's main port can be devstack's, and then moves with the main slot | Accepted; point 2 detailed by ADR-0057 (an announced port is not held) | | [0049](0049-a-lanes-need-is-measured-disk-included.md) | A lane's need is measured where it ran, disk included; the stack file sets a floor | Accepted, amended 2026-10-21 (point 9: what a lane here checks); how a node hands a GPU over, ADR-0112 | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index df679011..642ec670 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -79,6 +79,7 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `PUT /hub/mcp/scope` | cookie | `{agents: {: "repository"\|"user"}}`: `user` writes the entry `devstack` into the agent's user configuration (only that entry, the rest of the file kept), `repository` removes the entry the hub wrote (one the user had before stays); answers as `GET`, an agent's `error` saying why its file was not changed; 400 for an unknown agent | | `GET /hub/openers/{id}/icon` | cookie | the program's own icon as this machine shows it, read from the installed program ([ADR-0046](adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md), addendum 2026-11-23): `200` `image/png` (32 px, `Cache-Control: private, max-age=86400`); `404 {"error"}` for an id not found here or a program without one, and always on macOS and Linux for now. The page then shows the kind's icon | | `POST /hub/open {"stack", "path", "with"}` | cookie + Origin | open `path` with the program `with`: `204`. `path` must be the stack's repository or one of its worktrees (`git worktree list`), `with` an id `GET /hub/openers` lists now; `400` otherwise, `404` for an unknown stack, `502 {"error"}` when the program could not be started | +| `POST /hub/clone {"with", "url"?}` | cookie + Origin | start the Git client `with` to clone a repository not on this machine yet ([ADR-0046](adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md), amendment 2026-11-24): `204`. With `url`, its clone dialog with the address filled in (GitHub Desktop: `x-github-client://openRepo/`); without, the program alone. `with` must be an id of `kind: "git"` `GET /hub/openers` lists now; `url` an `https://` address with a host and only the characters of a path (no query, fragment or space); `400` otherwise, `502 {"error"}` when the program could not be started | | `GET /hub/prompt?kind=&stack=`, `?kind=&path=` or `?kind=&stack=&path=` | cookie | a prompt for a coding agent, written by the hub ([ADR-0046](adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md), amendment 2026-10-22): `{text, path}`, `path` the folder it works in. `kind` with `path` (a folder, checked as for `/hub/inspect`): `setup` (a stack file to write; says whether a draft is there), `fix-file` (one that does not load: `409` when there is none or it loads). With `stack`: `upgrade` (from the devstack `/hub/stacks/{id}/upgrade` names to this one), `start-failed` (the end of the last failed start from the dashboard and its log; `409` when there is none), `mcp` (register `devstack mcp` in the project's agent configuration, next to the servers there). `setup` and `upgrade` offer the same registration, suggested yes. With `stack` and `path`: `lane-file` (a linked worktree of the stack without a stack file of its own: take the main tree's over and adapt it to the branch, [ADR-0055](adr/0055-a-lane-without-a-stack-file-says-so-and-can-be-given-one.md); `path` in the answer is the worktree, `400` for anything else), `lane-image` (a worktree of the stack, the main one too, whose lane cannot go to a node because the stack file it runs with names no lane image: name one, [ADR-0028](adr/0028-lane-images.md) addendum 2026-10-29; `path` in the answer is the folder of that file, `409` when it names one). `400` for another kind or a missing target, `404` for an unknown stack. Below 5,000 characters: what is quoted is cut | | `POST /hub/agent {"kind", "stack" \| "path" \| both, "with"}` | cookie + Origin | start the agent `with` in the prompt's folder with the prompt `GET /hub/prompt` writes for the same `kind` and target: `204`. The page never sends text. `with` must be an id `GET /hub/openers` lists now with `prompt`; `400` otherwise, the refusals of `/hub/prompt`, `502 {"error"}` when the program could not be started | | `GET /hub/inspect?path=` | cookie | `{repo, is_dir, has_stack_file, valid, registered, id}` for an absolute folder path (the "Add a stack" dialog). `valid` is `null` without a stack file, `{"Ok":null}` when it loads, `{"Err":""}` when not; `registered` is the id or `null`. Every route that takes a `path` takes a local one only: `400` for a network path (`\\host\share`, `//host/share`; on Windows anything but a drive, `C:\` or `\\?\C:\`) | diff --git a/ui/src/api/mock/index.ts b/ui/src/api/mock/index.ts index 3284f8f0..30864b7f 100644 --- a/ui/src/api/mock/index.ts +++ b/ui/src/api/mock/index.ts @@ -973,6 +973,7 @@ export class MockTransport implements Transport { { id: 'orca', label: 'Orca', kind: 'agent', prompt: 'send' }, ]); if (p === '/hub/open' && method === 'POST') return empty(204); + if (p === '/hub/clone' && method === 'POST') return empty(204); // The hub writes the prompts (ADR-0046, amendment 2026-10-22); the mock's are short. if (p === '/hub/prompt' && method === 'GET') { const kind = url.searchParams.get('kind'); diff --git a/ui/src/api/transport.ts b/ui/src/api/transport.ts index 184041f7..3f869c38 100644 --- a/ui/src/api/transport.ts +++ b/ui/src/api/transport.ts @@ -59,6 +59,7 @@ export const paths = { openers: '/hub/openers', openerIcon: (id: string) => `/hub/openers/${encodeURIComponent(id)}/icon`, open: '/hub/open', + clone: '/hub/clone', prompt: (kind: string, target: { stack?: string; path?: string }) => `/hub/prompt?kind=${encodeURIComponent(kind)}${target.stack !== undefined ? `&stack=${encodeURIComponent(target.stack)}` : ''}${target.path !== undefined ? `&path=${encodeURIComponent(target.path)}` : ''}`, agent: '/hub/agent', diff --git a/ui/src/components/AddStackDialog.test.ts b/ui/src/components/AddStackDialog.test.ts new file mode 100644 index 00000000..395e0e17 --- /dev/null +++ b/ui/src/components/AddStackDialog.test.ts @@ -0,0 +1,121 @@ +// "Add a stack" for a repository not cloned yet: the path menu's Git clients +// start to clone it, an https address pasted into the field goes to their +// clone dialog, and an address is never checked as a folder. +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { createApp, h, nextTick } from 'vue'; +import { createPinia, setActivePinia } from 'pinia'; +import { createMemoryHistory, createRouter } from 'vue-router'; +import { FakeTransport, ok } from '@/test/fake'; + +const t = vi.hoisted(() => ({ current: null as FakeTransport | null })); + +vi.mock('@/api', async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + api: () => { + if (!t.current) throw new Error('no fake transport'); + return t.current; + }, + }; +}); + +const { useOpenerPrefs } = await import('@/lib/openers'); +const AddStackDialog = (await import('./AddStackDialog.vue')).default; + +let fake: FakeTransport; + +beforeEach(() => { + localStorage.clear(); + document.body.innerHTML = ''; + setActivePinia(createPinia()); + fake = new FakeTransport(); + t.current = fake; + fake.on('/hub/openers', ok([ + { id: 'vscode', label: 'VS Code', kind: 'editor' }, + { id: 'github-desktop', label: 'GitHub Desktop', kind: 'git' }, + ])); + fake.on('/hub/clone', { status: 204, ok: true, body: null }); + useOpenerPrefs().save({ order: [], hidden: [], favorites: [] }); +}); + +async function settle() { + for (let i = 0; i < 5; i++) { + await new Promise((r) => setTimeout(r, 0)); + await nextTick(); + } +} + +function mount() { + const el = document.createElement('div'); + document.body.appendChild(el); + const app = createApp(() => h(AddStackDialog, { open: true })); + app.use(createPinia()); + app.use(createRouter({ history: createMemoryHistory(), routes: [{ path: '/', component: { render: () => null } }] })); + app.mount(el); + return app; +} + +const q = (id: string) => document.body.querySelectorAll(`[data-testid="${id}"]`); + +async function type(value: string) { + const input = document.body.querySelector('[data-testid="add-stack-path"]')!; + input.value = value; + input.dispatchEvent(new Event('input')); + await settle(); +} + +describe('AddStackDialog, cloning', () => { + it('offers the Git clients only, and starts one without an address', async () => { + const app = mount(); + await settle(); + const buttons = q('clone-with-open'); + expect([...buttons].map((b) => b.dataset.id)).toEqual(['github-desktop']); + buttons[0].click(); + await settle(); + expect(fake.requests.find((r) => r.path === '/hub/clone')?.body).toEqual({ with: 'github-desktop' }); + app.unmount(); + }); + + it('hands a pasted https address to the clone dialog and does not check it as a folder', async () => { + const app = mount(); + await settle(); + await type('https://github.com/acme/shop.git'); + await new Promise((r) => setTimeout(r, 500)); + expect(fake.requests.some((r) => r.path.startsWith('/hub/inspect'))).toBe(false); + q('clone-with-open')[0].click(); + await settle(); + expect(fake.requests.find((r) => r.path === '/hub/clone')?.body).toEqual({ with: 'github-desktop', url: 'https://github.com/acme/shop.git' }); + app.unmount(); + }); + + it('says that an ssh address is not handed over', async () => { + const app = mount(); + await settle(); + await type('git@github.com:acme/shop.git'); + expect(q('add-stack-not-https')).toHaveLength(1); + q('clone-with-open')[0].click(); + await settle(); + expect(fake.requests.find((r) => r.path === '/hub/clone')?.body).toEqual({ with: 'github-desktop' }); + app.unmount(); + }); + + it('keeps the way to the programs when the Git client is unchecked', async () => { + useOpenerPrefs().save({ order: [], hidden: ['github-desktop'], favorites: [] }); + const app = mount(); + await settle(); + expect(q('clone-with-open')).toHaveLength(0); + expect(q('clone-with-manage')).toHaveLength(1); + app.unmount(); + }); + + it('shows nothing where no Git client is found', async () => { + fake = new FakeTransport(); + t.current = fake; + fake.on('/hub/openers', ok([{ id: 'vscode', label: 'VS Code', kind: 'editor' }])); + const app = mount(); + await settle(); + expect(q('clone-with')).toHaveLength(0); + app.unmount(); + }); +}); diff --git a/ui/src/components/AddStackDialog.vue b/ui/src/components/AddStackDialog.vue index 78f6c52d..7572dc7e 100644 --- a/ui/src/components/AddStackDialog.vue +++ b/ui/src/components/AddStackDialog.vue @@ -10,6 +10,7 @@ import { useRouter } from 'vue-router'; import { api, paths } from '@/api'; import { act } from '@/lib/actions'; import AgentPrompt from './AgentPrompt.vue'; +import CloneWith from './CloneWith.vue'; import FolderField from './FolderField.vue'; import Modal from './Modal.vue'; import Icon from './icons/Icon.vue'; @@ -50,15 +51,20 @@ watch( clearTimeout(timer); info.value = null; problem.value = null; - if (path.value.trim()) timer = setTimeout(check, 450); + if (path.value.trim() && !address.value) timer = setTimeout(check, 450); }, { flush: 'sync' }, ); +/** A repository's address pasted instead of a folder: it is cloned first. */ +const address = computed(() => /^([a-z][a-z0-9+.-]*:\/\/|[\w.-]+@[\w.-]+:)/i.test(path.value.trim())); +/** Only an https address goes to the Git client's clone dialog. */ +const httpsUrl = computed(() => (address.value && /^https:\/\//i.test(path.value.trim()) ? path.value.trim() : undefined)); + async function check() { clearTimeout(timer); const p = path.value.trim(); - if (!p) return; + if (!p || address.value) return; checking.value = true; problem.value = null; info.value = null; @@ -113,12 +119,21 @@ async function add() {