From c53a89d931b4270546c531b4719004356fc227eb Mon Sep 17 00:00:00 2001 From: CarmenDou <80885297+CarmenDou@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:51:22 -0500 Subject: [PATCH 01/23] Add workspace key create and revoke, and exec envs without history Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/agents.rs | 1 + src-tauri/src/api/mod.rs | 113 +++++++++++++++++++++++++++++ src-tauri/src/api/types.rs | 25 ++++++- src-tauri/src/app.rs | 1 + src-tauri/src/github.rs | 1 + src-tauri/src/repos.rs | 2 + src-tauri/src/sandbox/connect.rs | 6 ++ src-tauri/src/sandbox/lifecycle.rs | 1 + src-tauri/src/sandbox/sync.rs | 1 + src-tauri/src/t3proxy/hub.rs | 2 + 10 files changed, 152 insertions(+), 1 deletion(-) diff --git a/src-tauri/src/agents.rs b/src-tauri/src/agents.rs index e4965f4..2dfaa91 100644 --- a/src-tauri/src/agents.rs +++ b/src-tauri/src/agents.rs @@ -199,6 +199,7 @@ async fn exec(client: &Client, id: &str, cmd: String) -> Result { let req = ExecRequest { cmd, timeout_seconds: Some(EXEC_TIMEOUT_SECS), + ..Default::default() }; Ok(client.exec(id, &req).await?) } diff --git a/src-tauri/src/api/mod.rs b/src-tauri/src/api/mod.rs index 99d3920..c913104 100644 --- a/src-tauri/src/api/mod.rs +++ b/src-tauri/src/api/mod.rs @@ -403,6 +403,36 @@ impl Client { })); self.call(r).await } + + /// A key of org `org`, personal or workspace. Needs a sign-in session of someone who + /// manages the org. + pub async fn create_org_api_key( + &self, + org: &str, + name: &str, + scopes: &[&str], + expires_in_days: u32, + ) -> Result { + let r = Req::new(Method::POST, &["v1", "orgs", org, "keys"]).json(&serde_json::json!({ + "name": name, "scopes": scopes, "expiresInDays": expires_in_days + })); + self.call(r).await + } + + /// Revokes key `key_id` of org `org`. A key that is already gone counts as revoked. + pub async fn revoke_org_api_key(&self, org: &str, key_id: &str) -> Result<()> { + match self + .send(Req::new( + Method::DELETE, + &["v1", "orgs", org, "keys", key_id], + )) + .await + { + Ok(_) => Ok(()), + Err(e) if e.status == 404 => Ok(()), + Err(e) => Err(e), + } + } } fn decode(bytes: &[u8]) -> Result { @@ -763,6 +793,7 @@ mod tests { &ExecRequest { cmd: "true".into(), timeout_seconds: None, + ..Default::default() }, ) .await @@ -775,4 +806,86 @@ mod tests { "a reply without background is an ordinary token" ); } + + #[tokio::test] + async fn creates_a_workspace_key_for_the_org() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v1/orgs/o1/keys")) + .and(wiremock::matchers::body_json(serde_json::json!({ + "name": "Amp orbs", + "scopes": ["machines:read", "images:read"], + "expiresInDays": 365 + }))) + .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({ + "apiKey": {"id": "wkey_1", "name": "Amp orbs", "prefix": "abcd1234", + "scopes": ["machines:read"], "createdAt": "2026-12-03T00:00:00Z", + "lastUsedAt": null, "expiresAt": "2027-12-03T00:00:00Z"}, + "key": "ibk_x" + }))) + .expect(1) + .mount(&server) + .await; + let (c, _) = client(&server); + let k = c + .create_org_api_key("o1", "Amp orbs", &["machines:read", "images:read"], 365) + .await + .unwrap(); + assert_eq!(k.key, "ibk_x"); + assert_eq!(k.api_key.id, "wkey_1"); + assert_eq!( + k.api_key.expires_at.as_deref(), + Some("2027-12-03T00:00:00Z") + ); + } + + #[tokio::test] + async fn revoking_a_gone_key_is_fine() { + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .and(path("/v1/orgs/o1/keys/wkey_1")) + .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!( + {"error": {"code": "not_found", "message": "key not found", "retryable": false}}))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/v1/orgs/o1/keys/wkey_2")) + .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!( + {"error": {"code": "permission_denied", "message": "no", "retryable": false}}))) + .expect(1) + .mount(&server) + .await; + let (c, _) = client(&server); + c.revoke_org_api_key("o1", "wkey_1").await.unwrap(); + let e = c.revoke_org_api_key("o1", "wkey_2").await.unwrap_err(); + assert_eq!(e.status, 403); + } + + #[test] + fn exec_sends_envs_without_history() { + let plain = ExecRequest { + cmd: "true".into(), + timeout_seconds: Some(5), + ..Default::default() + }; + assert_eq!( + serde_json::to_value(&plain).unwrap(), + serde_json::json!({"cmd": "true", "timeoutSeconds": 5}), + "a request without envs is sent as before" + ); + let secret = ExecRequest { + cmd: "x".into(), + timeout_seconds: None, + envs: Some(std::collections::BTreeMap::from([( + "K".to_string(), + "v".to_string(), + )])), + no_history: true, + }; + assert_eq!( + serde_json::to_value(&secret).unwrap(), + serde_json::json!({"cmd": "x", "envs": {"K": "v"}, "noHistory": true}) + ); + } } diff --git a/src-tauri/src/api/types.rs b/src-tauri/src/api/types.rs index e0cdf9a..6d2e838 100644 --- a/src-tauri/src/api/types.rs +++ b/src-tauri/src/api/types.rs @@ -199,12 +199,19 @@ pub struct UpdateMachineRequest { pub apply: Option, } -#[derive(Debug, Clone, PartialEq, Serialize)] +#[derive(Debug, Clone, Default, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct ExecRequest { pub cmd: String, #[serde(skip_serializing_if = "Option::is_none")] pub timeout_seconds: Option, + /// Environment of the command. Values never appear in `cmd`, so a secret sent here + /// stays out of the command text the sandbox keeps. + #[serde(skip_serializing_if = "Option::is_none")] + pub envs: Option>, + /// Keeps the command out of the sandbox's exec history. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub no_history: bool, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] @@ -246,6 +253,22 @@ pub struct CreatedApiKey { pub key: String, } +/// Answer to `POST /v1/orgs/{id}/keys`. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CreatedOrgKey { + pub key: String, + pub api_key: OrgKeyInfo, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OrgKeyInfo { + pub id: String, + #[serde(default)] + pub expires_at: Option, +} + /// Sign-in session tokens. Stored in the keychain as JSON. #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rs index 08895e9..51060b4 100644 --- a/src-tauri/src/app.rs +++ b/src-tauri/src/app.rs @@ -3192,6 +3192,7 @@ impl Core { let req = crate::api::ExecRequest { cmd: probe.script(), timeout_seconds: Some(PROBE_TIMEOUT_SECS), + ..Default::default() }; let failed = match client.exec(&key.0, &req).await { Ok(r) if r.exit_code == 0 && !r.timed_out => { diff --git a/src-tauri/src/github.rs b/src-tauri/src/github.rs index b3faf97..ecda605 100644 --- a/src-tauri/src/github.rs +++ b/src-tauri/src/github.rs @@ -196,6 +196,7 @@ async fn exec(client: &Client, id: &str, cmd: String) -> Result { let req = ExecRequest { cmd, timeout_seconds: Some(EXEC_TIMEOUT_SECS), + ..Default::default() }; Ok(client.exec(id, &req).await?) } diff --git a/src-tauri/src/repos.rs b/src-tauri/src/repos.rs index 58c1dba..61898c2 100644 --- a/src-tauri/src/repos.rs +++ b/src-tauri/src/repos.rs @@ -171,6 +171,7 @@ pub async fn list(client: &Client, id: &str) -> Result { let req = ExecRequest { cmd: list_command(), timeout_seconds: Some(EXEC_TIMEOUT_SECS), + ..Default::default() }; parse_list(&client.exec(id, &req).await?) } @@ -253,6 +254,7 @@ pub async fn folder(client: &Client, id: &str, repo: &RepoName) -> Result Result Result Date: Fri, 4 Dec 2026 00:00:18 -0500 Subject: [PATCH 02/23] Add the Amp orbs provider program and its setup flows amp-orbs is the dispatch program Amp's orb provider runs on an always-on provider sandbox: it starts, pauses (saving a project snapshot) and deletes one instabox sandbox per Amp thread with the instabox CLI. It imports Amp's orb image as the base snapshot every day. orbs.rs mints a workspace key, creates or repairs the provider and installs the program with the key sent as exec env. Co-Authored-By: Claude Opus 5.5 --- .../assets/amp-orbs/amp-orb-image.service | 13 + src-tauri/assets/amp-orbs/amp-orb-image.timer | 10 + .../assets/amp-orbs/amp-orb-provider.service | 17 + src-tauri/assets/amp-orbs/amp-orbs | 398 +++++ src-tauri/examples/e2e.rs | 1 + src-tauri/src/lib.rs | 1 + src-tauri/src/orbs.rs | 1325 +++++++++++++++++ 7 files changed, 1765 insertions(+) create mode 100644 src-tauri/assets/amp-orbs/amp-orb-image.service create mode 100644 src-tauri/assets/amp-orbs/amp-orb-image.timer create mode 100644 src-tauri/assets/amp-orbs/amp-orb-provider.service create mode 100755 src-tauri/assets/amp-orbs/amp-orbs create mode 100644 src-tauri/src/orbs.rs diff --git a/src-tauri/assets/amp-orbs/amp-orb-image.service b/src-tauri/assets/amp-orbs/amp-orb-image.service new file mode 100644 index 0000000..b6bfccc --- /dev/null +++ b/src-tauri/assets/amp-orbs/amp-orb-image.service @@ -0,0 +1,13 @@ +[Unit] +Description=Import Amp's orb image as the base snapshot of new orbs +After=network-online.target instabox-data-init.service +Wants=network-online.target +RequiresMountsFor=/data + +[Service] +Type=oneshot +User=__USER__ +EnvironmentFile=/etc/amp-orbs/env +WorkingDirectory=__HOME__ +ExecStart=/usr/local/bin/amp-orbs image build +TimeoutStartSec=2h diff --git a/src-tauri/assets/amp-orbs/amp-orb-image.timer b/src-tauri/assets/amp-orbs/amp-orb-image.timer new file mode 100644 index 0000000..983a40d --- /dev/null +++ b/src-tauri/assets/amp-orbs/amp-orb-image.timer @@ -0,0 +1,10 @@ +[Unit] +Description=Update the Amp orb image every day + +[Timer] +OnCalendar=daily +RandomizedDelaySec=1h +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/src-tauri/assets/amp-orbs/amp-orb-provider.service b/src-tauri/assets/amp-orbs/amp-orb-provider.service new file mode 100644 index 0000000..d387970 --- /dev/null +++ b/src-tauri/assets/amp-orbs/amp-orb-provider.service @@ -0,0 +1,17 @@ +[Unit] +Description=Amp orbs provider for instabox +After=network-online.target instabox-data-init.service +Wants=network-online.target +RequiresMountsFor=/data +StartLimitIntervalSec=0 + +[Service] +User=__USER__ +EnvironmentFile=/etc/amp-orbs/env +WorkingDirectory=__HOME__ +ExecStart=/usr/local/bin/amp-orbs serve +Restart=always +RestartSec=10 + +[Install] +WantedBy=multi-user.target diff --git a/src-tauri/assets/amp-orbs/amp-orbs b/src-tauri/assets/amp-orbs/amp-orbs new file mode 100755 index 0000000..783ec8b --- /dev/null +++ b/src-tauri/assets/amp-orbs/amp-orbs @@ -0,0 +1,398 @@ +#!/usr/bin/env bash +# amp-orbs: runs Amp orbs on instabox sandboxes. InstaADE installs it on the provider sandbox. +# +# amp-orbs with ORB_OPERATION set: Amp's dispatch (spawn, pause, delete) +# amp-orbs serve runs `amp orb provider` with this program as its dispatch +# amp-orbs connect signs in to Amp and adds this sandbox as an orb provider +# amp-orbs status prints one JSON line for InstaADE +# amp-orbs image build imports Amp's orb image as the base snapshot of new orbs +# amp-orbs purge deletes the orb snapshots before the provider goes away +# +# Every instabox call reads /dev/null: exec refuses piped input, and Amp's pipes are not ours. +# Bash 3.2 compatible (the tests run on macOS). + +set -o pipefail + +VERSION=1 +ENV_FILE=${AMP_ORBS_ENV_FILE:-/etc/amp-orbs/env} +STATE_DIR=${AMP_ORBS_STATE_DIR:-/var/lib/amp-orbs} +POLL=${AMP_ORBS_POLL:-2} +SELF=${AMP_ORBS_SELF:-/usr/local/bin/amp-orbs} +IMAGE_DEFAULT=us-central1-docker.pkg.dev/amp-prod-0/amp-orb/amp-orb:latest +PROVIDER_NAME=instabox +ROLE_KEY=instabox-role +ROLE_ORB=amp-orb +ID_KEY=amp-orb-id +BASE_PREFIX=amp-orb-base- +SNAP_PREFIX=amp-orb-snap- +BUILDER=amp-orb-builder +TOKEN_PREFIX=orb-provider-token@ + +if [ -r "$ENV_FILE" ]; then + set -a + # shellcheck disable=SC1090 + . "$ENV_FILE" + set +a +fi +export INSTABOX_NO_UPDATE_CHECK=1 INSTABOX_QUIET=1 INSTABOX_NO_TELEMETRY=1 + +log() { printf 'amp-orbs: %s\n' "$*" >&2; } +die() { log "$*"; exit 1; } + +# ib runs the instabox CLI. Its stderr goes to $IB_ERR, so a failure can say why. +IB_ERR=$(mktemp "${TMPDIR:-/tmp}/amp-orbs.XXXXXX") || exit 1 +trap 'rm -f "$IB_ERR"' EXIT +ib() { instabox "$@" "$IB_ERR"; } +ib_why() { tail -n 3 "$IB_ERR" | tr '\n' ' ' | sed 's/ *$//'; } + +# --- the orb's sandbox --------------------------------------------------------------------- + +orb_name() { printf '%s' "$ORB_ID" | tr 'A-Z' 'a-z'; } + +# lookup sets BOX_ID and BOX_STATE. Returns 1 when there is no such sandbox. A sandbox of that +# name that is not this orb is never touched. +lookup() { + local out rc + out=$(ib get "$NAME" --json) + rc=$? + if [ "$rc" = 4 ]; then BOX_ID=; BOX_STATE=; return 1; fi + [ "$rc" = 0 ] || die "Cannot read sandbox $NAME: $(ib_why)" + local role id + role=$(printf '%s' "$out" | jq -r --arg k "$ROLE_KEY" '.metadata[$k] // ""') + id=$(printf '%s' "$out" | jq -r --arg k "$ID_KEY" '.metadata[$k] // ""') + if [ "$role" != "$ROLE_ORB" ] || [ "$id" != "$ORB_ID" ]; then + die "Sandbox $NAME exists and is not this orb. Rename or delete it." + fi + BOX_ID=$(printf '%s' "$out" | jq -r '.id') + BOX_STATE=$(printf '%s' "$out" | jq -r '.state') + return 0 +} + +past_deadline() { [ "$SECONDS" -ge "$DEADLINE" ]; } + +# settle waits while the sandbox is changing state. Returns 1 when it is gone. +settle() { + while :; do + case "$BOX_STATE" in + creating|starting|resuming|suspending|stopping) ;; + *) return 0 ;; + esac + past_deadline && die "Sandbox $NAME is still $BOX_STATE" + sleep "$POLL" + lookup || return 1 + done +} + +# snap_prefix prints the name prefix of the snapshots that hold Amp project snapshot $1. +snap_prefix() { + local id=$1 clean max=101 + clean=$(printf '%s' "$id" | tr -c 'A-Za-z0-9._-' '-') + if [ "$clean" != "$id" ] || [ "${#clean}" -gt "$max" ]; then + local sum + sum=$(printf '%s' "$id" | cksum | awk '{printf "%08x", $1}') + clean="${clean:0:92}-$sum" + fi + printf '%s%s-' "$SNAP_PREFIX" "$clean" +} + +# newest prints "id sizeLocked" of the newest ready snapshot named $1 plus 10-13 digits. +newest() { + printf '%s' "$SNAPSHOTS" | jq -r --arg p "$1" ' + [ .[] | select(.status == "ready" and (.name | startswith($p)) + and (.name[($p | length):] | test("^[0-9]{10,13}$"))) ] + | sort_by(.createdAt, .name) | last // empty + | "\(.id) \(.sizeLocked // false)"' +} + +# source_snapshot sets SRC_ID and SRC_LOCKED: the newest project snapshot of the thread, or the +# newest base snapshot. +source_snapshot() { + SNAPSHOTS=$(ib snapshot ls --json) || die "Cannot list snapshots: $(ib_why)" + local pick= + if [ -n "$ORB_SNAPSHOT_ID" ]; then pick=$(newest "$(snap_prefix "$ORB_SNAPSHOT_ID")"); fi + [ -n "$pick" ] || pick=$(newest "$BASE_PREFIX") + [ -n "$pick" ] || die "No orb image yet. It builds after setup and takes about 5 minutes." + SRC_ID=${pick%% *} + SRC_LOCKED=${pick#* } +} + +create_orb() { + source_snapshot + local size=${AMP_ORBS_SIZE:-4/8192} + set -- create --name "$NAME" --snapshot "$SRC_ID" --user user --auto-suspend 0 \ + --meta "$ROLE_KEY=$ROLE_ORB" --meta "$ID_KEY=$ORB_ID" --no-vault --ready-timeout 240s --json + if [ "$SRC_LOCKED" != true ]; then set -- "$@" --vcpus "${size%/*}" --mem-mib "${size#*/}"; fi + log "Creating $NAME" + if ! ib "$@" >/dev/null; then + # Another job may have made it first: the lookup decides. + local why + why=$(ib_why) + lookup || die "Cannot create sandbox $NAME: $why" + fi +} + +record_image() { + # Amp says which image its orbs want; the next image build uses it. + [ -n "$ORB_IMAGE" ] || return 0 + mkdir -p "$STATE_DIR" 2>/dev/null && printf '%s\n' "$ORB_IMAGE" >"$STATE_DIR/orb-image-ref" 2>/dev/null + return 0 +} + +spawn() { + [ -n "$ORB_TOKEN" ] || die "ORB_TOKEN is missing" + record_image + local created=0 + lookup + while [ "$BOX_STATE" != running ]; do + past_deadline && die "Sandbox $NAME did not start in time" + case "$BOX_STATE" in + "") + [ "$created" = 0 ] || die "Sandbox $NAME went away after it was created" + created=1 + create_orb ;; + suspended) + log "Resuming $NAME" + ib resume "$BOX_ID" --no-vault >/dev/null || die "Cannot resume $NAME: $(ib_why)" ;; + stopped) + log "Starting $NAME" + ib start "$BOX_ID" --no-vault >/dev/null || die "Cannot start $NAME: $(ib_why)" ;; + creating|starting|resuming|suspending|stopping) + settle || continue + continue ;; + error) + [ "$created" = 0 ] || die "The new sandbox $NAME failed" + log "Deleting failed sandbox $NAME" + ib rm --yes "$BOX_ID" >/dev/null || die "Cannot delete failed sandbox $NAME: $(ib_why)" ;; + *) + die "Sandbox $NAME is $BOX_STATE" ;; + esac + lookup + done + ib exec "$BOX_ID" --timeout 60 -- 'test "$(id -un)" = user && sudo -n hostname localhost && sudo -n mkdir -p /home/user && sudo -n chown user /home/user && test -w /home/user' >/dev/null \ + || die "Sandbox $NAME is not ready for Amp: $(ib_why)" + set -- exec "$BOX_ID" --background --env "ORB_TOKEN=$ORB_TOKEN" + if [ -n "$AMP_URL" ]; then set -- "$@" --env "AMP_URL=$AMP_URL"; fi + log "Starting Amp in $NAME" + ib "$@" -- 'cd /home/user && HOME=/home/user exec /usr/local/bin/amp orb bootstrap >>/home/user/.amp-bootstrap.log 2>&1' >/dev/null \ + || die "Cannot start Amp in $NAME: $(ib_why)" +} + +save_snapshot() { + local prefix name status + prefix=$(snap_prefix "$ORB_SNAPSHOT_ID") + name="$prefix$(date +%s)" + log "Saving $name" + if ! ib snapshot save "$BOX_ID" --name "$name" --no-wait --json >/dev/null; then + grep -Eqi "409|conflict|already exists" "$IB_ERR" || die "Cannot save snapshot $name: $(ib_why)" + fi + while :; do + SNAPSHOTS=$(ib snapshot ls --json) || die "Cannot list snapshots: $(ib_why)" + status=$(printf '%s' "$SNAPSHOTS" | jq -r --arg n "$name" '[.[] | select(.name == $n)][0].status // "missing"') + case "$status" in + ready) break ;; + pending|creating|missing) ;; + *) die "Snapshot $name is $status" ;; + esac + past_deadline && die "Snapshot $name is not ready in time" + sleep "$POLL" + done + # Keep the newest one of this project. + printf '%s' "$SNAPSHOTS" | jq -r --arg p "$prefix" --arg n "$name" ' + .[] | select((.name | startswith($p)) and .name != $n + and (.name[($p | length):] | test("^[0-9]{10,13}$")) + and (.status == "ready" or .status == "failed")) | .id' | + while read -r old; do + [ -n "$old" ] || continue + ib snapshot rm --yes "$old" >/dev/null || log "Cannot delete old snapshot $old: $(ib_why)" + done +} + +pause() { + lookup || return 0 + settle || return 0 + if [ -n "$ORB_SNAPSHOT_ID" ]; then + if [ "$BOX_STATE" = suspended ]; then + # instabox cannot save a paused sandbox: wake it, save, pause it again. + log "Resuming $NAME to save it" + ib resume "$BOX_ID" --no-vault >/dev/null || die "Cannot resume $NAME: $(ib_why)" + lookup || return 0 + settle || return 0 + fi + save_snapshot + fi + if [ "$BOX_STATE" = running ]; then + log "Pausing $NAME" + ib suspend "$BOX_ID" >/dev/null || die "Cannot pause $NAME: $(ib_why)" + fi +} + +delete() { + lookup || return 0 + log "Deleting $NAME" + ib rm --yes "$BOX_ID" >/dev/null || die "Cannot delete $NAME: $(ib_why)" +} + +dispatch() { + [ -n "$ORB_ID" ] || die "ORB_ID is missing" + NAME=$(orb_name) + case "$NAME" in + amp-[a-z0-9]*) ;; + *) die "ORB_ID $ORB_ID is not an orb ID" ;; + esac + printf '%s' "$NAME" | grep -Eq '^[a-z0-9][a-z0-9-]{0,62}$' || die "ORB_ID $ORB_ID is not an orb ID" + case "$ORB_OPERATION" in + spawn) DEADLINE=280; spawn ;; + pause) if [ -n "$ORB_SNAPSHOT_ID" ]; then DEADLINE=580; else DEADLINE=280; fi; pause ;; + delete) DEADLINE=280; delete ;; + *) die "Unknown ORB_OPERATION $ORB_OPERATION" ;; + esac +} + +# --- the provider ---------------------------------------------------------------------------- + +secrets_file() { printf '%s/.local/share/amp/secrets.json' "$HOME"; } + +read_token() { + local f + f=$(secrets_file) + [ -r "$f" ] || return 0 + jq -r --arg p "$TOKEN_PREFIX" \ + 'to_entries | map(select(.key | startswith($p))) | .[0].value // empty' "$f" 2>/dev/null +} + +signed_in() { + command -v amp >/dev/null 2>&1 || return 1 + amp account list --json /dev/null | jq -e '[.accounts[]? | select(.active)] | length > 0' >/dev/null 2>&1 +} + +serve() { + local token + token=$(read_token) + if [ -z "$token" ]; then + log "Not connected to Amp. Run amp-orbs-connect in a terminal on this sandbox." + sleep 60 + exit 1 + fi + export AMP_ORB_PROVIDER_TOKEN=$token + exec amp orb provider "$SELF" +} + +connect() { + echo "Connecting this sandbox to Amp." + if ! signed_in; then + echo "Sign in to Amp in your browser." + amp login || die "Amp sign-in did not finish" + fi + if [ -z "$(read_token)" ]; then + echo "Adding instabox as an orb provider in Amp." + if ! amp orb provider create "$PROVIDER_NAME"; then + die "Amp did not add the provider. If Amp already has a provider named $PROVIDER_NAME, delete it in Amp's orb settings and run amp-orbs-connect again." + fi + [ -n "$(read_token)" ] || die "Amp added the provider but saved no token on this sandbox" + fi + amp orb provider set-default "$PROVIDER_NAME" || log "Could not make $PROVIDER_NAME your default orb provider. Pick it in Amp." + sudo -n systemctl restart amp-orb-provider || die "Cannot restart the provider service" + echo + echo "Connected. instabox is your orb provider in Amp. You can close this window." +} + +image_state() { + local f="$STATE_DIR/image.json" + [ -r "$f" ] && cat "$f" || printf '{}' +} + +write_image_state() { + mkdir -p "$STATE_DIR" || return 1 + printf '%s\n' "$1" >"$STATE_DIR/image.json.new" && mv -f "$STATE_DIR/image.json.new" "$STATE_DIR/image.json" +} + +image_build() { + local ref name out why now + ref=$(cat "$STATE_DIR/orb-image-ref" 2>/dev/null) + ref=${ref:-${AMP_ORBS_IMAGE:-$IMAGE_DEFAULT}} + name="$BASE_PREFIX$(date +%s)" + write_image_state "$(jq -cn --arg r "$ref" --arg s "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + --argjson prev "$(image_state)" '$prev + {status: "building", ref: $r, startedAt: $s, error: null}')" + # A builder left by a stopped import blocks the name: delete it, only if the import made it. + if out=$(ib get "$BUILDER" --json); then + if [ -n "$(printf '%s' "$out" | jq -r '.metadata["instabox-import"] // ""')" ]; then + ib rm --yes "$BUILDER" >/dev/null || log "Cannot delete the old builder: $(ib_why)" + fi + fi + log "Importing $ref as $name" + out=$(ib snapshot import "$ref" --name "$name" --no-entrypoint --platform linux/amd64 \ + --builder-name "$BUILDER" --json) + if [ $? != 0 ] || [ "$(printf '%s' "$out" | jq -r '.verified // false' 2>/dev/null)" != true ]; then + why=$(ib_why) + write_image_state "$(jq -cn --arg e "${why:-the import failed}" --arg f "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + --argjson prev "$(image_state)" '$prev + {status: "failed", error: $e, finishedAt: $f}')" + die "The orb image did not build: ${why:-the import failed}" + fi + now=$(date -u +%Y-%m-%dT%H:%M:%SZ) + write_image_state "$(jq -cn --arg s "$name" --arg f "$now" --arg r "$ref" \ + --arg d "$(printf '%s' "$out" | jq -r '.digest // ""')" \ + '{status: "ready", snapshot: $s, finishedAt: $f, ref: $r, digest: $d, error: null}')" + # Delete older base snapshots. + SNAPSHOTS=$(ib snapshot ls --json) || return 0 + printf '%s' "$SNAPSHOTS" | jq -r --arg p "$BASE_PREFIX" --arg n "$name" ' + .[] | select((.name | startswith($p)) and .name != $n + and (.name[($p | length):] | test("^[0-9]{10,13}$")) + and .status != "pending" and .status != "creating") | .id' | + while read -r old; do + [ -n "$old" ] || continue + ib snapshot rm --yes "$old" >/dev/null || log "Cannot delete old image $old: $(ib_why)" + done +} + +purge() { + sudo -n systemctl disable --now amp-orb-provider amp-orb-image.timer >/dev/null 2>&1 + sudo -n systemctl stop amp-orb-image >/dev/null 2>&1 + local out + if out=$(ib get "$BUILDER" --json); then + if [ -n "$(printf '%s' "$out" | jq -r '.metadata["instabox-import"] // ""')" ]; then + ib rm --yes "$BUILDER" >/dev/null || log "Cannot delete the builder: $(ib_why)" + fi + fi + SNAPSHOTS=$(ib snapshot ls --json) || die "Cannot list snapshots: $(ib_why)" + printf '%s' "$SNAPSHOTS" | jq -r --arg b "$BASE_PREFIX" --arg s "$SNAP_PREFIX" ' + .[] | select((.name | startswith($b)) or (.name | startswith($s))) | .id' | + while read -r id; do + [ -n "$id" ] || continue + ib snapshot rm --yes "$id" >/dev/null || log "Cannot delete snapshot $id: $(ib_why)" + done +} + +unit_state() { systemctl is-active "$1" 2>/dev/null | head -n 1; } + +status() { + local signed=false saved=false service image building + signed_in && signed=true + [ -n "$(read_token)" ] && saved=true + service=$(unit_state amp-orb-provider) + image=$(image_state) + building=$(unit_state amp-orb-image) + if [ "$building" = active ] || [ "$building" = activating ]; then + image=$(printf '%s' "$image" | jq -c '. + {status: "building"}') + fi + jq -cn --arg v "$VERSION" --argjson signed "$signed" --argjson saved "$saved" \ + --arg service "${service:-unknown}" --argjson image "$image" \ + --arg keyId "${AMP_ORBS_KEY_ID:-}" --arg keyExpires "${AMP_ORBS_KEY_EXPIRES:-}" '{ + version: ($v | tonumber), signedIn: $signed, tokenSaved: $saved, service: $service, + image: {status: ($image.status // "none"), snapshot: ($image.snapshot // null), + finishedAt: ($image.finishedAt // null), error: ($image.error // null)}, + keyId: (if $keyId == "" then null else $keyId end), + keyExpires: (if $keyExpires == "" then null else $keyExpires end)}' +} + +if [ $# = 0 ] && [ -n "$ORB_OPERATION" ]; then + dispatch + exit $? +fi +case "$1 $2" in + "serve ") serve ;; + "connect ") connect ;; + "status ") status ;; + "image build") image_build ;; + "purge ") purge ;; + *) echo "usage: amp-orbs serve|connect|status|image build|purge (or ORB_OPERATION=... amp-orbs)" >&2; exit 2 ;; +esac diff --git a/src-tauri/examples/e2e.rs b/src-tauri/examples/e2e.rs index 897471f..df980e7 100644 --- a/src-tauri/examples/e2e.rs +++ b/src-tauri/examples/e2e.rs @@ -78,6 +78,7 @@ async fn sh(client: &Client, id: &str, cmd: &str) -> Result<(i32, String), Strin &ExecRequest { cmd: cmd.to_string(), timeout_seconds: Some(60), + ..Default::default() }, ) .await diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 386d8ff..b389fa8 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -12,6 +12,7 @@ pub mod github; pub mod login; pub mod mcp; pub mod old_app; +pub mod orbs; pub mod process; pub mod repos; pub mod sandbox; diff --git a/src-tauri/src/orbs.rs b/src-tauri/src/orbs.rs new file mode 100644 index 0000000..e1e55f3 --- /dev/null +++ b/src-tauri/src/orbs.rs @@ -0,0 +1,1325 @@ +//! Amp orbs: an always-on provider sandbox runs `amp orb provider`, and each Amp thread gets +//! its own sandbox in the workspace. The provider runs `amp-orbs` (assets/amp-orbs), which +//! starts, pauses and deletes orb sandboxes with the instabox CLI and a workspace key. The +//! Amp token stays on the provider: the user signs in there, in a terminal. docs/amp-orbs.md. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::ade::Ade; +use crate::api::{self, Client, CreateMachineRequest, ExecRequest, Machine, MachineSpec}; +use crate::sandbox::connect::setup_failure; +use crate::sandbox::{ + CREATE_WAIT, SandboxError, ensure_running, new_key, retry_transient, wait_op, +}; + +/// The metadata key that gives a sandbox a role. A sandbox with a role is never an ADE's. +pub const ROLE_KEY: &str = "instabox-role"; +pub const ROLE_PROVIDER: &str = "amp-orb-provider"; +pub const ROLE_ORB: &str = "amp-orb"; +pub const PROVIDER_NAME: &str = "amp-orb-provider"; +pub const PROVIDER_TEMPLATE: &str = "minimal"; +pub const KEY_NAME: &str = "Amp orbs"; +pub const KEY_SCOPES: [&str; 6] = [ + "machines:read", + "machines:write", + "machines:delete", + "images:read", + "images:write", + "images:delete", +]; +pub const KEY_DAYS: u32 = 365; +/// What the sign-in terminal runs on the provider. Plain, as `ssh::terminal_args` wants. +pub const CONNECT_COMMAND: &str = "amp-orbs-connect"; +/// The size of an orb when the plan allows it: Amp's default orb. +const ORB_SPEC: (u32, u32) = (4, 8192); + +const INSTALL_TIMEOUT_SECS: u32 = 600; +const STATUS_TIMEOUT_SECS: u32 = 60; +const PURGE_TIMEOUT_SECS: u32 = 300; + +const PROGRAM: &str = include_str!("../assets/amp-orbs/amp-orbs"); +const PROVIDER_UNIT: &str = include_str!("../assets/amp-orbs/amp-orb-provider.service"); +const IMAGE_UNIT: &str = include_str!("../assets/amp-orbs/amp-orb-image.service"); +const IMAGE_TIMER: &str = include_str!("../assets/amp-orbs/amp-orb-image.timer"); + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Role { + Provider, + Orb, +} + +/// The role in a sandbox's metadata. None for an ordinary sandbox. +pub fn role(metadata: &BTreeMap) -> Option { + match metadata.get(ROLE_KEY).map(String::as_str) { + Some(ROLE_PROVIDER) => Some(Role::Provider), + Some(ROLE_ORB) => Some(Role::Orb), + _ => None, + } +} + +/// The smallest size the plan allows: the provider only waits for Amp's jobs. +pub fn provider_spec(allowed: &[MachineSpec]) -> Option { + allowed.iter().min_by_key(|s| (s.vcpus, s.mem_mib)).cloned() +} + +/// The size of a new orb: Amp's default when the plan allows it, else the closest smaller one, +/// else the smallest. +pub fn orb_spec(allowed: &[MachineSpec]) -> Option { + let (vcpus, mem_mib) = ORB_SPEC; + allowed + .iter() + .filter(|s| s.vcpus <= vcpus && s.mem_mib <= mem_mib) + .max_by_key(|s| (s.vcpus, s.mem_mib)) + .or_else(|| allowed.iter().min_by_key(|s| (s.vcpus, s.mem_mib))) + .cloned() +} + +/// What `amp-orbs status` prints. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ProviderStatus { + #[serde(default)] + pub version: u32, + #[serde(default)] + pub signed_in: bool, + #[serde(default)] + pub token_saved: bool, + /// systemd's state of the provider service: `active` when it runs. + #[serde(default)] + pub service: String, + #[serde(default)] + pub image: ImageStatus, + #[serde(default)] + pub key_id: Option, + #[serde(default)] + pub key_expires: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ImageStatus { + /// `none`, `building`, `ready` or `failed`. + #[serde(default)] + pub status: String, + #[serde(default)] + pub snapshot: Option, + #[serde(default)] + pub finished_at: Option, + #[serde(default)] + pub error: Option, +} + +impl ProviderStatus { + /// Amp can send jobs: signed in, the provider token saved, the service running. + pub fn connected(&self) -> bool { + self.signed_in && self.token_saved && self.service == "active" + } +} + +/// The status in the last line of `amp-orbs status` output. None when there is none. +pub fn parse_status(stdout: &str) -> Option { + stdout + .lines() + .rev() + .find(|l| l.trim_start().starts_with('{')) + .and_then(|l| serde_json::from_str(l.trim()).ok()) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum OrbsStep { + Creating, + Installing, + Removing, +} + +fn fail(message: impl Into) -> SandboxError { + SandboxError::Api(api::Error { + status: 0, + code: "amp_orbs".into(), + message: message.into(), + retryable: false, + retry_after: None, + }) +} + +/// A URL the install can write into the provider's environment as is. +fn plain_url(url: &str) -> Option<&str> { + let url = url.trim_end_matches('/'); + let ok = !url.is_empty() + && url + .chars() + .all(|c| c.is_ascii_alphanumeric() || ":/._-".contains(c)); + ok.then_some(url) +} + +/// The script that installs `amp-orbs` and its units on the provider and prints its status. +/// It reads the key from `AMP_ORBS_KEY`, `AMP_ORBS_KEY_ID` and `AMP_ORBS_KEY_EXPIRES`, which +/// reach it as exec env: the key is never in the command text. +pub fn install_script(api_url: &str, orb: &MachineSpec) -> String { + let api_line = plain_url(api_url) + .map(|u| format!("INSTABOX_API_URL={u}\n")) + .unwrap_or_default(); + INSTALL_TEMPLATE + .replace("__PROGRAM__", PROGRAM.trim_end()) + .replace("__PROVIDER_UNIT__", PROVIDER_UNIT.trim_end()) + .replace("__IMAGE_UNIT__", IMAGE_UNIT.trim_end()) + .replace("__IMAGE_TIMER__", IMAGE_TIMER.trim_end()) + .replace("__API_LINE__", &api_line) + .replace("__SIZE__", &format!("{}/{}", orb.vcpus, orb.mem_mib)) +} + +const INSTALL_TEMPLATE: &str = r##"set -eu +: "${AMP_ORBS_KEY:?}" "${AMP_ORBS_KEY_ID:?}" +user=$(id -un) +group=$(id -gn) +home=$HOME +new=$(mktemp -d) +trap 'rm -rf "$new"' EXIT +cat > "$new/amp-orbs" <<'__AMP_ORBS_EOF__' +__PROGRAM__ +__AMP_ORBS_EOF__ +cat > "$new/amp-orb-provider.service" <<'__AMP_ORBS_EOF__' +__PROVIDER_UNIT__ +__AMP_ORBS_EOF__ +cat > "$new/amp-orb-image.service" <<'__AMP_ORBS_EOF__' +__IMAGE_UNIT__ +__AMP_ORBS_EOF__ +cat > "$new/amp-orb-image.timer" <<'__AMP_ORBS_EOF__' +__IMAGE_TIMER__ +__AMP_ORBS_EOF__ +cat > "$new/amp-orbs-connect" <<'__AMP_ORBS_EOF__' +#!/bin/sh +/usr/local/bin/amp-orbs connect "$@" +status=$? +printf '\nPress Enter to close. ' +read -r _ +exit $status +__AMP_ORBS_EOF__ +if ! command -v jq >/dev/null 2>&1; then + sudo -n apt-get update -qq >/dev/null + sudo -n env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq jq >/dev/null +fi +command -v npm >/dev/null 2>&1 || { echo "Amp orbs need Node.js and npm on the provider" >&2; exit 1; } +npm install -g --no-fund --no-audit --silent instabox@latest >/dev/null +prefix=$(npm prefix -g) +ib="$(npm root -g)/instabox/cli/instabox-linux-amd64" +[ -x "$ib" ] || ib="$prefix/bin/instabox" +[ -x "$ib" ] || { echo "The instabox CLI did not install" >&2; exit 1; } +find_amp() { + for c in "$home/.amp/bin/amp" "$home/.local/bin/amp" "$prefix/bin/amp" "$(readlink -f /usr/local/bin/amp 2>/dev/null || true)"; do + if [ -n "$c" ] && [ "$c" != /usr/local/bin/amp ] && [ -x "$c" ]; then echo "$c"; return 0; fi + done + return 1 +} +if ! amp=$(find_amp); then + curl -fsSL https://ampcode.com/install.sh | bash /dev/null 2>&1 \ + || npm install -g --no-fund --no-audit --silent @sourcegraph/amp >/dev/null + amp=$(find_amp) || { echo "The Amp CLI did not install" >&2; exit 1; } +fi +(umask 077 +cat > "$new/env" <<__AMP_ORBS_EOF__ +HOME=$home +PATH=/usr/local/bin:/usr/bin:/bin:$prefix/bin +INSTABOX_API_KEY=$AMP_ORBS_KEY +__API_LINE__AMP_ORBS_KEY_ID=$AMP_ORBS_KEY_ID +AMP_ORBS_KEY_EXPIRES=${AMP_ORBS_KEY_EXPIRES:-} +AMP_ORBS_SIZE=__SIZE__ +__AMP_ORBS_EOF__ +) +for u in amp-orb-provider.service amp-orb-image.service; do + sed -e "s|__USER__|$user|" -e "s|__HOME__|$home|" "$new/$u" > "$new/$u.out" + mv -f "$new/$u.out" "$new/$u" +done +sudo -n install -d -m 0755 /etc/amp-orbs +sudo -n install -d -o "$user" -g "$group" -m 0755 /var/lib/amp-orbs +sudo -n install -m 0600 -o "$user" -g "$group" "$new/env" /etc/amp-orbs/env +sudo -n install -m 0755 "$new/amp-orbs" /usr/local/bin/amp-orbs +sudo -n install -m 0755 "$new/amp-orbs-connect" /usr/local/bin/amp-orbs-connect +sudo -n ln -sfn "$ib" /usr/local/bin/instabox +sudo -n ln -sfn "$amp" /usr/local/bin/amp +for u in amp-orb-provider.service amp-orb-image.service amp-orb-image.timer; do + sudo -n install -m 0644 "$new/$u" "/etc/systemd/system/$u" +done +sudo -n systemctl daemon-reload +sudo -n systemctl enable -q amp-orb-provider.service amp-orb-image.timer +sudo -n systemctl reset-failed amp-orb-provider.service 2>/dev/null || true +sudo -n systemctl restart amp-orb-provider.service +sudo -n systemctl start amp-orb-image.timer +status=$(/usr/local/bin/amp-orbs status) +case "$status" in + *'"status":"ready"'*|*'"status":"building"'*) ;; + *) sudo -n systemctl start --no-block amp-orb-image.service + status=$(/usr/local/bin/amp-orbs status) ;; +esac +printf '%s\n' "$status""##; + +/// The provider sandbox of `org` in `machines`. Fails when a sandbox has the provider's name +/// but is not the provider: it belongs to the user, and setup never takes it over. +pub fn find_provider<'a>( + machines: &'a [Machine], + org: &str, +) -> Result, SandboxError> { + let mine = machines + .iter() + .filter(|m| m.org_id == org || m.org_id.is_empty()); + if let Some(m) = mine + .clone() + .find(|m| role(&m.metadata) == Some(Role::Provider)) + { + return Ok(Some(m)); + } + if mine.clone().any(|m| m.name == PROVIDER_NAME) { + return Err(fail(format!( + "A sandbox named {PROVIDER_NAME} is already in this workspace. Rename or delete it, then set up Amp orbs again." + ))); + } + Ok(None) +} + +/// The orb sandboxes of `org`. +pub fn orbs_of<'a>(machines: &'a [Machine], org: &'a str) -> impl Iterator { + machines.iter().filter(move |m| { + (m.org_id == org || m.org_id.is_empty()) && role(&m.metadata) == Some(Role::Orb) + }) +} + +fn key_error(e: api::Error) -> SandboxError { + if e.status == 403 { + return fail( + "Only an owner or admin of this workspace can set up Amp orbs: it needs a workspace API key.", + ); + } + e.into() +} + +async fn create_provider( + client: &Client, + org: &str, + spec: &MachineSpec, +) -> Result { + let body = CreateMachineRequest { + name: PROVIDER_NAME.into(), + template_id: Some(PROVIDER_TEMPLATE.into()), + snapshot_id: None, + vcpus: Some(spec.vcpus), + mem_mib: Some(spec.mem_mib), + metadata: Some(BTreeMap::from([( + ROLE_KEY.to_string(), + ROLE_PROVIDER.to_string(), + )])), + auto_suspend_after_seconds: Some(0), + org_id: Some(org.to_string()), + }; + let key = new_key(); + let op = retry_transient(|| client.create(&body, &key)).await?; + Ok(wait_op(client, &op, CREATE_WAIT).await?.id) +} + +async fn exec( + client: &Client, + id: &str, + req: &ExecRequest, +) -> Result { + let secs = req.timeout_seconds.unwrap_or(STATUS_TIMEOUT_SECS); + let r = client.exec(id, req).await?; + if r.exit_code != 0 || r.timed_out { + return Err(setup_failure(Ade::Amp, &r, secs)); + } + Ok(r) +} + +/// What a finished setup knows. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SetUp { + pub provider_id: String, + pub status: Option, +} + +/// Sets Amp orbs up in `org`, or repairs them: mints a workspace key, creates the provider +/// (or wakes the one there is) and installs `amp-orbs` on it with the key. A failed setup +/// revokes the new key; a finished one revokes the key the provider had before. +pub async fn set_up( + client: &Client, + org: &str, + api_url: &str, + allowed: &[MachineSpec], + progress: impl Fn(OrbsStep), +) -> Result { + let machines = client.machines().await?; + let existing = find_provider(&machines, org)?.cloned(); + let spec = + provider_spec(allowed).ok_or_else(|| fail("This workspace allows no sandbox size"))?; + let orb = orb_spec(allowed).unwrap_or_else(|| spec.clone()); + // The key first: nothing is created for someone who may not make one. + let key = client + .create_org_api_key(org, KEY_NAME, &KEY_SCOPES, KEY_DAYS) + .await + .map_err(key_error)?; + let installed = async { + let (id, old_key) = match existing { + Some(m) => { + if m.state != "running" { + progress(OrbsStep::Creating); + } + ensure_running(client, &m.id).await?; + let old = status(client, &m.id) + .await + .ok() + .flatten() + .and_then(|s| s.key_id); + (m.id, old) + } + None => { + progress(OrbsStep::Creating); + (create_provider(client, org, &spec).await?, None) + } + }; + progress(OrbsStep::Installing); + let req = ExecRequest { + cmd: install_script(api_url, &orb), + timeout_seconds: Some(INSTALL_TIMEOUT_SECS), + envs: Some(BTreeMap::from([ + ("AMP_ORBS_KEY".to_string(), key.key.clone()), + ("AMP_ORBS_KEY_ID".to_string(), key.api_key.id.clone()), + ( + "AMP_ORBS_KEY_EXPIRES".to_string(), + key.api_key.expires_at.clone().unwrap_or_default(), + ), + ])), + no_history: true, + }; + let r = exec(client, &id, &req).await?; + Ok::<_, SandboxError>((id, old_key, parse_status(&r.stdout))) + } + .await; + match installed { + Err(e) => { + let _ = client.revoke_org_api_key(org, &key.api_key.id).await; + Err(e) + } + Ok((provider_id, old_key, status)) => { + if let Some(old) = old_key.filter(|k| *k != key.api_key.id) { + let _ = client.revoke_org_api_key(org, &old).await; + } + Ok(SetUp { + provider_id, + status, + }) + } + } +} + +/// The provider's status. None when it has no `amp-orbs` that answers. +pub async fn status(client: &Client, id: &str) -> Result, SandboxError> { + let req = ExecRequest { + cmd: "if [ -x /usr/local/bin/amp-orbs ]; then /usr/local/bin/amp-orbs status; fi".into(), + timeout_seconds: Some(STATUS_TIMEOUT_SECS), + ..Default::default() + }; + Ok(parse_status(&exec(client, id, &req).await?.stdout)) +} + +/// Starts a new import of the orb image. It runs on the provider for a few minutes. +pub async fn rebuild_image(client: &Client, id: &str) -> Result<(), SandboxError> { + let req = ExecRequest { + cmd: "sudo -n systemctl start --no-block amp-orb-image.service".into(), + timeout_seconds: Some(STATUS_TIMEOUT_SECS), + ..Default::default() + }; + exec(client, id, &req).await.map(|_| ()) +} + +/// Removes Amp orbs from `org`: deletes the orb snapshots, revokes the key and deletes the +/// provider. Refuses while orb sandboxes are left: Amp still has their threads. +pub async fn remove( + client: &Client, + org: &str, + provider: &Machine, + orbs_left: usize, +) -> Result<(), SandboxError> { + if orbs_left > 0 { + let what = if orbs_left == 1 { + "1 orb sandbox is" + } else { + "orb sandboxes are" + }; + return Err(fail(format!( + "{what} left. Delete their threads in Amp first, so Amp deletes their sandboxes too." + ))); + } + ensure_running(client, &provider.id).await?; + let key_id = status(client, &provider.id) + .await + .ok() + .flatten() + .and_then(|s| s.key_id); + let purge = ExecRequest { + cmd: "if [ -x /usr/local/bin/amp-orbs ]; then /usr/local/bin/amp-orbs purge; fi".into(), + timeout_seconds: Some(PURGE_TIMEOUT_SECS), + ..Default::default() + }; + exec(client, &provider.id, &purge).await?; + if let Some(k) = key_id { + client.revoke_org_api_key(org, &k).await?; + } + crate::sandbox::lifecycle::delete(client, &provider.id).await +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::api::Credentials; + use async_trait::async_trait; + use std::sync::Arc; + use url::Url; + use wiremock::matchers::{body_partial_json, body_string_contains, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + struct Creds; + + #[async_trait] + impl Credentials for Creds { + async fn bearer(&self) -> crate::api::Result { + Ok("iba_x".into()) + } + async fn refreshed(&self) -> crate::api::Result { + Ok("iba_x".into()) + } + } + + fn client(server: &MockServer) -> Client { + Client::new(Url::parse(&server.uri()).unwrap(), Arc::new(Creds)) + } + + fn spec(vcpus: u32, mem_mib: u32) -> MachineSpec { + MachineSpec { vcpus, mem_mib } + } + + fn pro() -> Vec { + vec![spec(4, 8192), spec(2, 4096), spec(8, 16384)] + } + + fn machine( + id: &str, + name: &str, + state: &str, + metadata: serde_json::Value, + ) -> serde_json::Value { + serde_json::json!({ + "id": id, "name": name, "state": state, "revision": 1, + "template": {"id": "minimal", "version": 1, "digest": "d"}, + "spec": {"vcpus": 2, "memMiB": 4096, "persistentDiskGiB": 10}, + "runtime": {"ready": true}, "autoSuspendAfterSeconds": 0, + "maxRunMinutes": -1, "runStartedAt": null, "cooldownUntil": null, + "metadata": metadata, "orgId": "o1", "free": false, "operationId": null + }) + } + + fn provider_json(state: &str) -> serde_json::Value { + machine( + "p1", + PROVIDER_NAME, + state, + serde_json::json!({ROLE_KEY: ROLE_PROVIDER}), + ) + } + + const STATUS_LINE: &str = r#"{"version":1,"signedIn":false,"tokenSaved":false,"service":"active","image":{"status":"building","snapshot":null,"finishedAt":null,"error":null},"keyId":"wkey_1","keyExpires":"2027-12-03T00:00:00Z"}"#; + + async fn list(server: &MockServer, machines: Vec) { + Mock::given(method("GET")) + .and(path("/v1/machines")) + .respond_with( + ResponseTemplate::new(200).set_body_json(serde_json::json!({"machines": machines})), + ) + .mount(server) + .await; + } + + async fn key(server: &MockServer, expect: u64) { + Mock::given(method("POST")) + .and(path("/v1/orgs/o1/keys")) + .and(body_partial_json(serde_json::json!({ + "name": KEY_NAME, "scopes": KEY_SCOPES, "expiresInDays": KEY_DAYS + }))) + .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({ + "apiKey": {"id": "wkey_1", "expiresAt": "2027-12-03T00:00:00Z"}, + "key": "ibk_secret" + }))) + .expect(expect) + .mount(server) + .await; + } + + async fn install(server: &MockServer, exit_code: i32, stderr: &str) { + Mock::given(method("POST")) + .and(path("/v1/machines/p1/exec")) + .and(body_string_contains("set -eu")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "stdout": format!("{STATUS_LINE}\n"), "stderr": stderr, "exitCode": exit_code + }))) + .expect(1) + .mount(server) + .await; + } + + async fn revoke(server: &MockServer, id: &str, expect: u64) { + Mock::given(method("DELETE")) + .and(path(format!("/v1/orgs/o1/keys/{id}"))) + .respond_with(ResponseTemplate::new(204)) + .expect(expect) + .mount(server) + .await; + } + + #[tokio::test] + async fn set_up_creates_the_provider_always_on() { + let server = MockServer::start().await; + list(&server, vec![]).await; + key(&server, 1).await; + Mock::given(method("POST")) + .and(path("/v1/machines")) + .and(body_partial_json(serde_json::json!({ + "name": PROVIDER_NAME, "templateId": "minimal", "vcpus": 2, "memMiB": 4096, + "autoSuspendAfterSeconds": 0, "orgId": "o1", + "metadata": {ROLE_KEY: ROLE_PROVIDER} + }))) + .respond_with(ResponseTemplate::new(202).set_body_json(serde_json::json!({ + "id": "op1", "machineId": "p1", "type": "create", "state": "succeeded", + "machine": provider_json("running") + }))) + .expect(1) + .mount(&server) + .await; + install(&server, 0, "").await; + revoke(&server, "wkey_1", 0).await; + let steps = std::sync::Mutex::new(Vec::new()); + let done = set_up( + &client(&server), + "o1", + "https://api.instabox.sh", + &pro(), + |s| steps.lock().unwrap().push(s), + ) + .await + .unwrap(); + assert_eq!(done.provider_id, "p1"); + let status = done.status.unwrap(); + assert_eq!(status.image.status, "building"); + assert!(!status.connected()); + assert_eq!( + *steps.lock().unwrap(), + vec![OrbsStep::Creating, OrbsStep::Installing] + ); + } + + #[tokio::test] + async fn set_up_reuses_the_provider_and_revokes_its_old_key() { + let server = MockServer::start().await; + list(&server, vec![provider_json("running")]).await; + Mock::given(method("GET")) + .and(path("/v1/machines/p1")) + .respond_with(ResponseTemplate::new(200).set_body_json(provider_json("running"))) + .mount(&server) + .await; + key(&server, 1).await; + Mock::given(method("POST")) + .and(path("/v1/machines")) + .respond_with(ResponseTemplate::new(500)) + .expect(0) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/v1/machines/p1/exec")) + .and(body_string_contains("amp-orbs status; fi")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "stdout": STATUS_LINE.replace("wkey_1", "wkey_old"), "stderr": "", "exitCode": 0 + }))) + .expect(1) + .mount(&server) + .await; + install(&server, 0, "").await; + revoke(&server, "wkey_old", 1).await; + revoke(&server, "wkey_1", 0).await; + let done = set_up( + &client(&server), + "o1", + "https://api.instabox.sh", + &pro(), + |_| {}, + ) + .await + .unwrap(); + assert_eq!(done.provider_id, "p1"); + } + + #[tokio::test] + async fn set_up_refuses_a_foreign_sandbox() { + let server = MockServer::start().await; + list( + &server, + vec![machine( + "u1", + PROVIDER_NAME, + "running", + serde_json::json!({}), + )], + ) + .await; + key(&server, 0).await; + let e = set_up(&client(&server), "o1", "", &pro(), |_| {}) + .await + .unwrap_err(); + assert!(e.to_string().contains("Rename or delete it"), "{e}"); + } + + #[tokio::test] + async fn a_failed_install_revokes_the_key() { + let server = MockServer::start().await; + list(&server, vec![]).await; + key(&server, 1).await; + Mock::given(method("POST")) + .and(path("/v1/machines")) + .respond_with(ResponseTemplate::new(202).set_body_json(serde_json::json!({ + "id": "op1", "machineId": "p1", "type": "create", "state": "succeeded", + "machine": provider_json("running") + }))) + .mount(&server) + .await; + install(&server, 1, "npm ERR! boom").await; + revoke(&server, "wkey_1", 1).await; + let e = set_up(&client(&server), "o1", "", &pro(), |_| {}) + .await + .unwrap_err(); + assert!(matches!(e, SandboxError::Setup { .. }), "{e:?}"); + assert!(e.to_string().contains("npm ERR! boom"), "{e}"); + } + + #[tokio::test] + async fn a_member_who_may_not_make_keys_gets_told_why() { + let server = MockServer::start().await; + list(&server, vec![]).await; + Mock::given(method("POST")) + .and(path("/v1/orgs/o1/keys")) + .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!( + {"error": {"code": "permission_denied", "message": "no", "retryable": false}}))) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/v1/machines")) + .respond_with(ResponseTemplate::new(500)) + .expect(0) + .mount(&server) + .await; + let e = set_up(&client(&server), "o1", "", &pro(), |_| {}) + .await + .unwrap_err(); + assert!(e.to_string().contains("owner or admin"), "{e}"); + } + + #[tokio::test] + async fn key_never_appears_in_exec_text() { + let server = MockServer::start().await; + list(&server, vec![]).await; + key(&server, 1).await; + Mock::given(method("POST")) + .and(path("/v1/machines")) + .respond_with(ResponseTemplate::new(202).set_body_json(serde_json::json!({ + "id": "op1", "machineId": "p1", "type": "create", "state": "succeeded", + "machine": provider_json("running") + }))) + .mount(&server) + .await; + install(&server, 0, "").await; + set_up(&client(&server), "o1", "", &pro(), |_| {}) + .await + .unwrap(); + let requests = server.received_requests().await.unwrap(); + let exec = requests + .iter() + .find(|r| r.url.path() == "/v1/machines/p1/exec") + .unwrap(); + let body: serde_json::Value = serde_json::from_slice(&exec.body).unwrap(); + assert!(!body["cmd"].as_str().unwrap().contains("ibk_secret")); + assert_eq!(body["envs"]["AMP_ORBS_KEY"], "ibk_secret"); + assert_eq!(body["envs"]["AMP_ORBS_KEY_ID"], "wkey_1"); + assert_eq!(body["noHistory"], true); + } + + #[tokio::test] + async fn remove_refuses_while_orbs_exist() { + let server = MockServer::start().await; + let provider: Machine = serde_json::from_value(provider_json("running")).unwrap(); + let e = remove(&client(&server), "o1", &provider, 2) + .await + .unwrap_err(); + assert!( + e.to_string().contains("Delete their threads in Amp first"), + "{e}" + ); + assert!(server.received_requests().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn remove_purges_revokes_and_deletes() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/v1/machines/p1")) + .respond_with(ResponseTemplate::new(200).set_body_json(provider_json("running"))) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/v1/machines/p1/exec")) + .and(body_string_contains("amp-orbs status; fi")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "stdout": STATUS_LINE, "stderr": "", "exitCode": 0 + }))) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/v1/machines/p1/exec")) + .and(body_string_contains("amp-orbs purge; fi")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "stdout": "", "stderr": "", "exitCode": 0 + }))) + .expect(1) + .mount(&server) + .await; + revoke(&server, "wkey_1", 1).await; + Mock::given(method("DELETE")) + .and(path("/v1/machines/p1")) + .respond_with(ResponseTemplate::new(202).set_body_json(serde_json::json!({ + "id": "op2", "machineId": "p1", "type": "delete", "state": "succeeded", + "machine": provider_json("deleted") + }))) + .expect(1) + .mount(&server) + .await; + let provider: Machine = serde_json::from_value(provider_json("running")).unwrap(); + remove(&client(&server), "o1", &provider, 0).await.unwrap(); + } + + #[test] + fn provider_spec_picks_the_smallest() { + assert_eq!(provider_spec(&pro()), Some(spec(2, 4096))); + assert_eq!(orb_spec(&pro()), Some(spec(4, 8192))); + assert_eq!( + orb_spec(&[spec(2, 4096), spec(8, 16384)]), + Some(spec(2, 4096)) + ); + assert_eq!(orb_spec(&[spec(8, 16384)]), Some(spec(8, 16384))); + assert_eq!(provider_spec(&[]), None); + } + + #[test] + fn a_role_comes_from_the_metadata() { + let m = |v: &str| BTreeMap::from([(ROLE_KEY.to_string(), v.to_string())]); + assert_eq!(role(&m(ROLE_PROVIDER)), Some(Role::Provider)); + assert_eq!(role(&m(ROLE_ORB)), Some(Role::Orb)); + assert_eq!(role(&m("other")), None); + assert_eq!(role(&BTreeMap::new()), None); + } + + #[test] + fn status_is_read_from_the_last_json_line() { + let s = parse_status(&format!("npm notice\n{STATUS_LINE}\n")).unwrap(); + assert_eq!(s.key_id.as_deref(), Some("wkey_1")); + assert_eq!(s.service, "active"); + assert!(parse_status("nothing here").is_none()); + let connected = ProviderStatus { + signed_in: true, + token_saved: true, + ..s + }; + assert!(connected.connected()); + } + + #[test] + fn install_script_carries_the_program_whole() { + let s = install_script("https://api.instabox.sh/", &spec(4, 8192)); + assert!(s.contains(PROGRAM.trim_end())); + assert!(s.contains("INSTABOX_API_URL=https://api.instabox.sh\n")); + assert!(s.contains("AMP_ORBS_SIZE=4/8192")); + for placeholder in [ + "__PROGRAM__", + "__PROVIDER_UNIT__", + "__IMAGE_UNIT__", + "__API_LINE__", + "__SIZE__", + ] { + assert!(!s.contains(placeholder), "{placeholder} left in the script"); + } + let odd = install_script("https://x.test/$(rm -rf /)", &spec(4, 8192)); + assert!(!odd.contains("INSTABOX_API_URL"), "an odd URL is left out"); + } + + #[cfg(unix)] + #[test] + fn install_script_is_valid_bash() { + let dir = tempfile::tempdir().unwrap(); + let f = dir.path().join("install.sh"); + std::fs::write( + &f, + install_script("https://api.instabox.sh", &spec(4, 8192)), + ) + .unwrap(); + let out = std::process::Command::new("bash") + .arg("-n") + .arg(&f) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + } +} + +/// The provider program against fake `instabox`, `amp` and `systemctl` commands. +#[cfg(all(test, unix))] +mod script_tests { + use super::PROGRAM; + use std::os::unix::fs::PermissionsExt; + use std::path::{Path, PathBuf}; + use std::process::{Command, Output}; + + /// Sandboxes are files in $FAKE/boxes/.json; snapshots are one JSON array. + const FAKE_INSTABOX: &str = r#"#!/bin/bash +printf '%s\n' "$*" >> "$FAKE/log" +box_by_id() { + for f in "$FAKE"/boxes/*.json; do + [ -f "$f" ] || continue + if [ "$(jq -r .id "$f")" = "$1" ]; then echo "$f"; return 0; fi + done + return 1 +} +set_state() { + f=$(box_by_id "$1") || { echo "sandbox not found" >&2; exit 4; } + jq -c --arg s "$2" '.state = $s' "$f" > "$f.new" && mv "$f.new" "$f" +} +snaps() { jq -c "$@" "$FAKE/snapshots.json" > "$FAKE/snapshots.new" && mv "$FAKE/snapshots.new" "$FAKE/snapshots.json"; } +case "$1" in + get) f="$FAKE/boxes/$2.json"; [ -f "$f" ] || { echo "sandbox not found" >&2; exit 4; }; cat "$f" ;; + create) + shift; name=; snap=; meta='{}' + while [ $# -gt 0 ]; do + case "$1" in + --name) name=$2; shift ;; + --snapshot) snap=$2; shift ;; + --meta) meta=$(jq -c --arg k "${2%%=*}" --arg v "${2#*=}" '.[$k] = $v' <<<"$meta"); shift ;; + esac + shift + done + jq -cn --arg n "$name" --arg s "$snap" --argjson m "$meta" \ + '{id: ("id-" + $n), name: $n, state: "running", metadata: $m, snapshot: $s}' > "$FAKE/boxes/$name.json" + cat "$FAKE/boxes/$name.json" ;; + resume|start) set_state "$2" running ;; + suspend) set_state "$2" suspended ;; + rm) f=$(box_by_id "$3") || exit 4; rm -f "$f" ;; + exec) exit "${FAKE_EXEC_EXIT:-0}" ;; + snapshot) + case "$2" in + ls) cat "$FAKE/snapshots.json" ;; + save) + f=$(box_by_id "$3") || exit 4 + if [ "$(jq -r .state "$f")" != running ]; then echo "conflict (409): the sandbox is paused" >&2; exit 1; fi + snaps --arg n "$5" '. + [{id: ("sn-" + $n), name: $n, status: "ready", createdAt: "2026-12-04T00:00:00Z", sizeLocked: true}]' ;; + rm) snaps --arg i "$4" 'map(select(.id != $i))' ;; + esac ;; +esac +"#; + + const FAKE_AMP: &str = r#"#!/bin/bash +printf 'amp %s\n' "$*" >> "$FAKE/log" +case "$1 $2" in + "account list") echo '{"accounts":[{"email":"a@b.c","active":true}]}' ;; +esac +"#; + + const FAKE_SYSTEMCTL: &str = "#!/bin/bash\necho inactive\nexit 3\n"; + + struct Fake { + dir: tempfile::TempDir, + } + + impl Fake { + fn new(snapshots: serde_json::Value) -> Fake { + let dir = tempfile::tempdir().unwrap(); + let bin = dir.path().join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + std::fs::create_dir_all(dir.path().join("boxes")).unwrap(); + std::fs::create_dir_all(dir.path().join("home")).unwrap(); + for (name, body) in [ + ("instabox", FAKE_INSTABOX), + ("amp", FAKE_AMP), + ("systemctl", FAKE_SYSTEMCTL), + ("amp-orbs", PROGRAM), + ] { + let p = bin.join(name); + std::fs::write(&p, body).unwrap(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + std::fs::write(dir.path().join("snapshots.json"), snapshots.to_string()).unwrap(); + std::fs::write(dir.path().join("log"), "").unwrap(); + Fake { dir } + } + + fn path(&self) -> &Path { + self.dir.path() + } + + fn box_file(&self, name: &str) -> PathBuf { + self.path().join("boxes").join(format!("{name}.json")) + } + + fn put_box(&self, name: &str, state: &str, metadata: serde_json::Value) { + let b = serde_json::json!({"id": format!("id-{name}"), "name": name, "state": state, "metadata": metadata}); + std::fs::write(self.box_file(name), b.to_string()).unwrap(); + } + + fn state(&self, name: &str) -> Option { + let s = std::fs::read_to_string(self.box_file(name)).ok()?; + let v: serde_json::Value = serde_json::from_str(&s).unwrap(); + v["state"].as_str().map(str::to_string) + } + + fn log(&self) -> Vec { + std::fs::read_to_string(self.path().join("log")) + .unwrap() + .lines() + .map(str::to_string) + .collect() + } + + fn snapshots(&self) -> Vec { + let s = std::fs::read_to_string(self.path().join("snapshots.json")).unwrap(); + let v: Vec = serde_json::from_str(&s).unwrap(); + v.iter() + .map(|s| s["name"].as_str().unwrap().to_string()) + .collect() + } + + fn run(&self, args: &[&str], env: &[(&str, &str)]) -> Output { + let bin = self.path().join("bin"); + let mut cmd = Command::new("bash"); + cmd.arg(bin.join("amp-orbs")) + .args(args) + .env_clear() + .env("PATH", format!("{}:/usr/bin:/bin", bin.display())) + .env("HOME", self.path().join("home")) + .env("TMPDIR", self.path()) + .env("FAKE", self.path()) + .env("AMP_ORBS_ENV_FILE", self.path().join("no-env")) + .env("AMP_ORBS_STATE_DIR", self.path().join("state")) + .env("AMP_ORBS_POLL", "0"); + for (k, v) in env { + cmd.env(k, v); + } + cmd.output().unwrap() + } + + fn dispatch(&self, op: &str, env: &[(&str, &str)]) -> Output { + let mut all = vec![ + ("ORB_OPERATION", op), + ("ORB_ID", ORB_ID), + ("ORB_TOKEN", "orb_tok"), + ]; + all.extend_from_slice(env); + self.run(&[], &all) + } + } + + const ORB_ID: &str = "amp-T-3F2A9C00-0000-4000-8000-000000000001"; + const NAME: &str = "amp-t-3f2a9c00-0000-4000-8000-000000000001"; + + fn orb_meta() -> serde_json::Value { + serde_json::json!({"instabox-role": "amp-orb", "amp-orb-id": ORB_ID}) + } + + fn snap(name: &str, status: &str, created: &str, locked: bool) -> serde_json::Value { + serde_json::json!({"id": format!("sn-{name}"), "name": name, "status": status, + "createdAt": created, "sizeLocked": locked}) + } + + fn ok(out: &Output) { + assert!( + out.status.success(), + "exit {:?}\nstderr: {}", + out.status.code(), + String::from_utf8_lossy(&out.stderr) + ); + } + + fn has_jq() -> bool { + Command::new("jq").arg("--version").output().is_ok() + } + + #[test] + fn spawn_creates_from_the_newest_base() { + if !has_jq() { + return; + } + let fake = Fake::new(serde_json::json!([ + snap( + "amp-orb-base-1700000000", + "ready", + "2026-11-01T00:00:00Z", + false + ), + snap( + "amp-orb-base-1800000000", + "ready", + "2026-12-01T00:00:00Z", + false + ), + snap( + "amp-orb-base-1900000000", + "pending", + "2026-12-02T00:00:00Z", + false + ), + ])); + let out = fake.dispatch("spawn", &[("AMP_URL", "https://ampcode.com")]); + ok(&out); + let log = fake.log(); + let create = log.iter().find(|l| l.starts_with("create ")).unwrap(); + assert!(create.contains(&format!("--name {NAME}")), "{create}"); + assert!( + create.contains("--snapshot sn-amp-orb-base-1800000000"), + "{create}" + ); + assert!(create.contains("--meta instabox-role=amp-orb"), "{create}"); + assert!( + create.contains(&format!("--meta amp-orb-id={ORB_ID}")), + "{create}" + ); + assert!(create.contains("--auto-suspend 0"), "{create}"); + assert!(create.contains("--vcpus 4 --mem-mib 8192"), "{create}"); + let boot = log.iter().find(|l| l.contains("--background")).unwrap(); + assert!(boot.contains("--env ORB_TOKEN=orb_tok"), "{boot}"); + assert!(boot.contains("--env AMP_URL=https://ampcode.com"), "{boot}"); + assert!(boot.contains("amp orb bootstrap"), "{boot}"); + } + + #[test] + fn spawn_uses_the_project_snapshot_at_its_size() { + if !has_jq() { + return; + } + let fake = Fake::new(serde_json::json!([ + snap( + "amp-orb-base-1800000000", + "ready", + "2026-12-01T00:00:00Z", + false + ), + snap( + "amp-orb-snap-p1-1800000001", + "ready", + "2026-12-01T00:00:01Z", + true + ), + snap( + "amp-orb-snap-p10-1800000002", + "ready", + "2026-12-01T00:00:02Z", + true + ), + ])); + ok(&fake.dispatch("spawn", &[("ORB_SNAPSHOT_ID", "p1")])); + let log = fake.log(); + let create = log.iter().find(|l| l.starts_with("create ")).unwrap(); + assert!( + create.contains("--snapshot sn-amp-orb-snap-p1-1800000001"), + "{create}" + ); + assert!( + !create.contains("--vcpus"), + "a size-locked snapshot keeps its size: {create}" + ); + } + + #[test] + fn spawn_resumes_a_suspended_orb() { + if !has_jq() { + return; + } + let fake = Fake::new(serde_json::json!([])); + fake.put_box(NAME, "suspended", orb_meta()); + ok(&fake.dispatch("spawn", &[])); + let log = fake.log(); + assert!( + log.iter() + .any(|l| l == &format!("resume id-{NAME} --no-vault")), + "{log:?}" + ); + assert!(!log.iter().any(|l| l.starts_with("create ")), "{log:?}"); + assert_eq!(fake.state(NAME).as_deref(), Some("running")); + } + + #[test] + fn spawn_refuses_a_foreign_box() { + if !has_jq() { + return; + } + let fake = Fake::new(serde_json::json!([])); + fake.put_box(NAME, "running", serde_json::json!({})); + let out = fake.dispatch("spawn", &[]); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("is not this orb")); + let log = fake.log(); + assert!( + !log.iter().any(|l| l.starts_with("rm ") + || l.starts_with("create ") + || l.starts_with("exec ")), + "{log:?}" + ); + } + + #[test] + fn spawn_without_an_image_says_so() { + if !has_jq() { + return; + } + let fake = Fake::new(serde_json::json!([])); + let out = fake.dispatch("spawn", &[]); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("No orb image yet")); + } + + #[test] + fn pause_saves_then_suspends() { + if !has_jq() { + return; + } + let fake = Fake::new(serde_json::json!([ + snap( + "amp-orb-snap-p1-1700000000", + "ready", + "2026-11-01T00:00:00Z", + true + ), + snap( + "amp-orb-snap-p2-1700000000", + "ready", + "2026-11-01T00:00:00Z", + true + ), + ])); + fake.put_box(NAME, "running", orb_meta()); + ok(&fake.dispatch("pause", &[("ORB_SNAPSHOT_ID", "p1")])); + let log = fake.log(); + let save = log + .iter() + .position(|l| l.starts_with("snapshot save")) + .unwrap(); + let suspend = log.iter().position(|l| l.starts_with("suspend ")).unwrap(); + assert!(save < suspend, "{log:?}"); + assert_eq!(fake.state(NAME).as_deref(), Some("suspended")); + let snaps = fake.snapshots(); + assert!( + !snaps.contains(&"amp-orb-snap-p1-1700000000".to_string()), + "{snaps:?}" + ); + assert!( + snaps.contains(&"amp-orb-snap-p2-1700000000".to_string()), + "{snaps:?}" + ); + assert_eq!( + snaps + .iter() + .filter(|s| s.starts_with("amp-orb-snap-p1-")) + .count(), + 1 + ); + } + + #[test] + fn pause_resumes_a_suspended_orb_to_save() { + if !has_jq() { + return; + } + let fake = Fake::new(serde_json::json!([])); + fake.put_box(NAME, "suspended", orb_meta()); + ok(&fake.dispatch("pause", &[("ORB_SNAPSHOT_ID", "proj/with space")])); + let log = fake.log(); + let resume = log.iter().position(|l| l.starts_with("resume ")).unwrap(); + let save = log + .iter() + .position(|l| l.starts_with("snapshot save")) + .unwrap(); + let suspend = log.iter().position(|l| l.starts_with("suspend ")).unwrap(); + assert!(resume < save && save < suspend, "{log:?}"); + assert_eq!(fake.state(NAME).as_deref(), Some("suspended")); + let saved = fake.snapshots(); + assert!( + saved[0].starts_with("amp-orb-snap-proj-with-space-"), + "an odd project ID gets a clean name with a hash: {saved:?}" + ); + } + + #[test] + fn pause_without_a_snapshot_only_suspends() { + if !has_jq() { + return; + } + let fake = Fake::new(serde_json::json!([])); + fake.put_box(NAME, "running", orb_meta()); + ok(&fake.dispatch("pause", &[])); + assert!(!fake.log().iter().any(|l| l.starts_with("snapshot save"))); + assert_eq!(fake.state(NAME).as_deref(), Some("suspended")); + } + + #[test] + fn delete_removes_the_orb() { + if !has_jq() { + return; + } + let fake = Fake::new(serde_json::json!([])); + fake.put_box(NAME, "suspended", orb_meta()); + ok(&fake.dispatch("delete", &[])); + assert!(fake.state(NAME).is_none()); + // A second delete finds nothing and is fine. + ok(&fake.dispatch("delete", &[])); + } + + #[test] + fn status_reports_a_missing_token() { + if !has_jq() { + return; + } + let fake = Fake::new(serde_json::json!([])); + let out = fake.run(&["status"], &[]); + ok(&out); + let s = super::parse_status(&String::from_utf8_lossy(&out.stdout)).unwrap(); + assert!(s.signed_in); + assert!(!s.token_saved); + assert_eq!(s.service, "inactive"); + assert_eq!(s.image.status, "none"); + assert!(!s.connected()); + } + + #[test] + fn status_sees_a_saved_token() { + if !has_jq() { + return; + } + let fake = Fake::new(serde_json::json!([])); + let amp = fake.path().join("home/.local/share/amp"); + std::fs::create_dir_all(&).unwrap(); + std::fs::write( + amp.join("secrets.json"), + r#"{"orb-provider-token@https://ampcode.com/":"aop_live_x"}"#, + ) + .unwrap(); + let out = fake.run(&["status"], &[("AMP_ORBS_KEY_ID", "wkey_1")]); + ok(&out); + let s = super::parse_status(&String::from_utf8_lossy(&out.stdout)).unwrap(); + assert!(s.token_saved); + assert_eq!(s.key_id.as_deref(), Some("wkey_1")); + } +} From e1e777d69000c7df8e15d13e86e7c567d5fc24c1 Mon Sep 17 00:00:00 2001 From: CarmenDou <80885297+CarmenDou@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:03:39 -0500 Subject: [PATCH 03/23] Show the role of Amp orbs sandboxes and keep ADEs off them Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/app.rs | 26 +++++++++++++++++++++++--- src-tauri/src/orbs.rs | 4 +++- src-tauri/src/sandbox/view.rs | 17 +++++++++++++++++ src-tauri/src/tray.rs | 17 +++++++++++++++++ src/App.test.tsx | 1 + src/fixtures/state.json | 12 ++++++++---- src/types.ts | 5 +++++ 7 files changed, 74 insertions(+), 8 deletions(-) diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rs index 51060b4..4672aba 100644 --- a/src-tauri/src/app.rs +++ b/src-tauri/src/app.rs @@ -783,10 +783,14 @@ pub fn sizes_for(orgs: &[Org], org_id: Option<&str>, me: &Me) -> Vec /// The ADEs an action may use on a machine when none was asked for: the ones its mark lists, /// in the order they were added, else the default when it has no mark at all. Empty when the /// mark names only ADEs this build does not know, such as one a newer app connected: such a -/// sandbox never counts as the default. Only for picking an ADE to act with (connect, pair -/// again, reinstall, resume, sync). What a sandbox has is its mark alone (`Data::ades_of`). +/// sandbox never counts as the default, and neither does a sandbox of Amp orbs (`orbs::role`). +/// Only for picking an ADE to act with (connect, pair again, reinstall, resume, sync). What a +/// sandbox has is its mark alone (`Data::ades_of`). fn action_ades(m: &Machine) -> Vec { - if view::has_mark(&m.metadata) { + if crate::orbs::role(&m.metadata).is_some() { + // Amp orbs' sandboxes: Amp runs them, no ADE does. + Vec::new() + } else if view::has_mark(&m.metadata) { view::marked_ades(&m.metadata) } else { vec![Ade::default()] @@ -7325,6 +7329,22 @@ mod tests { assert_eq!(ades, [vec![Ade::T3], vec![Ade::T3], vec![], vec![]]); } + #[test] + fn a_sandbox_of_amp_orbs_never_defaults_to_an_ade() { + let mut d = data(); + // f has no mark, so it would default to T3; as an orb it has no ADE at all. + let f = d.machines.iter_mut().find(|m| m.id == "f").unwrap(); + f.metadata + .insert(crate::orbs::ROLE_KEY.into(), crate::orbs::ROLE_ORB.into()); + assert_eq!(d.ade_of("f"), None); + assert_eq!(d.pinned_ade_of("f"), None); + assert!(d.ades_of("f").is_empty()); + let views = sandbox_views(&d, Some("org-me"), now()); + let f = views.iter().find(|v| v.id == "f").unwrap(); + assert_eq!(f.role, Some(crate::orbs::Role::Orb)); + assert!(!f.connected); + } + #[test] fn a_sandbox_with_several_ades_keeps_t3_in_step() { let mut d = data(); diff --git a/src-tauri/src/orbs.rs b/src-tauri/src/orbs.rs index e1e55f3..cc54e2c 100644 --- a/src-tauri/src/orbs.rs +++ b/src-tauri/src/orbs.rs @@ -44,9 +44,11 @@ const PROVIDER_UNIT: &str = include_str!("../assets/amp-orbs/amp-orb-provider.se const IMAGE_UNIT: &str = include_str!("../assets/amp-orbs/amp-orb-image.service"); const IMAGE_TIMER: &str = include_str!("../assets/amp-orbs/amp-orb-image.timer"); -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub enum Role { + #[serde(rename = "ampOrbProvider")] Provider, + #[serde(rename = "ampOrb")] Orb, } diff --git a/src-tauri/src/sandbox/view.rs b/src-tauri/src/sandbox/view.rs index 4a1cc72..3a9e946 100644 --- a/src-tauri/src/sandbox/view.rs +++ b/src-tauri/src/sandbox/view.rs @@ -122,6 +122,8 @@ pub struct SandboxView { pub update_pending: bool, /// The sandbox's T3 is newer than the desktop's: T3 Code on this computer is behind. pub desktop_behind: bool, + /// Amp orbs' provider or one of its orbs. Such a sandbox is never an ADE's. + pub role: Option, } pub fn view_state(state: &str) -> ViewState { @@ -202,6 +204,7 @@ pub fn view(m: &Machine, now: DateTime) -> SandboxView { cooldown_minutes, update_pending: false, desktop_behind: false, + role: crate::orbs::role(&m.metadata), } } @@ -294,6 +297,20 @@ mod tests { v.iter().map(|c| c.seconds).collect() } + #[test] + fn a_sandbox_of_amp_orbs_shows_its_role() { + let mut m = machine("running"); + assert_eq!(view(&m, now()).role, None); + m.metadata.insert( + crate::orbs::ROLE_KEY.into(), + crate::orbs::ROLE_PROVIDER.into(), + ); + let v = view(&m, now()); + assert_eq!(v.role, Some(crate::orbs::Role::Provider)); + assert_eq!(serde_json::to_value(&v).unwrap()["role"], "ampOrbProvider"); + assert!(v.ades.is_empty() && !v.connected); + } + #[test] fn state_mapping() { let table = [ diff --git a/src-tauri/src/tray.rs b/src-tauri/src/tray.rs index c816657..5405edd 100644 --- a/src-tauri/src/tray.rs +++ b/src-tauri/src/tray.rs @@ -72,6 +72,8 @@ pub fn tray_rows(state: &AppState) -> Vec { state .sandboxes .iter() + // Amp runs the sandboxes of Amp orbs: pausing them here would break its threads. + .filter(|s| s.role.is_none()) .map(|s| TrayRow { id: s.id.clone(), label: row_label(&s.name, s.state), @@ -511,6 +513,7 @@ mod tests { cooldown_minutes: None, update_pending: false, desktop_behind: false, + role: None, } } @@ -561,6 +564,20 @@ mod tests { assert_eq!(rows[2].action, None); } + #[test] + fn the_tray_leaves_out_sandboxes_of_amp_orbs() { + let mut orb = row("orb", ViewState::Running); + orb.role = Some(crate::orbs::Role::Orb); + let mut provider = row("p", ViewState::Running); + provider.role = Some(crate::orbs::Role::Provider); + let state = AppState { + sandboxes: vec![orb, row("a", ViewState::Running), provider], + ..AppState::default() + }; + let ids: Vec = tray_rows(&state).into_iter().map(|r| r.id).collect(); + assert_eq!(ids, ["a"]); + } + #[test] fn open_item_follows_connected() { assert_eq!(open_label(Ade::T3, true), "Open in T3 Code"); diff --git a/src/App.test.tsx b/src/App.test.tsx index d54366f..bfaa533 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -62,6 +62,7 @@ const box: SandboxView = { cooldownMinutes: null, updatePending: false, desktopBehind: false, + role: null, }; type Answer = (args: Record) => unknown; diff --git a/src/fixtures/state.json b/src/fixtures/state.json index f5c7e87..db85f3d 100644 --- a/src/fixtures/state.json +++ b/src/fixtures/state.json @@ -63,7 +63,8 @@ "runLeftMinutes": 100, "cooldownMinutes": null, "updatePending": false, - "desktopBehind": false + "desktopBehind": false, + "role": null }, { "id": "e", @@ -81,7 +82,8 @@ "runLeftMinutes": null, "cooldownMinutes": null, "updatePending": true, - "desktopBehind": false + "desktopBehind": false, + "role": null }, { "id": "f", @@ -99,7 +101,8 @@ "runLeftMinutes": null, "cooldownMinutes": null, "updatePending": false, - "desktopBehind": false + "desktopBehind": false, + "role": null }, { "id": "g", @@ -117,7 +120,8 @@ "runLeftMinutes": null, "cooldownMinutes": null, "updatePending": false, - "desktopBehind": true + "desktopBehind": true, + "role": null } ], "sizes": [ diff --git a/src/types.ts b/src/types.ts index 8639c50..8cc10bd 100644 --- a/src/types.ts +++ b/src/types.ts @@ -40,6 +40,9 @@ export interface OrgView { personal: boolean; } +/** A sandbox of Amp orbs: the always-on provider, or an orb that runs one Amp thread. */ +export type SandboxRole = "ampOrbProvider" | "ampOrb"; + export interface SandboxView { id: string; name: string; @@ -58,6 +61,8 @@ export interface SandboxView { updatePending: boolean; /** The sandbox's T3 is newer than the desktop's: offer "Update T3 Code on this computer", never [Update]. */ desktopBehind: boolean; + /** Amp orbs' provider or one of its orbs: Amp runs it, no ADE connects to it. */ + role: SandboxRole | null; } export interface SizeChoice { From a4a37c357f3243ee2006aa283667c588a2675b27 Mon Sep 17 00:00:00 2001 From: CarmenDou <80885297+CarmenDou@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:14:28 -0500 Subject: [PATCH 04/23] Add the Amp orbs page, its commands and its state Amp mode offers Amp orbs in the list. The page sets up the provider sandbox, opens the sign-in terminal on it, shows its status, rebuilds the orb image and removes it all. Orb and provider rows say what they are, open their thread or the page, and have no ADE, power or delete actions. Free plans get a paid-plan notice. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/app.rs | 371 ++++++++++++++++++++++++++++++ src-tauri/src/commands.rs | 28 +++ src-tauri/src/lib.rs | 5 + src-tauri/src/orbs.rs | 45 ++++ src/AmpOrbs.tsx | 458 ++++++++++++++++++++++++++++++++++++++ src/App.test.tsx | 146 ++++++++++++ src/App.tsx | 12 +- src/SandboxList.tsx | 16 +- src/SandboxMenu.tsx | 51 ++++- src/Settings.tsx | 26 ++- src/api.ts | 5 + src/fixtures/state.json | 6 + src/preview.ts | 94 +++++++- src/styles.css | 140 ++++++++++++ src/types.test.ts | 1 + src/types.ts | 33 +++ 16 files changed, 1418 insertions(+), 19 deletions(-) create mode 100644 src/AmpOrbs.tsx diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rs index 4672aba..cc4136d 100644 --- a/src-tauri/src/app.rs +++ b/src-tauri/src/app.rs @@ -553,6 +553,8 @@ pub struct AppState { pub next_steps: Vec, /// GitHub on the sandboxes the list shows, for those the app checked or signs in. pub github: Vec, + /// Amp orbs in the selected workspace (`orbs`). + pub orbs: crate::orbs::OrbsView, pub error: Option, pub start_at_login: bool, /// This build's version and its updates (see `updater`). Set once the app starts. @@ -998,6 +1000,7 @@ impl AppState { .collect(); self.sizes = sizes_for(&orgs, org_id.as_deref(), me); self.sleep_choices = view::sleep_choices(me, tier == "free"); + self.orbs.allowed = tier != "free" && self.sleep_choices.iter().any(|c| c.seconds == 0); self.sandboxes = sandbox_views(d, org_id.as_deref(), now); self.snapshots = snapshot_views(&d.snapshots, &d.templates, org_id.as_deref()); self.tier = tier; @@ -5268,6 +5271,244 @@ impl Core { .await } + // ---- Amp orbs ---- + + /// What an Amp orbs flow starts from: the client, the account, the selected workspace and + /// the sizes it allows. Fails on a plan without always-on sandboxes. + fn orbs_context(&self) -> Res<(Client, u64, String, Vec)> { + let (client, account, (org, allowed, sizes)) = self.signed_in_with(|i| { + let sizes = i + .state + .sizes + .iter() + .map(|s| crate::api::MachineSpec { + vcpus: s.vcpus, + mem_mib: s.mem_mib, + }) + .collect::>(); + (i.state.org_id.clone(), i.state.orbs.allowed, sizes) + })?; + if !allowed { + return Err(ErrorView::other( + "Amp orbs need a paid plan: the provider sandbox runs all the time.", + )); + } + let org = org.ok_or_else(|| ErrorView::other("Pick a workspace first"))?; + Ok((client, account, org, sizes)) + } + + /// The provider sandbox of workspace `org`, as the last refresh read it. + fn orbs_provider(&self, account: u64, org: &str) -> Option { + self.read_in(account, |i| { + crate::orbs::find_provider(&i.data.machines, org) + .ok() + .flatten() + .cloned() + }) + .flatten() + } + + /// Sets Amp orbs up in the selected workspace, or repairs them (`orbs::set_up`), then opens + /// the sign-in terminal on the provider when it is not connected to Amp yet. + pub async fn orbs_set_up(self: &Arc) -> Res<()> { + let (client, account, org, sizes) = match self.orbs_context() { + Ok(c) => c, + Err(e) => return self.settle(Err(e)), + }; + let first = if self.orbs_provider(account, &org).is_some() { + crate::orbs::OrbsStep::Installing + } else { + crate::orbs::OrbsStep::Creating + }; + let busy = self.update_in(account, |i| { + let busy = i.state.orbs.step.is_some(); + if !busy { + i.state.orbs.step = Some(first); + } + busy + }); + if busy != Some(false) { + return Err(ErrorView::other("Amp orbs are being set up already")); + } + let r = self.orbs_install(&client, account, &org, &sizes).await; + let r = match r { + Ok((id, connected)) if !connected => { + self.open_terminal_command(&id, crate::orbs::CONNECT_COMMAND, account) + .await + } + other => other.map(drop), + }; + self.act(account, std::future::ready(r)).await + } + + /// Runs `orbs::set_up` with its steps in the state, and keeps the status it ends with. + /// Returns the provider's id and whether it is connected to Amp. + async fn orbs_install( + self: &Arc, + client: &Client, + account: u64, + org: &str, + sizes: &[crate::api::MachineSpec], + ) -> Res<(String, bool)> { + let progress = |s| { + self.update_in(account, |i| i.state.orbs.step = Some(s)); + }; + let r = crate::orbs::set_up(client, org, self.base.as_str(), sizes, progress).await; + self.update_in(account, |i| { + i.state.orbs.step = None; + if let Ok(done) = &r { + i.state.orbs.provider_id = Some(done.provider_id.clone()); + i.state.orbs.status = done.status.clone(); + } + }); + let done = r.map_err(ErrorView::from)?; + let connected = done + .status + .as_ref() + .is_some_and(|s| s.signed_in && s.token_saved); + Ok((done.provider_id, connected)) + } + + /// Reads the provider's status into the state. A provider that is not running has none. + /// A key that expires within a month is renewed (`orbs::renew_due`). + pub async fn orbs_refresh(self: &Arc) -> Res<()> { + let (client, account, org) = self.signed_in_with(|i| i.state.org_id.clone())?; + let Some(org) = org else { return Ok(()) }; + let Some(provider) = self.orbs_provider(account, &org) else { + self.update_in(account, |i| { + i.state.orbs.provider_id = None; + i.state.orbs.status = None; + }); + return Ok(()); + }; + let status = if provider.state == "running" { + crate::orbs::status(&client, &provider.id) + .await + .map_err(ErrorView::from)? + } else { + None + }; + let renew = status + .as_ref() + .is_some_and(|s| crate::orbs::renew_due(s, Utc::now())); + self.update_in(account, |i| { + i.state.orbs.provider_id = Some(provider.id.clone()); + i.state.orbs.status = status; + }); + if renew { + let (client, account, org, sizes) = self.orbs_context()?; + let free = self.update_in(account, |i| { + let free = i.state.orbs.step.is_none(); + if free { + i.state.orbs.step = Some(crate::orbs::OrbsStep::Installing); + } + free + }); + if free == Some(true) { + self.orbs_install(&client, account, &org, &sizes).await?; + } + } + Ok(()) + } + + /// Opens the sign-in terminal on the provider: it signs in to Amp and adds the provider. + pub async fn orbs_sign_in(self: &Arc) -> Res<()> { + let (_, account, org) = self.signed_in_with(|i| i.state.org_id.clone())?; + let provider = org.and_then(|o| self.orbs_provider(account, &o)); + let r = match provider { + Some(p) => { + self.open_terminal_command(&p.id, crate::orbs::CONNECT_COMMAND, account) + .await + } + None => Err(ErrorView::other("Set up Amp orbs first")), + }; + self.act(account, std::future::ready(r)).await + } + + /// Imports Amp's orb image again now, on the provider. + pub async fn orbs_rebuild_image(self: &Arc) -> Res<()> { + let (client, account, org) = self.signed_in_with(|i| i.state.org_id.clone())?; + let provider = org.and_then(|o| self.orbs_provider(account, &o)); + let r = match provider { + Some(p) => crate::orbs::rebuild_image(&client, &p.id) + .await + .map_err(ErrorView::from), + None => Err(ErrorView::other("Set up Amp orbs first")), + }; + let r = self.settle_in(account, r); + if r.is_ok() { + let _ = self.orbs_refresh().await; + } + r + } + + /// Removes Amp orbs from the selected workspace (`orbs::remove`). + pub async fn orbs_remove(self: &Arc) -> Res<()> { + let (client, account, (org, orbs)) = self.signed_in_with(|i| { + let org = i.state.org_id.clone(); + let orbs = org + .as_deref() + .map_or(0, |o| crate::orbs::orbs_of(&i.data.machines, o).count()); + (org, orbs) + })?; + let Some(org) = org else { + return self.settle(Err(ErrorView::other("Pick a workspace first"))); + }; + let Some(provider) = self.orbs_provider(account, &org) else { + return self.settle(Err(ErrorView::other("Amp orbs are not set up here"))); + }; + let busy = self.update_in(account, |i| { + let busy = i.state.orbs.step.is_some(); + if !busy { + i.state.orbs.step = Some(crate::orbs::OrbsStep::Removing); + } + busy + }); + if busy != Some(false) { + return Err(ErrorView::other( + "Amp orbs are busy. Try again in a moment.", + )); + } + let r = crate::orbs::remove(&client, &org, &provider, orbs) + .await + .map_err(ErrorView::from); + self.update_in(account, |i| { + i.state.orbs.step = None; + if r.is_ok() { + i.state.orbs.provider_id = None; + i.state.orbs.status = None; + } + }); + self.act(account, std::future::ready(r)).await + } + + /// Opens a terminal on sandbox `id` that runs `remote`, a plain command there, with the + /// sandbox's ordinary SSH token, as a terminal ADE opens (`open_terminal_login`). The + /// sandbox wakes first. + async fn open_terminal_command( + self: &Arc, + id: &str, + remote: &'static str, + account: u64, + ) -> Res<()> { + // Amp is a terminal ADE: its check finds the OpenSSH client. + let ade = Ade::Amp; + self.check_app_first(ade).await?; + let client = self + .read_in(account, |i| i.client.clone()) + .flatten() + .ok_or_else(account_changed)?; + sandbox::ensure_running(&client, id) + .await + .map_err(ErrorView::from)?; + let ssh_client = self.checked_app(ade).await?; + let tok = self.ade_token(ade, &client, id, account).await?; + let args = ssh::terminal_args(&tok, remote).map_err(ErrorView::other)?; + guarded(&self.gate(account), || (self.terminal)(&ssh_client, &args)) + .ok_or_else(account_changed)? + .map_err(ErrorView::other) + } + /// Sets the ADE up again on the sandbox at the desktop version. pub async fn reinstall(self: &Arc, id: &str, ade: Option) -> Res<()> { let account = self.account(); @@ -6288,6 +6529,7 @@ mod tests { "t3Switch", "nextSteps", "github", + "orbs", "error", "startAtLogin", "update", @@ -12245,6 +12487,135 @@ mod tests { (core, opened) } + /// `cmux_server` on a plan with always-on sandboxes, whose exec answers the Amp orbs install + /// and status with `status`, and which mints a workspace key. + async fn orbs_server( + metadata: serde_json::Value, + tier: &str, + status: &str, + ) -> (wiremock::MockServer, Url) { + use wiremock::matchers::{body_string_contains, method, path}; + use wiremock::{Mock, ResponseTemplate}; + let (server, base) = cmux_server(metadata).await; + Mock::given(method("GET")) + .and(path("/v1/me")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "userId": 7, "login": "alex", "alwaysOnAllowed": tier != "free", + "idleChoicesSeconds": [300, 1800], + "allowedSpecs": [{"vcpus": 2, "memMiB": 4096}, {"vcpus": 4, "memMiB": 8192}], + "org": {"id": "org-me", "tier": tier, "kind": "personal"} + }))) + .with_priority(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/v1/orgs/org-me/keys")) + .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({ + "apiKey": {"id": "wkey_1", "expiresAt": "2027-12-03T00:00:00Z"}, "key": "ibk_orbs" + }))) + .mount(&server) + .await; + for marker in ["set -eu", "amp-orbs status; fi"] { + Mock::given(method("POST")) + .and(path("/v1/machines/m1/exec")) + .and(body_string_contains(marker)) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "stdout": format!("{status}\n"), "stderr": "", "exitCode": 0 + }))) + .with_priority(1) + .mount(&server) + .await; + } + (server, base) + } + + const ORBS_NOT_SIGNED_IN: &str = r#"{"version":1,"signedIn":false,"tokenSaved":false,"service":"active","image":{"status":"building"},"keyId":"wkey_1","keyExpires":"2027-12-03T00:00:00Z"}"#; + + #[tokio::test] + async fn setting_up_orbs_installs_and_opens_the_sign_in_terminal() { + let (server, base) = orbs_server(serde_json::json!({}), "pro", ORBS_NOT_SIGNED_IN).await; + let (core, opened) = amp_core(&base, true); + core.update(|i| i.data.me = None); + core.refresh(false).await; + assert!(core.state().orbs.allowed); + assert_eq!(core.orbs_set_up().await, Ok(())); + let opened = opened.lock().unwrap().clone(); + assert_eq!(opened.len(), 1, "{opened:?}"); + assert!( + opened[0].ends_with("ibssh_new@ssh.example.test amp-orbs-connect"), + "{opened:?}" + ); + let s = core.state(); + assert_eq!(s.orbs.step, None); + assert_eq!(s.orbs.provider_id.as_deref(), Some("m1")); + assert_eq!(s.orbs.status.unwrap().image.status, "building"); + assert_eq!(s.error, None); + let reqs = server.received_requests().await.unwrap(); + let create = reqs + .iter() + .find(|r| r.method.as_str() == "POST" && r.url.path() == "/v1/machines") + .unwrap(); + let body: serde_json::Value = serde_json::from_slice(&create.body).unwrap(); + assert_eq!(body["templateId"], "minimal"); + assert_eq!(body["autoSuspendAfterSeconds"], 0); + assert_eq!( + (body["vcpus"].clone(), body["memMiB"].clone()), + (2.into(), 4096.into()) + ); + assert_eq!(body["metadata"]["instabox-role"], "amp-orb-provider"); + let install = reqs + .iter() + .find(|r| { + r.url.path().ends_with("/exec") + && String::from_utf8_lossy(&r.body).contains("set -eu") + }) + .unwrap(); + let body: serde_json::Value = serde_json::from_slice(&install.body).unwrap(); + assert_eq!(body["envs"]["AMP_ORBS_KEY"], "ibk_orbs"); + assert!(body["cmd"].as_str().unwrap().contains(&format!( + "INSTABOX_API_URL={}", + base.as_str().trim_end_matches('/') + ))); + } + + #[tokio::test] + async fn orbs_refuse_on_free() { + let (server, base) = orbs_server(serde_json::json!({}), "free", ORBS_NOT_SIGNED_IN).await; + let (core, opened) = amp_core(&base, true); + core.update(|i| i.data.me = None); + core.refresh(false).await; + assert_eq!(core.state().tier, "free"); + assert!(!core.state().orbs.allowed); + let e = core.orbs_set_up().await.unwrap_err(); + assert!(e.message.contains("paid plan"), "{e:?}"); + assert_eq!(core.state().error, Some(e)); + assert!(opened.lock().unwrap().is_empty()); + let r = requests(&server).await; + assert!( + !r.iter() + .any(|x| x.contains("/keys") || x == "POST /v1/machines"), + "{r:?}" + ); + } + + #[tokio::test] + async fn refresh_reads_the_orbs_status() { + let md = serde_json::json!({"instabox-role": "amp-orb-provider"}); + let (_server, base) = orbs_server(md, "pro", ORBS_NOT_SIGNED_IN).await; + let (core, _) = amp_core(&base, true); + core.refresh(false).await; + assert_eq!( + core.state().sandboxes[0].role, + Some(crate::orbs::Role::Provider) + ); + core.orbs_refresh().await.unwrap(); + let s = core.state().orbs; + assert_eq!(s.provider_id.as_deref(), Some("m1")); + let status = s.status.unwrap(); + assert_eq!(status.key_id.as_deref(), Some("wkey_1")); + assert!(!status.connected()); + } + #[tokio::test] async fn installing_amp_sets_it_up_marks_the_sandbox_and_opens_a_terminal() { let (server, base) = amp_server( diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 2b3304c..b4f9481 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -185,6 +185,34 @@ pub async fn set_auto_sleep(core: Shared<'_>, id: String, seconds: i64) -> Res<( core.inner().clone().set_auto_sleep(&id, seconds).await } +/// Sets Amp orbs up in the selected workspace, or repairs them. +#[tauri::command] +pub async fn orbs_set_up(core: Shared<'_>) -> Res<()> { + core.inner().clone().orbs_set_up().await +} + +/// Reads the Amp orbs provider's status into the state. +#[tauri::command] +pub async fn orbs_refresh(core: Shared<'_>) -> Res<()> { + core.inner().clone().orbs_refresh().await +} + +/// Opens the terminal on the provider that signs in to Amp. +#[tauri::command] +pub async fn orbs_sign_in(core: Shared<'_>) -> Res<()> { + core.inner().clone().orbs_sign_in().await +} + +#[tauri::command] +pub async fn orbs_rebuild_image(core: Shared<'_>) -> Res<()> { + core.inner().clone().orbs_rebuild_image().await +} + +#[tauri::command] +pub async fn orbs_remove(core: Shared<'_>) -> Res<()> { + core.inner().clone().orbs_remove().await +} + /// Sets the ADE (T3) up again on the sandbox. cmux installs nothing there to set up again. #[tauri::command] pub async fn reinstall_t3(core: Shared<'_>, id: String, ade: Option) -> Res<()> { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b389fa8..cf05f4a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -290,6 +290,11 @@ pub fn run() { commands::delete, commands::resize, commands::set_auto_sleep, + commands::orbs_set_up, + commands::orbs_refresh, + commands::orbs_sign_in, + commands::orbs_rebuild_image, + commands::orbs_remove, commands::reinstall_t3, commands::agent_sign_in, commands::agent_status, diff --git a/src-tauri/src/orbs.rs b/src-tauri/src/orbs.rs index cc54e2c..e6e243b 100644 --- a/src-tauri/src/orbs.rs +++ b/src-tauri/src/orbs.rs @@ -137,6 +137,33 @@ pub enum OrbsStep { Removing, } +/// Amp orbs in the app's state. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OrbsView { + /// The selected workspace may run Amp orbs: a paid plan with always-on sandboxes. + pub allowed: bool, + /// What a setup or a removal is doing now. + pub step: Option, + /// The provider sandbox `status` came from. + pub provider_id: Option, + /// What the provider said when the app last asked. + pub status: Option, +} + +/// Days before the provider's key expires when the app makes it a new one. +const RENEW_DAYS: i64 = 30; + +/// True when the provider's key expires within `RENEW_DAYS` of `now`. False when its expiry is +/// not known. +pub fn renew_due(status: &ProviderStatus, now: chrono::DateTime) -> bool { + status + .key_expires + .as_deref() + .and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok()) + .is_some_and(|t| t.with_timezone(&chrono::Utc) - now < chrono::Duration::days(RENEW_DAYS)) +} + fn fail(message: impl Into) -> SandboxError { SandboxError::Api(api::Error { status: 0, @@ -839,6 +866,24 @@ mod tests { assert!(connected.connected()); } + #[test] + fn the_key_renews_a_month_before_it_expires() { + use chrono::TimeZone; + let now = chrono::Utc.with_ymd_and_hms(2026, 12, 4, 0, 0, 0).unwrap(); + let with = |t: Option<&str>| ProviderStatus { + key_expires: t.map(str::to_string), + ..parse_status(STATUS_LINE).unwrap() + }; + assert!(!renew_due(&with(Some("2027-12-03T00:00:00Z")), now)); + assert!(renew_due(&with(Some("2026-12-20T00:00:00Z")), now)); + assert!( + renew_due(&with(Some("2026-11-01T00:00:00Z")), now), + "an expired key too" + ); + assert!(!renew_due(&with(None), now)); + assert!(!renew_due(&with(Some("soon")), now)); + } + #[test] fn install_script_carries_the_program_whole() { let s = install_script("https://api.instabox.sh/", &spec(4, 8192)); diff --git a/src/AmpOrbs.tsx b/src/AmpOrbs.tsx new file mode 100644 index 0000000..b1c53ad --- /dev/null +++ b/src/AmpOrbs.tsx @@ -0,0 +1,458 @@ +import { useEffect, useState } from "react"; +import { openSsh, orbsRebuildImage, orbsRefresh, orbsRemove, orbsSetUp, orbsSignIn } from "./api"; +import type { Mode } from "./ades"; +import { cap, Line, openExternal, StateDot, stateLabel } from "./common"; +import type { Run } from "./common"; +import { Check, Spinner, Terminal } from "./icons"; +import type { AppState, ProviderStatus, SandboxView } from "./types"; + +export const PROVIDER_NAME = "amp-orb-provider"; +export const AMP_URL = "https://ampcode.com"; +export const PRICING_URL = "https://instabox.sh/pricing"; +const CARD_DISMISSED = "instaade.ampOrbsCardDismissed"; + +/** Hourly prices of a running sandbox (instabox pricing). */ +const VCPU_HOUR = 0.004; +const GIB_HOUR = 0.00225; +const HOURS_A_MONTH = 730; + +/** The provider sandbox of the selected workspace. */ +export const orbsProvider = (state: AppState) => state.sandboxes.find((s) => s.role === "ampOrbProvider"); + +/** The orb sandboxes of the selected workspace. */ +export const orbSandboxes = (state: AppState) => state.sandboxes.filter((s) => s.role === "ampOrb"); + +/** Amp's page of the thread an orb runs: its name is the thread ID, lowercased. */ +export function threadUrl(name: string): string | null { + const m = /^amp-t-([0-9a-f-]{36})$/.exec(name); + return m ? `${AMP_URL}/threads/T-${m[1]}` : null; +} + +/** vCPUs and GB of a size label such as "2 vCPU / 4 GB". */ +function parseSize(label: string): { vcpus: number; gb: number } | null { + const m = /^(\d+) vCPU \/ ([\d.]+) GB$/.exec(label); + return m ? { vcpus: Number(m[1]), gb: Number(m[2]) } : null; +} + +const hourly = (s: { vcpus: number; gb: number }) => s.vcpus * VCPU_HOUR + s.gb * GIB_HOUR; + +/** "about $12 a month" for a sandbox of `label` that runs all the time. */ +export function monthlyCost(label: string): string | null { + const s = parseSize(label); + return s ? `about $${Math.round(hourly(s) * HOURS_A_MONTH)} a month` : null; +} + +/** "$0.034 an hour" while a sandbox of `label` runs. */ +export function hourlyCost(label: string): string | null { + const s = parseSize(label); + return s ? `$${hourly(s).toFixed(3)} an hour` : null; +} + +/** Signed in to Amp, the provider token saved and the provider service running. */ +export const isConnected = (s: ProviderStatus | null | undefined) => !!s && s.signedIn && s.tokenSaved && s.service === "active"; + +function readDismissed(): boolean { + try { + return localStorage.getItem(CARD_DISMISSED) === "1"; + } catch { + return false; + } +} + +function saveDismissed() { + try { + localStorage.setItem(CARD_DISMISSED, "1"); + } catch { + // Only a convenience: the card shows again next time. + } +} + +function OrbMark() { + return ( + + ); +} + +/** The list's offer to set Amp orbs up: in Amp mode, while the workspace has no provider. */ +export function OrbsCard({ state, mode, onOrbs }: { state: AppState; mode: Mode; onOrbs: () => void }) { + const [dismissed, setDismissed] = useState(readDismissed); + if (mode !== "amp" || dismissed || orbsProvider(state)) return null; + return ( +
+
+ + Run Amp threads on instabox +
+

Amp orbs give each Amp thread its own sandbox here. They keep working while your computer sleeps.

+
+ + +
+
+ ); +} + +/** The line of a row of an Amp orbs sandbox, in place of its ADEs. */ +export function RoleLine({ s, onOrbs }: { s: SandboxView; onOrbs: () => void }) { + if (s.role === "ampOrbProvider") { + return ( +
+
+ Amp orbs provider + always on +
+ +
+ ); + } + const url = threadUrl(s.name); + return ( +
+
+ Amp orb + {s.state === "running" ? "working on a thread" : s.state === "paused" ? "paused by Amp" : stateLabel(s.state).toLowerCase()} +
+ {url && ( + + )} +
+ ); +} + +/** The details of an Amp orbs sandbox: Amp runs it, so it has no ADE, power or delete. */ +export function OrbSandboxDetails({ sandbox: s, run, onOrbs }: { sandbox: SandboxView; run: Run; onOrbs: () => void }) { + const provider = s.role === "ampOrbProvider"; + const url = provider ? null : threadUrl(s.name); + return ( +
+
+
+
+
+
+ {provider ? "The Amp orbs provider" : "Amp manages this sandbox"} + + {provider + ? "It runs all the time and starts a sandbox for each Amp thread. Change it on the Amp orbs page." + : "Amp starts, pauses and deletes it with its thread. Delete the thread in Amp to delete it."} + +
+
+
+ {provider ? ( + + ) : ( + url && ( + + ) + )} +
+
+

Power

+
+
+ Status + + + {stateLabel(s.state)} + +
+
+ Auto sleep + {provider ? "Never" : "Amp decides"} +
+
+ Size + {s.size} +
+
+
+
+

Look inside

+
+
+ Terminal + +
+
+
+
+
+ ); +} + +type StepState = "done" | "now" | "todo" | "failed"; + +function StepIcon({ state }: { state: StepState }) { + if (state === "done") + return ( + + + + ); + if (state === "now") + return ( + + + + ); + return ; +} + +interface Step { + title: string; + detail: string; + state: StepState; + action?: { label: string; onClick: () => void }; +} + +function Steps({ steps }: { steps: Step[] }) { + return ( +
    + {steps.map((s) => ( +
  1. + +
    + {s.title} + {s.detail} + {s.action && ( + + )} +
    +
  2. + ))} +
+ ); +} + +function imageText(status: ProviderStatus | null): string { + switch (status?.image.status) { + case "ready": + return status.image.finishedAt && new Date(status.image.finishedAt).toDateString() === new Date().toDateString() ? "Updated today" : "Ready"; + case "building": + return "Building, about 5 minutes"; + case "failed": + return "Failed"; + default: + return "Not built yet"; + } +} + +function keyText(status: ProviderStatus | null): string { + if (!status?.keyExpires) return "Unknown"; + const days = (new Date(status.keyExpires).getTime() - Date.now()) / 86_400_000; + return days > 30 ? "Renews by itself" : "Renews soon"; +} + +/** Amp orbs on a plan that cannot run them. */ +function PaidOnly() { + return ( +
+
+ Amp orbs need a paid plan + The provider sandbox runs all the time. The Free plan pauses every sandbox after 30 minutes. +
+ +

You can still use Amp: install it on any sandbox and run it in a terminal.

+
+ ); +} + +/** The Amp orbs page: setup, its status, and removal. */ +export default function AmpOrbs({ state, run }: { state: AppState; run: Run }) { + const provider = orbsProvider(state); + const orbs = orbSandboxes(state); + const { step } = state.orbs; + const status = provider && state.orbs.providerId === provider.id ? state.orbs.status : null; + const connected = isConnected(status); + const [confirmRemove, setConfirmRemove] = useState(false); + const providerId = provider?.id; + const providerRunning = provider?.state === "running"; + const settled = connected && status?.image.status !== "building"; + + // Read the provider's status now, and again every 10 s until it is connected and its image built. + useEffect(() => { + if (!providerId || step) return; + void orbsRefresh().catch(() => {}); + if (settled) return; + const t = setInterval(() => void orbsRefresh().catch(() => {}), 10_000); + return () => clearInterval(t); + }, [providerId, providerRunning, step, settled]); + + if (!state.orbs.allowed && !provider) return
; + + const smallest = state.sizes[0]?.label ?? ""; + const providerSize = provider?.size ?? smallest; + const orbSize = state.sizes.find((z) => z.vcpus === 4 && z.memMiB === 8192)?.label ?? smallest; + const setUp = () => void run(() => orbsSetUp()); + const signIn = () => void run(() => orbsSignIn()); + + const remove = ( +
+ + Delete the threads in Amp first, so Amp deletes their sandboxes too. +
+ ); + + if (provider && connected && !step) { + const running = orbs.filter((o) => o.state === "running").length; + const paused = orbs.length - running; + return ( +
+
+
+ + + instabox is your orb provider in Amp. Threads keep running when your computer sleeps. +
+ {!providerRunning && } +
+

Provider

+
+
+ {provider.name} + + + {stateLabel(provider.state)} + +
+
+ Size + {provider.size} +
+
+ Auto sleep + {["Never", monthlyCost(provider.size)].filter(Boolean).join(" · ")} +
+
+
+
+

Orbs

+
+
+ Sandboxes + {orbs.length ? `${running} running · ${paused} paused` : "None yet"} +
+
+ Orb image + {imageText(status)} +
+
+ instabox key + {keyText(status)} +
+
+ {status?.image.status === "failed" && status.image.error &&

{status.image.error}

} +
+
+ + +
+ {remove} +
+
+ ); + } + + const imageState: StepState = + status?.image.status === "ready" ? "done" : status?.image.status === "building" ? "now" : status?.image.status === "failed" ? "failed" : "todo"; + const steps: Step[] = [ + { title: "Paid plan", detail: `${cap(state.tier)} · always-on sandboxes are allowed`, state: "done" }, + { + title: "Provider sandbox", + detail: [PROVIDER_NAME, providerSize, "always on"].filter(Boolean).join(" · "), + state: step === "creating" || step === "installing" ? "now" : provider ? (providerRunning ? "done" : "failed") : "todo", + }, + { + title: "Sign in to Amp", + detail: status?.signedIn ? "Signed in" : "A terminal opens on the provider. Follow it to sign in to Amp in your browser.", + state: status?.signedIn ? "done" : status ? "now" : "todo", + action: status && !status.tokenSaved && !step ? { label: "Open sign-in terminal", onClick: signIn } : undefined, + }, + { + title: "Add instabox to Amp", + detail: "Made for you and set as your default orb provider. No token to copy.", + state: status?.tokenSaved ? "done" : "todo", + }, + { + title: "Build the orb image", + detail: status?.image.status === "failed" ? (status.image.error ?? "The image did not build") : "About 5 minutes. It updates every day.", + state: imageState, + action: status?.image.status === "failed" && !step ? { label: "Build again", onClick: () => void run(() => orbsRebuildImage()) } : undefined, + }, + { title: "Connect to Amp", detail: "Then pick instabox for a thread in Amp.", state: connected ? "done" : "todo" }, + ]; + const stepLabel = step === "creating" ? "Creating the provider sandbox…" : step === "installing" ? "Installing on the provider…" : step === "removing" ? "Removing Amp orbs…" : null; + + return ( +
+
+

InstaADE adds one always-on sandbox to your workspace. It starts a sandbox for each Amp thread, and pauses it when Amp says so.

+ {provider && !providerRunning && !step && } + +
+ What it costs + + {`The provider sandbox runs all the time: ${monthlyCost(providerSize) ?? "a small sandbox"}. Each orb bills like a sandbox, so a ${orbSize} orb is ${hourlyCost(orbSize) ?? "billed"} while it runs.`} + +
+ {stepLabel ? ( + + ) : !provider ? ( + + ) : ( +
+ + +
+ )} + {provider && !step && remove} +
+
+ ); +} diff --git a/src/App.test.tsx b/src/App.test.tsx index bfaa533..003ccab 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -43,6 +43,7 @@ const sample: AppState = { t3Switch: null, nextSteps: [], github: [], + orbs: { allowed: false, step: null, providerId: null, status: null }, error: null, startAtLogin: false, update: null, @@ -2777,3 +2778,148 @@ test("old app: the notice shows on the other screens too, sign-in included", asy await screen.findByRole("button", { name: "Sign in with GitHub" }); expect(screen.getByText(oldAppText)).toBeTruthy(); }); + +// ---- Amp orbs ---- + +const PRO_ORBS = { + tier: "pro", + sizes: [ + { vcpus: 2, memMiB: 4096, label: "2 vCPU / 4 GB" }, + { vcpus: 4, memMiB: 8192, label: "4 vCPU / 8 GB" }, + ], + sleepChoices: [{ seconds: 1800, label: "After 30 min" }, { seconds: 0, label: "Never" }], + orbs: { allowed: true, step: null, providerId: null, status: null }, +} satisfies Partial; + +const ORB_STATUS = { + version: 1, + signedIn: true, + tokenSaved: true, + service: "active", + image: { status: "ready" as const, snapshot: "amp-orb-base-1", finishedAt: "2026-12-01T00:00:00Z", error: null }, + keyId: "wkey_1", + keyExpires: "2099-01-01T00:00:00Z", +}; + +const PROVIDER: Partial = { id: "p", name: "amp-orb-provider", role: "ampOrbProvider", ades: [], connected: false, size: "2 vCPU / 4 GB" }; +const ORB: Partial = { id: "o", name: "amp-t-3f2a9c00-0000-4000-8000-000000000001", role: "ampOrb", ades: [], connected: false }; + +test("the list offers Amp orbs in Amp mode, and Later puts the offer away", async () => { + picked("amp"); + show({ ades: [t3Ade, ampAde], ...PRO_ORBS }, [{}]); + const card = await screen.findByRole("region", { name: "Amp orbs" }); + expect(within(card).getByText("Run Amp threads on instabox")).toBeTruthy(); + await userEvent.click(within(card).getByRole("button", { name: "Later" })); + expect(screen.queryByRole("region", { name: "Amp orbs" })).toBeNull(); + cleanup(); + show({ ades: [t3Ade, ampAde], ...PRO_ORBS }, [{}]); + await screen.findByText("dev-1"); + expect(screen.queryByRole("region", { name: "Amp orbs" })).toBeNull(); +}); + +test("the offer is only in Amp mode and only while there is no provider", async () => { + picked("t3"); + show({ ...PRO_ORBS }, [{}]); + await screen.findByText("dev-1"); + expect(screen.queryByRole("region", { name: "Amp orbs" })).toBeNull(); + cleanup(); + picked("amp"); + show({ ades: [t3Ade, ampAde], ...PRO_ORBS }, [{}, PROVIDER]); + await screen.findByText("dev-1"); + expect(screen.queryByRole("region", { name: "Amp orbs" })).toBeNull(); +}); + +test("setting Amp orbs up lists its steps and costs, then runs orbs_set_up", async () => { + picked("amp"); + show({ ades: [t3Ade, ampAde], ...PRO_ORBS }, [{}]); + const card = await screen.findByRole("region", { name: "Amp orbs" }); + await userEvent.click(within(card).getByRole("button", { name: "Set up Amp orbs" })); + expect(screen.getByText("Amp orbs", { selector: ".top-title" })).toBeTruthy(); + const steps = screen.getByRole("list", { name: "Setup steps" }); + expect(within(steps).getAllByRole("listitem").map((li) => li.querySelector(".orbs-step-title")?.textContent)).toEqual([ + "Paid plan", + "Provider sandbox", + "Sign in to Amp", + "Add instabox to Amp", + "Build the orb image", + "Connect to Amp", + ]); + expect(screen.getByText(/runs all the time: about \$12 a month/)).toBeTruthy(); + expect(screen.getByText(/4 vCPU \/ 8 GB orb is \$0\.034 an hour/)).toBeTruthy(); + await userEvent.click(screen.getByRole("button", { name: "Set up Amp orbs" })); + expect(calls("orbs_set_up")).toHaveLength(1); +}); + +test("the Amp orbs page asks for a paid plan on Free", async () => { + picked("instabox"); + show({}, [{}]); + await screen.findByText("dev-1"); + await userEvent.click(screen.getByRole("button", { name: "Settings" })); + const row = screen.getByText("Run Amp threads on instabox").closest(".group-row") as HTMLElement; + expect(within(row).getByText("Needs a paid plan")).toBeTruthy(); + await userEvent.click(within(row).getByRole("button", { name: "Set up" })); + expect(screen.getByText("Amp orbs need a paid plan")).toBeTruthy(); + await userEvent.click(screen.getByRole("button", { name: "See plans" })); + expect(invoke).toHaveBeenCalledWith("open_url", { url: "https://instabox.sh/pricing" }); + expect(calls("orbs_set_up")).toHaveLength(0); +}); + +test("a provider not signed in to Amp yet offers the sign-in terminal", async () => { + picked("instabox"); + const status = { ...ORB_STATUS, signedIn: false, tokenSaved: false, image: { ...ORB_STATUS.image, status: "building" as const } }; + show({ ...PRO_ORBS, orbs: { ...PRO_ORBS.orbs, providerId: "p", status } }, [PROVIDER]); + await userEvent.click(await screen.findByRole("button", { name: "Status" })); + expect(calls("orbs_refresh").length).toBeGreaterThan(0); + await userEvent.click(screen.getByRole("button", { name: "Open sign-in terminal" })); + expect(calls("orbs_sign_in")).toHaveLength(1); + expect(screen.getByRole("button", { name: "Repair" })).toBeTruthy(); +}); + +test("a connected provider shows its orbs and removes only after a confirm", async () => { + picked("instabox"); + show({ ...PRO_ORBS, orbs: { ...PRO_ORBS.orbs, providerId: "p", status: ORB_STATUS } }, [ + PROVIDER, + ORB, + { ...ORB, id: "o2", name: "amp-t-81d07e00-0000-4000-8000-000000000002", state: "paused" }, + ]); + await userEvent.click(await screen.findByRole("button", { name: "Status" })); + expect(screen.getByText("Connected to Amp")).toBeTruthy(); + expect(screen.getByText("1 running · 1 paused")).toBeTruthy(); + expect(screen.getByText("Never · about $12 a month")).toBeTruthy(); + expect(screen.getByText("Renews by itself")).toBeTruthy(); + await userEvent.click(screen.getByRole("button", { name: "Open Amp" })); + expect(invoke).toHaveBeenCalledWith("open_url", { url: "https://ampcode.com" }); + await userEvent.click(screen.getByRole("button", { name: "Rebuild image" })); + expect(calls("orbs_rebuild_image")).toHaveLength(1); + await userEvent.click(screen.getByRole("button", { name: "Remove Amp orbs" })); + expect(calls("orbs_remove")).toHaveLength(0); + await userEvent.click(screen.getByRole("button", { name: "Confirm remove" })); + expect(calls("orbs_remove")).toHaveLength(1); +}); + +test("orb rows open their thread and offer no ADE, power or delete", async () => { + picked("amp"); + show({ ades: [t3Ade, ampAde], ...PRO_ORBS }, [PROVIDER, ORB]); + const orb = within(await screen.findByText(ORB.name!).then(() => rowOf(ORB.name!))); + expect(orb.getByText("Amp orb")).toBeTruthy(); + expect(orb.getByText("working on a thread")).toBeTruthy(); + expect(orb.queryByRole("button", { name: "Connect" })).toBeNull(); + expect(orb.queryByRole("button", { name: /^(Pause|Resume) / })).toBeNull(); + await userEvent.click(orb.getByRole("button", { name: "Open thread" })); + expect(invoke).toHaveBeenCalledWith("open_url", { url: "https://ampcode.com/threads/T-3f2a9c00-0000-4000-8000-000000000001" }); + const provider = within(rowOf("amp-orb-provider")); + expect(provider.getByText("Amp orbs provider")).toBeTruthy(); + expect(provider.queryByRole("button", { name: "Connect" })).toBeNull(); + + await openMenu(ORB.name!); + expect(menuItems()).toEqual(["Open thread in Amp", "Copy SSH command", "Open in Terminal"]); + await userEvent.keyboard("{Escape}"); + await openMenu("amp-orb-provider"); + expect(menuItems()).toEqual(["Amp orbs status", "Copy SSH command", "Open in Terminal"]); + await userEvent.keyboard("{Escape}"); + + await userEvent.click(screen.getByText(ORB.name!)); + expect(screen.getByText("Amp manages this sandbox")).toBeTruthy(); + expect(screen.getByText("Amp decides")).toBeTruthy(); + expect(screen.queryByRole("button", { name: /Delete sandbox|Install Amp/ })).toBeNull(); +}); diff --git a/src/App.tsx b/src/App.tsx index 980c74d..5aae99b 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,6 +1,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { adeSwitched, connectSandbox, createSandbox, deleteSandbox, getState, hidePopover, onState, openInAde, openRepo, setScreen, toErrorView } from "./api"; import AdePicker from "./AdePicker"; +import AmpOrbs, { OrbSandboxDetails } from "./AmpOrbs"; import type { Mode } from "./ades"; import { agentKey } from "./common"; import type { AgentCache, OnAgentStatus } from "./common"; @@ -28,6 +29,7 @@ type View = | { name: "list" } | { name: "new" } | { name: "settings" } + | { name: "orbs" } | { name: "details"; id: string } | { name: "repos"; id: string; from: "list" | "details" }; type Menu = { id: string; anchor: HTMLElement } | null; @@ -288,6 +290,8 @@ export default function App({ showHero = false }: { showHero?: boolean }) { ? "New sandbox" : current.name === "settings" ? "Settings" + : current.name === "orbs" + ? "Amp orbs" : current.name === "repos" ? `Choose a repo for ${sandbox?.name ?? ""}` : (sandbox?.name ?? ""); @@ -322,9 +326,13 @@ export default function App({ showHero = false }: { showHero?: boolean }) { } else if (current.name === "new") { body = ; } else if (current.name === "settings") { - body = ; + body = go({ name: "orbs" })} />; + } else if (current.name === "orbs") { + body = ; } else if (current.name === "repos" && sandbox) { body = pickRepo(sandbox.id, repo)} />; + } else if (sandbox?.role) { + body = go({ name: "orbs" })} />; } else if (sandbox) { body = (
go({ name: "new" })} onSettings={() => go({ name: "settings" })} + onOrbs={() => go({ name: "orbs" })} onOpen={open} onConnect={connect} onDetails={(id) => go({ name: "details", id })} @@ -391,6 +400,7 @@ export default function App({ showHero = false }: { showHero?: boolean }) { onConnect={connect} onCopied={() => setNotice(SSH_COPIED)} onDelete={remove} + onOrbs={() => go({ name: "orbs" })} onClose={closeMenu} /> )} diff --git a/src/SandboxList.tsx b/src/SandboxList.tsx index 0695f11..0143873 100644 --- a/src/SandboxList.tsx +++ b/src/SandboxList.tsx @@ -13,6 +13,7 @@ import pauseIcon from "./assets/machine-card/pause.svg"; import dotsIcon from "./assets/machine-card/dots.svg"; import runningIcon from "./assets/machine-card/status.svg"; import AdeLogo from "./AdeLogo"; +import { OrbsCard, RoleLine } from "./AmpOrbs"; import playIcon from "./assets/main-view/play.svg"; import unfold from "./assets/main-view/unfold.svg"; import NextSteps from "./NextSteps"; @@ -42,6 +43,8 @@ export type RowLine = /** Plain Instabox shows no ADE line; an ADE mode shows Open or Install on every row. */ export function rowLine(s: SandboxView, state: AppState, agents: AgentCache, mode: Mode): RowLine { if (state.progress && state.progress.machineId === s.id) return { kind: "progress" }; + // Amp runs the sandboxes of Amp orbs: no ADE line, update or agent sign-in. + if (s.role) return null; // Updates belong to the installed ADE, independently of the selected mode. if (s.updatePending && !s.desktopBehind) return { kind: "update" }; if (s.desktopBehind) return { kind: "desktopBehind" }; @@ -64,6 +67,8 @@ export interface ListActions { onChooseRepo: (id: string) => void; onMenu: (id: string, anchor: HTMLElement) => void; onAgentStatus: OnAgentStatus; + /** Opens the Amp orbs page. */ + onOrbs: () => void; } interface RowProps extends ListActions { @@ -75,7 +80,7 @@ interface RowProps extends ListActions { menuOpen: boolean; } -function Row({ s, state, run, mode, agents, menuOpen, onConnect, onDetails, onChooseRepo, onMenu, onAgentStatus }: RowProps) { +function Row({ s, state, run, mode, agents, menuOpen, onConnect, onDetails, onChooseRepo, onMenu, onAgentStatus, onOrbs }: RowProps) { const line = rowLine(s, state, agents, mode); const busy = BUSY.includes(s.state); const adeNeedsUpdate = s.updatePending || s.desktopBehind; @@ -104,7 +109,7 @@ function Row({ s, state, run, mode, agents, menuOpen, onConnect, onDetails, onCh
- {(s.state === "running" || isAsleep(s)) && ( + {!s.role && (s.state === "running" || isAsleep(s)) && ( @@ -120,7 +125,7 @@ function Row({ s, state, run, mode, agents, menuOpen, onConnect, onDetails, onCh
-
+ {s.role ? :
{s.ades.map((id) => )} @@ -144,7 +149,7 @@ function Row({ s, state, run, mode, agents, menuOpen, onConnect, onDetails, onCh Connect ) : null} -
+
} {line?.kind === "progress" && } @@ -288,12 +293,15 @@ export default function SandboxList(props: Props) { // Until the account is known, its sandboxes are too: nothing is said about none. state.login !== null && ) : ( + <> +
    {showPending && } {state.sandboxes.map((s) => ( ))}
+ )}
{mode !== "instabox" && missing && ( diff --git a/src/SandboxMenu.tsx b/src/SandboxMenu.tsx index 883c9cd..0cdf115 100644 --- a/src/SandboxMenu.tsx +++ b/src/SandboxMenu.tsx @@ -3,7 +3,8 @@ import type { KeyboardEvent, ReactNode } from "react"; import { openSsh, pairAgain, pause, reinstallT3, resize, resume, setAutoSleep, sshCommand } from "./api"; import { adeName, hasAde, pairs } from "./ades"; import type { Mode } from "./ades"; -import { BUSY, copyText, isAsleep, isFree } from "./common"; +import { threadUrl } from "./AmpOrbs"; +import { BUSY, copyText, isAsleep, isFree, openExternal } from "./common"; import type { Run } from "./common"; import { Check, ChevronDown, ChevronRight } from "./icons"; import type { AdeId, AppState, SandboxView } from "./types"; @@ -21,6 +22,8 @@ interface Props { onConnect: (id: string, ade: AdeId) => void; onCopied: () => void; onDelete: (s: SandboxView) => void; + /** Opens the Amp orbs page. */ + onOrbs: () => void; onClose: () => void; } @@ -37,7 +40,7 @@ function Item({ children, onClick, disabled, danger }: { children: ReactNode; on const Sep = () =>
; -export default function SandboxMenu({ s, state, run, mode, anchor, container, onOpen, onConnect, onCopied, onDelete, onClose }: Props) { +export default function SandboxMenu({ s, state, run, mode, anchor, container, onOpen, onConnect, onCopied, onDelete, onOrbs, onClose }: Props) { const ref = useRef(null); const hint = useId(); const [sub, setSub] = useState<"size" | "sleep" | null>(null); @@ -127,7 +130,9 @@ export default function SandboxMenu({ s, state, run, mode, anchor, container, on const free = isFree(s, state.tier); // Plain Instabox has no ADE actions. T3 pairs from this computer: Pair again and Reinstall // need that pairing; cmux has neither. - const ade = mode === "instabox" ? null : mode; + // Amp runs the sandboxes of Amp orbs: no ADE, power, size, auto sleep or delete here. + const ade = mode === "instabox" || s.role ? null : mode; + const thread = s.role === "ampOrb" ? threadUrl(s.name) : null; const has = !!ade && hasAde(s, ade); const paired = !!ade && pairs(ade) && has && s.connected; const copySsh = () => { @@ -173,10 +178,30 @@ export default function SandboxMenu({ s, state, run, mode, anchor, container, on )} {paired && act(() => pairAgain(s.id))}>Pair again} - {ade && } - {s.state === "running" && act(() => pause(s.id))}>Pause} - {isAsleep(s) && act(() => resume(s.id))}>Resume} - {subItem("size", "Resize", s.size)} + {s.role === "ampOrbProvider" && ( + { + close(false); + onOrbs(); + }} + > + Amp orbs status + + )} + {thread && ( + { + close(true); + openExternal(thread); + }} + > + Open thread in Amp + + )} + {(ade || s.role) && } + {!s.role && s.state === "running" && act(() => pause(s.id))}>Pause} + {!s.role && isAsleep(s) && act(() => resume(s.id))}>Resume} + {!s.role && subItem("size", "Resize", s.size)} {sub === "size" && (

@@ -200,7 +225,7 @@ export default function SandboxMenu({ s, state, run, mode, anchor, container, on })}

)} - {subItem("sleep", "Auto sleep", s.autoSleep.label)} + {!s.role && subItem("sleep", "Auto sleep", s.autoSleep.label)} {sub === "sleep" && (
{state.sleepChoices.map((c) => { @@ -223,11 +248,13 @@ export default function SandboxMenu({ s, state, run, mode, anchor, container, on Copy SSH command act(() => openSsh(s.id))}>Open in Terminal - + {!s.role && } {paired && !s.desktopBehind && act(() => reinstallT3(s.id))}>Reinstall T3} - (confirmDelete ? remove() : setConfirmDelete(true))}> - {confirmDelete ? "Confirm delete" : "Delete sandbox"} - + {!s.role && ( + (confirmDelete ? remove() : setConfirmDelete(true))}> + {confirmDelete ? "Confirm delete" : "Delete sandbox"} + + )}
); } diff --git a/src/Settings.tsx b/src/Settings.tsx index a4d013f..a217a5e 100644 --- a/src/Settings.tsx +++ b/src/Settings.tsx @@ -1,4 +1,5 @@ import { setStartAtLogin, signOut } from "./api"; +import { isConnected, orbsProvider } from "./AmpOrbs"; import { CheckAdesButton } from "./AdeCards"; import { AdeBadge, COMING_SOON, terminalApp } from "./ades"; import { cap, thisComputer } from "./common"; @@ -6,8 +7,16 @@ import type { Run } from "./common"; import type { AppState } from "./types"; import UpdatesSection from "./UpdatesSection"; +/** One line on Amp orbs in the selected workspace. */ +function orbsSummary(state: AppState): string { + const provider = orbsProvider(state); + if (!provider) return state.orbs.allowed ? "Not set up" : "Needs a paid plan"; + const status = state.orbs.providerId === provider.id ? state.orbs.status : null; + return isConnected(status) ? "Connected to Amp" : "Not connected to Amp yet"; +} + /** Settings. The organization is picked in the list's footer. */ -export default function Settings({ state, run }: { state: AppState; run: Run }) { +export default function Settings({ state, run, onOrbs }: { state: AppState; run: Run; onOrbs: () => void }) { const name = state.login ?? "Signed in"; const initials = name.trim().charAt(0).toUpperCase(); @@ -81,6 +90,21 @@ export default function Settings({ state, run }: { state: AppState; run: Run })
+
+

Amp orbs

+
+
+
+ Run Amp threads on instabox + {orbsSummary(state)} +
+ +
+
+
+ {state.update && } diff --git a/src/api.ts b/src/api.ts index d067dc9..1d748c0 100644 --- a/src/api.ts +++ b/src/api.ts @@ -58,6 +58,11 @@ export const resume = (id: string) => invoke("resume", { id }); export const deleteSandbox = (id: string) => invoke("delete", { id }); export const resize = (id: string, vcpus: number, memMiB: number) => invoke("resize", { id, vcpus, memMiB }); export const setAutoSleep = (id: string, seconds: number) => invoke("set_auto_sleep", { id, seconds }); +export const orbsSetUp = () => invoke("orbs_set_up"); +export const orbsRefresh = () => invoke("orbs_refresh"); +export const orbsSignIn = () => invoke("orbs_sign_in"); +export const orbsRebuildImage = () => invoke("orbs_rebuild_image"); +export const orbsRemove = () => invoke("orbs_remove"); /** Sets T3 up again at this computer's version: Reinstall and Update. */ export const reinstallT3 = (id: string) => invoke("reinstall_t3", { id, ade: "t3" }); export const agentSignIn = (id: string, agent: Agent) => invoke("agent_sign_in", { id, agent }); diff --git a/src/fixtures/state.json b/src/fixtures/state.json index db85f3d..1081bbc 100644 --- a/src/fixtures/state.json +++ b/src/fixtures/state.json @@ -217,6 +217,12 @@ "ade": "t3", "error": null }, + "orbs": { + "allowed": false, + "step": null, + "providerId": null, + "status": null + }, "error": { "kind": "cooldown", "message": "Cooling down, ready in about 12 min", diff --git a/src/preview.ts b/src/preview.ts index 4b098f0..216b543 100644 --- a/src/preview.ts +++ b/src/preview.ts @@ -1,7 +1,7 @@ import fixture from "./fixtures/state.json"; import type { Mode } from "./ades"; import { modeKey, tipKey } from "./mode"; -import type { AdeId, AdeView, AppState, ErrorView, GitHubRepo, GithubView, NextStepView, ProgressView, SandboxView } from "./types"; +import type { AdeId, AdeView, AppState, ErrorView, GitHubRepo, GithubView, NextStepView, OrbsView, ProgressView, ProviderStatus, SandboxView } from "./types"; const SIGNED_OUT: Omit = { status: "signedOut", login: null, code: null, url: null, copied: false, commitsAs: null, later: false }; const SAMPLE_CODE = "4F2A-91BC"; @@ -213,6 +213,93 @@ function connected(id: string, ade: AdeId) { if (ade === "paseo" || ade === "rex") showStep({ sandboxId: id, ade, alias, address: `ssh://${alias}`, seen: null, kind: null, repo: null }); } +// ---- Amp orbs: `?orbs=setup`, `signin` or `connected` on a paid plan, `free` on the Free plan ---- + +const ORBS_PROVIDER = "preview-amp-orb-provider"; +const ORBS_STATUS: ProviderStatus = { + version: 1, signedIn: false, tokenSaved: false, service: "activating", + image: { status: "building", snapshot: null, finishedAt: null, error: null }, + keyId: "wkey_preview", keyExpires: "2027-12-04T00:00:00Z", +}; +const ORBS_CONNECTED: ProviderStatus = { + ...ORBS_STATUS, signedIn: true, tokenSaved: true, service: "active", + image: { status: "ready", snapshot: "amp-orb-base-1796054441", finishedAt: new Date().toISOString(), error: null }, +}; + +function orbSandbox(id: string, name: string, sandboxState: SandboxView["state"], role: SandboxView["role"], size: string): SandboxView { + return { ...(fixture.sandboxes[2] as SandboxView), id, name, state: sandboxState, size, role, connected: false, ades: [], t3Version: null, + autoSleep: { seconds: 0, label: "Never" } }; +} + +function seededOrbs(s: AppState): AppState { + const asked = query?.get("orbs"); + if (!asked || asked === "free") return s; + const paid: AppState = { + ...s, tier: "pro", + sleepChoices: [...s.sleepChoices, { seconds: 0, label: "Never" }], + sizes: [{ vcpus: 2, memMiB: 4096, label: "2 vCPU / 4 GB" }, { vcpus: 4, memMiB: 8192, label: "4 vCPU / 8 GB" }, { vcpus: 8, memMiB: 16384, label: "8 vCPU / 16 GB" }], + orbs: { allowed: true, step: null, providerId: null, status: null }, + }; + if (asked === "setup") return paid; + const provider = orbSandbox(ORBS_PROVIDER, "amp-orb-provider", "running", "ampOrbProvider", "2 vCPU / 4 GB"); + const orbs = asked === "connected" + ? [ + orbSandbox("preview-orb-1", "amp-t-3f2a9c00-0000-4000-8000-000000000001", "running", "ampOrb", "4 vCPU / 8 GB"), + orbSandbox("preview-orb-2", "amp-t-81d07e00-0000-4000-8000-000000000002", "paused", "ampOrb", "4 vCPU / 8 GB"), + ] + : []; + return { + ...paid, + sandboxes: [provider, ...orbs, ...paid.sandboxes], + orbs: { ...paid.orbs, providerId: ORBS_PROVIDER, status: asked === "connected" ? ORBS_CONNECTED : ORBS_STATUS }, + }; +} + +function setOrbs(patch: Partial) { + state = { ...state, orbs: { ...state.orbs, ...patch } }; + emitPreview(); +} + +const orbsWait = (ms = 1500) => new Promise((r) => setTimeout(r, ms)); + +async function previewOrbsSetUp() { + const had = state.sandboxes.some((s) => s.role === "ampOrbProvider"); + setOrbs({ step: had ? "installing" : "creating" }); + await orbsWait(); + if (!had) { + state = { ...state, sandboxes: [orbSandbox(ORBS_PROVIDER, "amp-orb-provider", "running", "ampOrbProvider", "2 vCPU / 4 GB"), ...state.sandboxes] }; + setOrbs({ step: "installing" }); + await orbsWait(); + } + setOrbs({ step: null, providerId: ORBS_PROVIDER, status: state.orbs.status ?? ORBS_STATUS }); +} + +async function previewOrbsSignIn() { + await orbsWait(2500); + setOrbs({ status: { ...(state.orbs.status ?? ORBS_STATUS), signedIn: true, tokenSaved: true, service: "active" } }); + await orbsWait(2500); + setOrbs({ status: ORBS_CONNECTED }); +} + +async function previewOrbsRebuild() { + setOrbs({ status: { ...(state.orbs.status ?? ORBS_CONNECTED), image: { ...ORBS_STATUS.image } } }); + await orbsWait(4000); + setOrbs({ status: { ...(state.orbs.status ?? ORBS_CONNECTED), image: ORBS_CONNECTED.image } }); +} + +async function previewOrbsRemove() { + if (state.sandboxes.some((s) => s.role === "ampOrb")) { + throw { kind: "other", message: "Orb sandboxes are left. Delete their threads in Amp first, so Amp deletes their sandboxes too." }; + } + setOrbs({ step: "removing" }); + await orbsWait(); + state = { ...state, sandboxes: state.sandboxes.filter((s) => s.role !== "ampOrbProvider") }; + setOrbs({ step: null, providerId: null, status: null }); +} + +// After the constants above: the sample state needs them. +state = seededOrbs(state); + // ---- a fake create: as the API lists them, the new sandbox comes last ---- /** How long each step of the fake create takes. */ @@ -349,6 +436,11 @@ export async function invokePreview(command: string, args: Record { "t3Switch", "nextSteps", "github", + "orbs", "error", "startAtLogin", "update", diff --git a/src/types.ts b/src/types.ts index 8cc10bd..97730eb 100644 --- a/src/types.ts +++ b/src/types.ts @@ -245,6 +245,37 @@ export interface UpdateView { error: ErrorView | null; } +/** What a setup or a removal of Amp orbs is doing now. */ +export type OrbsStep = "creating" | "installing" | "removing"; + +/** What the Amp orbs provider sandbox said when the app last asked (`amp-orbs status`). */ +export interface ProviderStatus { + version: number; + /** Amp is signed in on the provider. */ + signedIn: boolean; + /** Amp's provider token is saved on the provider. */ + tokenSaved: boolean; + /** systemd's state of the provider service: "active" when it runs. */ + service: string; + image: { + status: "none" | "building" | "ready" | "failed"; + snapshot: string | null; + finishedAt: string | null; + error: string | null; + }; + keyId: string | null; + keyExpires: string | null; +} + +export interface OrbsView { + /** The workspace may run Amp orbs: a paid plan with always-on sandboxes. */ + allowed: boolean; + step: OrbsStep | null; + /** The provider sandbox status came from. */ + providerId: string | null; + status: ProviderStatus | null; +} + export interface AppState { signedIn: boolean; /** From launch until the back end has read the saved sign-in: signedIn is not known yet, so @@ -271,6 +302,8 @@ export interface AppState { nextSteps: NextStepView[]; /** GitHub on the sandboxes the list shows, for those the app checked or signs in. */ github: GithubView[]; + /** Amp orbs in the selected workspace. */ + orbs: OrbsView; error: ErrorView | null; startAtLogin: boolean; update: UpdateView | null; From e300f7abc53aa0789cb0582e3a9f25e02b17c294 Mon Sep 17 00:00:00 2001 From: CarmenDou <80885297+CarmenDou@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:21:29 -0500 Subject: [PATCH 05/23] Document Amp orbs, and renew the orbs key while the app runs The key renewed only while the Amp orbs page was open. The app now reads the provider's status when it lists the provider and twice a day, so the key renews in its last 30 days while InstaADE runs. Co-Authored-By: Claude Opus 5.5 --- DEVELOPMENT.md | 1 + README.md | 2 ++ docs/amp-orbs.md | 85 ++++++++++++++++++++++++++++++++++++++++++++++++ src/App.test.tsx | 12 +++++++ src/App.tsx | 17 ++++++++-- 5 files changed, 115 insertions(+), 2 deletions(-) create mode 100644 docs/amp-orbs.md diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 61197e1..8632c2f 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -13,6 +13,7 @@ Read this before you change the code, open a pull request, build a preview or cu - `clipboard.rs`: copies a secret the user pastes once (Paradev's SSH address) and clears it a minute later, and copies Paseo's and Rex's host address, which holds no secret and stays. - `old_app.rs`: finds a copy of the app from before it was InstaADE, and moves it to the Trash (see [The old app](#the-old-app)). - `agents.rs`: signing Claude Code or Codex in on a sandbox. `github.rs`: signing GitHub's CLI in on a sandbox and setting up git there (see [GitHub sign-in](docs/ades.md#github-sign-in)). `repos.rs`: the GitHub repos `gh` lists on a sandbox, the repo names InstaADE takes, and the check of a repo's folder there (see [Bring your repo](docs/ades.md#bring-your-repo)). `settings.rs`: the app's saved settings, `settings.json`, which keep Later on that sign-in and Done on Orca's and Paseo's next steps (see [Next steps](docs/ades.md#next-steps)). `tray.rs`: the menu bar popover. `login.rs`: start at login. + - `orbs.rs`: Amp orbs, which make the workspace an orb provider for Amp (see [docs/amp-orbs.md](docs/amp-orbs.md)): the provider sandbox, its instabox key, its install script and its status. `assets/amp-orbs/` holds the dispatch program `amp-orbs` that runs on the provider and its systemd units. The tests in `orbs.rs` run the program with a fake `instabox`, `amp` and `systemctl`. - `updater.rs`: checks for a new version of InstaADE and installs it when the user clicks Update in Settings (see [In-app updates](#in-app-updates)). - `src/` is the React UI. `api.ts` wraps the Rust commands and `types.ts` mirrors the Rust state. `mode.ts` keeps the ADE the user picked, and whether they saw the tip under the switcher. diff --git a/README.md b/README.md index 5348845..f52b668 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,7 @@ You need macOS or Windows (x64), an [instabox](https://instabox.sh) account, and - Copy the SSH command or open it in a terminal - Sign in to Claude Code or Codex on the sandbox - Sign in to GitHub on the sandbox, so git can clone and push your private repos +- Run each [Amp](https://ampcode.com) thread on its own sandbox as an Amp orb, set up in one click on a paid plan. See [docs/amp-orbs.md](docs/amp-orbs.md). - Starts at login, and updates itself from **Update** in Settings ## Supported ADEs @@ -79,6 +80,7 @@ Every **Open in** wakes the sandbox first. - Installs Amp on the sandbox and opens it in your terminal over SSH. - First time: press `y` when Amp asks to log in, open the link it shows on your computer, sign in and check the code. - Closing the terminal ends Amp on the sandbox. Its threads stay at ampcode.com. + - To run Amp threads without your computer, set up [Amp orbs](docs/amp-orbs.md). - **[Rex](docs/ades.md#rex-macos)** · macOS 15 or later, Apple silicon - Installs Rex's server on the sandbox, adds it as an SSH host, copies its address and starts Rex. - First time: in Rex, open **Settings** → **Remote Hosts** → **Add Remote Host…**, paste the address as the URL and click **Add**. diff --git a/docs/amp-orbs.md b/docs/amp-orbs.md new file mode 100644 index 0000000..d8ffc6f --- /dev/null +++ b/docs/amp-orbs.md @@ -0,0 +1,85 @@ +# Amp orbs on instabox + +An [Amp orb](https://ampcode.com) is a sandbox where an Amp thread runs without your computer. Amp starts it, pauses it and deletes it through an orb provider. InstaADE makes your instabox workspace an orb provider: each Amp thread then runs on its own instabox sandbox. + +InstaADE does this in one click. It needs no change to instabox or to Amp. + +## What you need + +- A paid instabox plan. The provider sandbox runs all the time, and the Free plan pauses every sandbox after 30 minutes. See [pricing](https://instabox.sh/pricing). +- An Amp account. +- To be an owner or admin of the workspace. Setup makes an instabox key for the provider, and only owners and admins can make keys. + +## Set it up + +1. In Amp mode, click **Set up Amp orbs** on the offer above the list. You can also go to **Settings** → **Amp orbs** → **Set up**. +2. Read the steps and the costs, then click **Set up Amp orbs**. +3. InstaADE makes the provider sandbox and installs the provider on it. A terminal then opens on the provider. +4. In the terminal, open the link Amp shows, sign in, and check the code. The terminal adds instabox to Amp as your default orb provider. You copy no token. +5. Wait for the orb image. The first build takes about 5 minutes. The page ticks each step as it finishes. +6. In Amp, pick **instabox** as the orb provider of a thread. + +The page checks the provider every 10 seconds until it is connected and its image is built. **Repair** runs the install again, for example after an error. **Check again** reads the status now. + +## What runs where + +| Where | What | +| --- | --- | +| Provider sandbox `amp-orb-provider` | The smallest size of your plan, auto sleep off. It runs `amp orb provider` as the systemd service `amp-orb-provider`, with `/usr/local/bin/amp-orbs` as its dispatch program. | +| One orb sandbox per thread `amp-t-` | 4 vCPU / 8 GB, or the largest size of your plan below that. An orb from a project's snapshot keeps that snapshot's size. Auto sleep is off: Amp pauses it. Amp runs on it as `user`. | +| Snapshots `amp-orb-base-