diff --git a/CHANGELOG.md b/CHANGELOG.md index 31e789b..7acd771 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,21 @@ To be published as the `go/v0.6.1` tag. - A Mac computer create refused with `computer_not_enabled` and `unlocks_with_card: true` raises `NOT_AVAILABLE_ON_PLATFORM` with `reason="upgrade_required"` on `open()` and `open_persistent()`, as in TypeScript 0.7.1. - The `User-Agent` reports 0.5.1. +## 0.8.0 (unreleased) + +- Session profiles: `open(target, { profile: "signed-in", sessionProfileProjectId: "" })` runs a project's named session profile from Git without reading local `.revyl/config.yaml` or sending a local script or Git branch. The project option requires a named profile and a valid UUID, otherwise `INVALID_ARGUMENT` is thrown. Web, iOS, Android and Mac are supported; Linux still refuses a profile name. Explicit checkout profiles and `profile: "none"` are unchanged. +- Implicit checkout defaults on web, iOS and Android send `instruction: "default"` only when the backend advertises `device_session_session_profile_picks`, so an untargeted app can start without the profile. A missing capability or failed read preserves the named request; explicit profiles and Mac computer defaults are unchanged. + +## Go 0.7.0 (unreleased) + +- Session profiles: `OpenOptions.SessionProfileProjectID` with `Profile` runs a project's named session profile from Git without a local checkout, as in TypeScript 0.8.0. Invalid nonempty UUIDs and empty or `"none"` profiles return `ErrInvalidArgument`; `Attach` and `CurrentComputer` reject the option. An empty project ID preserves checkout behavior. +- Implicit checkout defaults negotiate `instruction: "default"` on capable web, iOS and Android backends, preserving named requests on older backends and for Mac computers, as in TypeScript 0.8.0. + +## Python 0.6.0 (unreleased) + +- Session profiles: `open(..., profile="signed-in", session_profile_project_id="")` and `async_open` run a project's named session profile from Git without a local checkout, as in TypeScript 0.8.0. An invalid UUID or a missing, empty or `"none"` profile raises `INVALID_ARGUMENT`. Explicit checkout profiles and `profile="none"` are unchanged. +- Implicit checkout defaults negotiate `instruction="default"` on capable web, iOS and Android backends, preserving named requests on older backends and for Mac computers, as in TypeScript 0.8.0. + ## 0.7.0 (2026-11-23) - Web sessions: `cdp()` (TypeScript, Python, `AsyncSession`) and `CDP(ctx)` (Go) return a single-use Chrome DevTools Protocol endpoint, `{ url, expiresAt }` / `CDPEndpoint(url, expires_at)` / `CDPEndpoint{URL, ExpiresAt}`, valid for 60 seconds, so Playwright (`connectOverCDP`), Puppeteer or chromedp can attach to the session's browser while `instruction()` and `validation()` keep working. It posts `device-proxy/{run}/cdp`. iOS, Android and computers throw `NOT_AVAILABLE_ON_PLATFORM` before any request, a closed session `SESSION_ENDED`, and a backend without the route `NOT_AVAILABLE_ON_PLATFORM`. The endpoint's url is left out of `console.log`, `repr()` and `fmt` output. The API page and the Python and Go READMEs list the rules (one connection at a time, the session's own page, `browser.close()` only disconnects, http(s) navigation only, no downloads, a fixed window size, a 24 MB reply limit), with runnable Playwright and chromedp examples in `examples/web-cdp`, `python/examples/cdp_playwright.py` and `go/examples/cdp`. diff --git a/go/README.md b/go/README.md index 291dd71..40d1b57 100644 --- a/go/README.md +++ b/go/README.md @@ -153,6 +153,7 @@ Run with `go test -v -timeout 6m`. `t.Fatal` runs deferred cleanup. The URL and - `Target.StartTimeout` bounds startup (default 10 minutes); on web/mobile, `IdleTimeoutSeconds` sets the session's idle timeout (default 600 seconds). All methods also honor the caller's context. - `Open` takes at most one `OpenOptions` value, plus `WithModel`, `WithCustomModel` or `WithAgent` to run steps on your own model; `Instruction` and `Validation` take the same options for one step. `OpenOptions{StepTimeout: 3*time.Minute}` changes the default step timeout. Per-call `StepOptions{Timeout: time.Minute}` and `ValidationOptions{Timeout: time.Minute, Soft: true}` override it. Run one step at a time per session. - `OpenOptions{Profile: "signed-in"}` runs a session profile from your project's `.revyl/config.yaml` before `Open` returns; `Profile: "none"` runs no profile. Left empty, the project's `session.default_profile` runs when it sets one. Web, iOS, Android and Mac computers. See [Session profiles](#session-profiles). +- `OpenOptions.SessionProfileProjectID`: a Revyl project UUID to read the named session profile from Git instead of your checkout. Requires `Profile` to name a session profile, not `"none"`. Verify reads no local `.revyl/config.yaml` and sends no local script or Git branch. An empty project ID keeps checkout behavior. - Redirects are rejected, not followed with credentials. - `OpenOptions{Log: func(line string) { ... }}` opts into progress lines: `: starting session ` as soon as the session ID exists, before the browser or device is ready, then `ready`, on web, iOS, Android and hosted sessions; computer lifecycle; evidence-gap messages; mobile best-effort first-screen debug notes; and the turns of steps run on your own model. The default is quiet for all targets, so pass `Log: func(line string) { log.Println(line) }` to see the session link while a slow start runs. Keep that callback concurrency-safe if operations run concurrently. A confirmed execution result remains usable when its report evidence is pending or failed; the callback identifies that gap without logging private output or recording URLs. @@ -175,14 +176,29 @@ bare, err := verify.Open(ctx, verify.Target{Platform: verify.Web, AppID: "…", | `Profile` | What Verify sends | | --- | --- | | `"signed-in"` | That profile, with the project and the script from this checkout. | -| `""` (left out) | The project's `session.default_profile`, the same way, when `.revyl/config.yaml` sets one. Otherwise nothing, so the start request is the same as before profiles existed. | +| `""` (left out) | The checkout's `session.default_profile` when set. On web, iOS and Android, a capable backend skips it if the project doesn't target the launched app. Otherwise nothing is sent. | | `"none"` | No profile, not even the default: Verify sends no profile fields, so the start request is the same as before profiles existed. Needs no `.revyl/config.yaml`. | -Profiles work on web, iOS, Android and Mac computers. On a Linux computer, a profile name returns `ErrNotAvailableOnPlatform` before anything is sent, and no default runs; `"none"` is accepted. Hosted sessions (`computer.Open`), `Attach` and `CurrentComputer` never run a profile: `computer.Open` takes no options, and `Attach` and `CurrentComputer` return `ErrInvalidArgument` when `Profile` is set. +Profiles work on web, iOS, Android and Mac computers. On a Linux computer, a profile name returns `ErrNotAvailableOnPlatform` before anything is sent, and no default runs; `"none"` is accepted without a project option. Hosted sessions (`computer.Open`), `Attach` and `CurrentComputer` never run a profile: `computer.Open` takes no options, and `Attach` and `CurrentComputer` return `ErrInvalidArgument` when `Profile` or `SessionProfileProjectID` is set. + +For an implicit checkout default on web, iOS or Android, Verify reads `GET /api/v1/backend-capabilities?contract=session_profile_starts`. If `capabilities` includes `device_session_session_profile_picks`, it sends `instruction: "default"` with the default's name and the same checkout files and source. Revyl runs it when the project targets the launched app, or when no registered app launches; otherwise the session starts without a profile. A missing capability or a failed read keeps today's `instruction: "named"` request. Explicit profiles and Mac computer defaults always use `named` and make no capability request. + +### Without a checkout + +Pass `SessionProfileProjectID` with a named `Profile` to use the project's session profile from Git, without any local `.revyl/config.yaml`: + +```go +s, err := verify.Open(ctx, verify.Target{Platform: verify.Mac}, verify.OpenOptions{ + Profile: "signed-in", + SessionProfileProjectID: "0b9e6f3a-1c2d-4e5f-8a9b-0c1d2e3f4a5b", +}) +``` + +Verify sends `session_profile` with `instruction: "named"` and the profile name, and `session_profile_source` with only `project_id`. It sends no `session_profile_files` or `git_branch_name`; Revyl reads the project's default branch in Git. A local config, even if present, is ignored. An invalid nonempty project UUID or an empty or `"none"` profile returns `ErrInvalidArgument` before any request. Refusals, repository retries and waiting for the profile follow the same rules as checkout starts; an explicit profile is never silently skipped on an older backend. ### Where Verify reads the profile -Verify reads `.revyl/config.yaml` in the working directory (`os.Getwd()`) or the nearest folder above it that has one: the file `revyl init` writes in your app's checkout. In `go test`, the working directory is the package's folder, so the file is found when it sits in that folder or above it. Verify needs `project.id` and the profile under `session.profiles`, and reads nothing else from the file: +Without `SessionProfileProjectID`, Verify reads `.revyl/config.yaml` in the working directory (`os.Getwd()`) or the nearest folder above it that has one: the file `revyl init` writes in your app's checkout. In `go test`, the working directory is the package's folder, so the file is found when it sits in that folder or above it. Verify needs `project.id` and the profile under `session.profiles`, and reads nothing else from the file: ```yaml project: @@ -228,6 +244,8 @@ Neither errors nor logs contain the script's content or output. Check the code w | `script_unavailable` | The script isn't in this checkout or in Git, or the Library Script is missing | Commit the script or add it to `.revyl/scripts`, or create the Library Script | | `output_invalid` | A file the script wrote broke a rule; `FailureReason` names the file and the line | Fix what the script writes there | | `runner_failed` | Something failed on Revyl's side | Open the session again | +| `script_execution_unknown` | The run ended after Revyl let the script start because its runner was lost or the session stopped, timed out, or was cancelled, so the script may have run | Check the session before retrying | +| `cancelled_before_script_execution` | The session stopped, timed out, or was cancelled before the script started | Retry the profile when the session can remain active long enough to run it | ## Which call works where diff --git a/go/errors.go b/go/errors.go index e8a60df..d342270 100644 --- a/go/errors.go +++ b/go/errors.go @@ -12,6 +12,20 @@ type Code string type RefusalReason string +// SessionProfileOutcome describes how a session profile run ended. +type SessionProfileOutcome string + +const ( + SessionProfileSucceeded SessionProfileOutcome = "succeeded" + SessionProfileScriptFailed SessionProfileOutcome = "script_failed" + SessionProfileScriptTimedOut SessionProfileOutcome = "script_timed_out" + SessionProfileScriptUnavailable SessionProfileOutcome = "script_unavailable" + SessionProfileOutputInvalid SessionProfileOutcome = "output_invalid" + SessionProfileRunnerFailed SessionProfileOutcome = "runner_failed" + SessionProfileScriptExecutionUnknown SessionProfileOutcome = "script_execution_unknown" + SessionProfileCancelledBeforeScriptExecution SessionProfileOutcome = "cancelled_before_script_execution" +) + const ( ReasonWebRuntimeUnavailable RefusalReason = "web_runtime_unavailable" ReasonWebRuntimeNotConfigured RefusalReason = "web_runtime_not_configured" @@ -86,8 +100,8 @@ type Error struct { Message string Cause error ExecResult *ExecResult - // Outcome is set on ErrSessionProfileFailed: how the profile's run ended, such as "script_failed". - Outcome string + // Outcome is set on ErrSessionProfileFailed: how the profile's run ended. + Outcome SessionProfileOutcome // FailureReason is set on ErrSessionProfileFailed: Revyl's reason, which never holds a secret or the script's output. FailureReason string diff --git a/go/hosted.go b/go/hosted.go index 8fba0dc..81208fa 100644 --- a/go/hosted.go +++ b/go/hosted.go @@ -80,6 +80,9 @@ func CurrentComputer(ctx context.Context, options ...OpenOptions) (*Session, err func rejectProfile(options []OpenOptions) error { for _, option := range options { + if option.SessionProfileProjectID != "" { + return failure(ErrInvalidArgument, "SessionProfileProjectID runs only when Open starts a new web, iOS, Android or Mac session; Attach and CurrentComputer can't run one. Leave SessionProfileProjectID empty.") + } if option.Profile != "" { return failure(ErrInvalidArgument, "Profile runs only when Open starts a new web, iOS, Android or Mac session; Attach and CurrentComputer can't run one. Leave Profile empty.") } diff --git a/go/session.go b/go/session.go index a04e0c2..efe2771 100644 --- a/go/session.go +++ b/go/session.go @@ -25,10 +25,12 @@ type OpenOptions struct { StepTimeout time.Duration Log func(string) StopOnClose *bool - // Profile names a session profile from session.profiles in .revyl/config.yaml, such as "signed-in", that Revyl runs before + // Profile names a session profile from session.profiles in .revyl/config.yaml locally or in SessionProfileProjectID's Git + // repository, such as "signed-in", that Revyl runs before // Open returns, or "none" for no profile. Left empty, the project's session.default_profile runs when it sets one. Open reads - // .revyl/config.yaml from the working directory upward. Web, iOS, Android and Mac only. - Profile string + // .revyl/config.yaml from the working directory upward unless SessionProfileProjectID is set. Web, iOS, Android and Mac only. + Profile string + SessionProfileProjectID string } // OpenOption configures Open: an OpenOptions value, or an Option from WithModel, WithCustomModel or WithAgent. @@ -136,7 +138,7 @@ func Open(ctx context.Context, target Target, options ...OpenOption) (*Session, return nil, err } cwd, _ := os.Getwd() - profile, err := planSessionProfile(opt.Profile, target.Platform, cwd) + profile, err := planSessionProfile(opt.Profile, target.Platform, cwd, opt.SessionProfileProjectID) if err != nil { return nil, err } @@ -147,6 +149,9 @@ func Open(ctx context.Context, target Target, options ...OpenOption) (*Session, if err != nil { return nil, err } + if profile != nil && profile.implicit && target.Platform != Mac && supportsSessionProfileDefaults(ctx, c) { + profile.usesDefaultInstruction = true + } s, err := openStart(ctx, c, viewer, target, opt, agent, profile) if err == nil || profile == nil || !profile.implicit || !isLegacyProfileRefusal(err) { return s, err @@ -453,6 +458,9 @@ func (s *Session) profileDone(profile *reportedProfile, active bool) (bool, erro return false, nil } if profile == nil { + if plan.usesDefaultInstruction { + return true, nil + } return false, profileNotReportedError(s.platform, s.viewer) } return profile.status == "succeeded", nil diff --git a/go/session_profile.go b/go/session_profile.go index 25b28af..a434705 100644 --- a/go/session_profile.go +++ b/go/session_profile.go @@ -67,20 +67,37 @@ type profileFiles struct { // sessionProfilePlan is what Open sends for a session profile, and the name it waits on. implicit marks the project's default, // which the caller didn't ask for. type sessionProfilePlan struct { - name string - implicit bool - configPath string - source *profileSource - files *profileFiles + name string + implicit bool + configPath string + usesDefaultInstruction bool + source *profileSource + files *profileFiles } func (p *sessionProfilePlan) addTo(request map[string]any) { if p == nil { return } - request["session_profile"] = profileInstruction{Instruction: "named", Name: p.name} + instruction := "named" + if p.usesDefaultInstruction { + instruction = "default" + } + request["session_profile"] = profileInstruction{Instruction: instruction, Name: p.name} request["session_profile_source"] = p.source - request["session_profile_files"] = p.files + if p.files != nil { + request["session_profile_files"] = p.files + } +} + +func supportsSessionProfileDefaults(ctx context.Context, c *client) bool { + var response struct { + Capabilities []string `json:"capabilities"` + } + if err := c.json(ctx, "GET", "/api/v1/backend-capabilities?contract=session_profile_starts", nil, false, 30*time.Second, &response); err != nil { + return false + } + return slices.Contains(response.Capabilities, "device_session_session_profile_picks") } // reportedProfile is the session_profile object a start response or session report carries. @@ -93,8 +110,16 @@ type reportedProfile struct { } // planSessionProfile plans the session profile Open sends: an explicit name, or the project's session.default_profile when -// profile is empty. Nil when nothing is sent, which is always the case for profile "none". Reads .revyl/config.yaml at or above cwd. -func planSessionProfile(profile string, platform Platform, cwd string) (*sessionProfilePlan, error) { +// profile is empty. A project ID requires an explicit name and bypasses local config. Otherwise reads .revyl/config.yaml at or above cwd. +func planSessionProfile(profile string, platform Platform, cwd string, sessionProfileProjectID string) (*sessionProfilePlan, error) { + if sessionProfileProjectID != "" { + if !uuidPattern.MatchString(sessionProfileProjectID) { + return nil, failure(ErrInvalidArgument, "open(): SessionProfileProjectID must be a Revyl project UUID.") + } + if profile == profileNone || !profileNamePattern.MatchString(profile) { + return nil, failure(ErrInvalidArgument, "open(): SessionProfileProjectID requires Profile to name a session profile (1-64 lowercase letters, digits or hyphens), not 'none'.") + } + } if profile != "" && profile != profileNone && !profileNamePattern.MatchString(profile) { return nil, failure(ErrInvalidArgument, "open(): profile must be a session profile name from session.profiles in .revyl/config.yaml (1-64 lowercase letters, digits or hyphens), or 'none'.") } @@ -107,6 +132,9 @@ func planSessionProfile(profile string, platform Platform, cwd string) (*session } return nil, failure(ErrNotAvailableOnPlatform, fmt.Sprintf("open(): session profiles run on web, iOS, Android and Mac sessions, not %s. Leave out profile.", platform)) } + if sessionProfileProjectID != "" { + return &sessionProfilePlan{name: profile, source: &profileSource{ProjectID: sessionProfileProjectID}}, nil + } if absolute, err := filepath.Abs(cwd); err == nil { cwd = absolute } @@ -233,7 +261,7 @@ func readProfileConfig(configPath string) (project, session map[string]any, err func checkoutFiles(name, script string, requiresCheckout bool, projectRoot, configPath string) (*profileFiles, error) { files := &profileFiles{Script: script, RequiresRepositoryCheckout: requiresCheckout} unavailable := func(reason string) error { - return &Error{Code: ErrSessionProfileFailed, Message: fmt.Sprintf("session profile %q: %s. Fix session.profiles.%s.script in %s, or pass %s.", name, reason, name, configPath, profileNoneHint), Outcome: "script_unavailable", FailureReason: reason} + return &Error{Code: ErrSessionProfileFailed, Message: fmt.Sprintf("session profile %q: %s. Fix session.profiles.%s.script in %s, or pass %s.", name, reason, name, configPath, profileNoneHint), Outcome: SessionProfileScriptUnavailable, FailureReason: reason} } var filePath, relativePath string if strings.Contains(script, "/") { @@ -693,11 +721,13 @@ func missingBranchNotice(profile *reportedProfile, plan *sessionProfilePlan) str } var profileOutcomeFixes = map[string]string{ - "script_failed": "Its script exited with an error. Run the script yourself from the project root to see its output; Revyl doesn't show the output because setup scripts often print secrets.", - "script_timed_out": "Its script didn't finish within Revyl's 300-second limit. Make it finish sooner.", - "script_unavailable": "Revyl could not find its script: commit it, or check session.profiles in .revyl/config.yaml. A script name with no .revyl/scripts file must be a Library Script in your Revyl organization.", - "output_invalid": "An output file the script wrote broke a rule, as the reason says. Fix what the script writes there.", - "runner_failed": "It failed on Revyl's side. Open the session again.", + "script_failed": "Its script exited with an error. Run the script yourself from the project root to see its output; Revyl doesn't show the output because setup scripts often print secrets.", + "script_timed_out": "Its script didn't finish within Revyl's 300-second limit. Make it finish sooner.", + "script_unavailable": "Revyl could not find its script: commit it, or check session.profiles in .revyl/config.yaml. A script name with no .revyl/scripts file must be a Library Script in your Revyl organization.", + "output_invalid": "An output file the script wrote broke a rule, as the reason says. Fix what the script writes there.", + "runner_failed": "It failed on Revyl's side. Open the session again.", + "script_execution_unknown": "The runner or session stopped after the script may have started, so the script may have run. Check the session before retrying.", + "cancelled_before_script_execution": "The session stopped before the script started. Retry the profile when the session can remain active long enough to run it.", } // profileFailedError is SESSION_PROFILE_FAILED for a profile Revyl reported as failed. Revyl stops the session itself. @@ -718,7 +748,7 @@ func profileFailedError(profile *reportedProfile, plan *sessionProfilePlan, view if !known { fix = "Check the session link for what happened." } - return &Error{Code: ErrSessionProfileFailed, Message: fmt.Sprintf("Session profile %q failed (%s)%s %s Revyl stops the session. See %s", name, outcome, reason, fix, viewer), Outcome: profile.outcome, FailureReason: profile.failureReason} + return &Error{Code: ErrSessionProfileFailed, Message: fmt.Sprintf("Session profile %q failed (%s)%s %s Revyl stops the session. See %s", name, outcome, reason, fix, viewer), Outcome: SessionProfileOutcome(profile.outcome), FailureReason: profile.failureReason} } // profileNotReportedError is NOT_AVAILABLE_ON_PLATFORM for a session that became active without reporting the profile Verify sent. @@ -738,6 +768,9 @@ var profileRefusals = map[string]struct { fix func(*sessionProfilePlan) string }{ "session_profile_undefined": {ErrConfigInvalid, func(plan *sessionProfilePlan) string { + if plan.configPath == "" { + return "Check that the project's .revyl/config.yaml in Git defines the session profile and that SessionProfileProjectID names that project." + } return "Check that session.profiles in " + profileConfigPath(plan) + " defines it and that project.id names the project that holds it." }}, "session_profile_source_required": {ErrInvalidArgument, func(*sessionProfilePlan) string { @@ -753,6 +786,9 @@ var profileRefusals = map[string]struct { return "Connect the repository's GitHub or GitLab app to the project in Revyl, then open the session again." }}, "project_not_found": {ErrConfigInvalid, func(plan *sessionProfilePlan) string { + if plan.configPath == "" { + return "SessionProfileProjectID isn't a project in this API key's organization. Use a key from that organization, or fix SessionProfileProjectID." + } return "project.id in " + profileConfigPath(plan) + " isn't a project in this API key's organization. Use a key from that organization, or fix project.id." }}, "repository_unavailable": {ErrAPI, func(*sessionProfilePlan) string { @@ -790,7 +826,7 @@ func profileRefusalError(r response, plan *sessionProfilePlan, platform Platform } failed := &Error{Code: refusal.code, Reason: RefusalReason(code), HTTPStatus: r.status, Message: fmt.Sprintf("Revyl refused %s (%s)%s %s", subject, code, detail, refusal.fix(plan))} if code == "session_profile_script_unavailable" { - failed.Outcome, failed.FailureReason = "script_unavailable", said + failed.Outcome, failed.FailureReason = SessionProfileScriptUnavailable, said } return failed } diff --git a/packages/verify/docs/api.md b/packages/verify/docs/api.md index 81e4847..303baa3 100644 --- a/packages/verify/docs/api.md +++ b/packages/verify/docs/api.md @@ -22,6 +22,7 @@ const mac = await open({ platform: 'mac' }); // computer, - `options.model`: runs every instruction and validation on your own model instead of Revyl's agent; see [Your own model](#your-own-model). Browsers and devices only; computers throw `NOT_AVAILABLE_ON_PLATFORM`. - `options.agent`: the same with a custom agent; see [Custom agents](#custom-agents). Pass `model` or `agent`, not both. - `options.profile`: a session profile from your project's `.revyl/config.yaml`, such as `'signed-in'`, that Revyl runs before `open()` returns, or `'none'` for no profile. Left out, the project's `session.default_profile` runs when it sets one. Web, iOS, Android and Mac computers. See [Session profiles](#session-profiles). +- `options.sessionProfileProjectId`: a Revyl project UUID to read the named session profile from Git instead of your checkout. Requires `profile` to name a session profile, not `'none'`. Verify reads no local `.revyl/config.yaml` and sends no local script or Git branch. `open` needs credentials: `REVYL_API_KEY` or a Revyl CLI login. It throws `AUTH_MISSING` without them, `CONFIG_NOT_FOUND` or `CONFIG_INVALID` for config problems, and `SESSION_START_FAILED` or `TIMEOUT` when the browser or device does not start. @@ -40,14 +41,29 @@ const bare = await open('web', { profile: 'none' }); | `profile` | What Verify sends | | --- | --- | | `'signed-in'` | That profile, with the project and the script from this checkout. | -| left out | The project's `session.default_profile`, the same way, when `.revyl/config.yaml` sets one. Otherwise nothing, so the start request is the same as before profiles existed. | +| left out | The checkout's `session.default_profile` when set. On web, iOS and Android, a capable backend skips it if the project doesn't target the launched app. Otherwise nothing is sent. | | `'none'` | No profile, not even the default: Verify sends no profile fields, so the start request is the same as before profiles existed. Needs no `.revyl/config.yaml`. | -Profiles work on web, iOS, Android and Mac computers. On a Linux computer, a profile name throws `NOT_AVAILABLE_ON_PLATFORM` before anything is sent, and no default runs; `'none'` is accepted. Hosted sessions (`computer.open()`), `attach()` and `currentComputer()` never run a profile: their options have no `profile`, so TypeScript rejects one. +Profiles work on web, iOS, Android and Mac computers. On a Linux computer, a profile name throws `NOT_AVAILABLE_ON_PLATFORM` before anything is sent, and no default runs; `'none'` is accepted without a project option. Hosted sessions (`computer.open()`), `attach()` and `currentComputer()` never run a profile: their options have no `profile` or `sessionProfileProjectId`, so TypeScript rejects either. + +For an implicit checkout default on web, iOS or Android, Verify reads `GET /api/v1/backend-capabilities?contract=session_profile_starts`. If `capabilities` includes `device_session_session_profile_picks`, it sends `instruction: 'default'` with the default's name and the same checkout files and source. Revyl runs it when the project targets the launched app, or when no registered app launches; otherwise the session starts without a profile. A missing capability or a failed read keeps today's `instruction: 'named'` request. Explicit profiles and Mac computer defaults always use `named` and make no capability request. + +### Without a checkout + +Pass `sessionProfileProjectId` with a named `profile` to use the project's session profile from Git, without any local `.revyl/config.yaml`: + +```ts +const session = await open({ platform: 'mac' }, { + profile: 'signed-in', + sessionProfileProjectId: '0b9e6f3a-1c2d-4e5f-8a9b-0c1d2e3f4a5b', +}); +``` + +Verify sends `session_profile: { instruction: 'named', name: 'signed-in' }` and `session_profile_source: { project_id: '…' }`, with no `session_profile_files` or `git_branch_name`. Revyl reads the project's default branch in Git. A local config, even if present, is ignored. An invalid project UUID or a missing, empty or `'none'` profile throws `INVALID_ARGUMENT` before any request. Refusals, repository retries and waiting for the profile follow the same rules as checkout starts; an explicit profile is never silently skipped on an older backend. ### Where Verify reads the profile -Verify reads `.revyl/config.yaml` in the current folder (`process.cwd()`) or the nearest folder above it that has one: the file `revyl init` writes in your app's checkout. It needs `project.id` and the profile under `session.profiles`, and reads nothing else from the file: +Without `sessionProfileProjectId`, Verify reads `.revyl/config.yaml` in the current folder (`process.cwd()`) or the nearest folder above it that has one: the file `revyl init` writes in your app's checkout. It needs `project.id` and the profile under `session.profiles`, and reads nothing else from the file: ```yaml project: @@ -93,6 +109,8 @@ Neither errors nor logs contain the script's content or output. A refusal keeps | `script_unavailable` | The script isn't in this checkout or in Git, or the Library Script is missing | Commit the script or add it to `.revyl/scripts`, or create the Library Script | | `output_invalid` | A file the script wrote broke a rule; `failureReason` names the file and the line | Fix what the script writes there | | `runner_failed` | Something failed on Revyl's side | Open the session again | +| `script_execution_unknown` | The run ended after Revyl let the script start because its runner was lost or the session stopped, timed out, or was cancelled, so the script may have run | Check the session before retrying | +| `cancelled_before_script_execution` | The session stopped, timed out, or was cancelled before the script started | Retry the profile when the session can remain active long enough to run it | ## Inside a revyl-macos GitHub Actions job diff --git a/packages/verify/docs/errors.md b/packages/verify/docs/errors.md index 901aab9..b5f82ea 100644 --- a/packages/verify/docs/errors.md +++ b/packages/verify/docs/errors.md @@ -52,7 +52,7 @@ try { | `EDGE_BLOCKED` | An HTTP 403 has a `text/html` content type and nonempty `cf-ray`, without a valid JSON body | Check network access or contact support; Verify does not retry the request | | `API_ERROR` | Revyl returned an unexpected response | Try again; after an exact action, check the session first, since the action may have run. If it persists, report it with the session link | | `SESSION_START_FAILED` | The browser, device, or computer did not start, or the app an iOS or Android target names by bundle id could not be launched (the message names the bundle id and has the session link) | Computer `no_host` reports the 120-second unclaimed-start context; `device_limit` reports queued-work/concurrency context. Inspect the session and cleanup before starting again. | -| `SESSION_PROFILE_FAILED` | A session profile failed: Verify couldn't send its script, Revyl couldn't find it, or it ran and failed. `error.outcome` is `script_failed`, `script_timed_out`, `script_unavailable`, `output_invalid` or `runner_failed`, and `error.failureReason` is Revyl's reason | Follow the message for the outcome; see [Session profiles](api.md#session-profile-errors). Revyl stops the session itself | +| `SESSION_PROFILE_FAILED` | A session profile failed: Verify couldn't send its script, Revyl couldn't find it, or it ran and failed. `error.outcome` is `script_failed`, `script_timed_out`, `script_unavailable`, `output_invalid`, `runner_failed`, `script_execution_unknown` or `cancelled_before_script_execution`, and `error.failureReason` is Revyl's reason | Follow the message for the outcome; see [Session profiles](api.md#session-profile-errors). Revyl stops the session itself | | `SESSION_ENDED` | The session was closed, stopped, or expired, or Revyl answered 404 for the session itself | Close explicitly; computer expiry does not prove release | | `SESSION_BUSY` | A step conflict, computer operation limit, someone controlling a computer's screen in the Revyl viewer, or `recording()` on a computer you haven't closed | Inspect the state before another call; a terminal computer alone does not prove release | | `COMPUTER_LIMIT` | Computer admission was refused due to queued work (including iOS) or the concurrency limit | Wait for capacity; Verify does not retry or stop a definitely refused start | diff --git a/packages/verify/docs/llms.txt b/packages/verify/docs/llms.txt index 3e67f12..14b10b2 100644 --- a/packages/verify/docs/llms.txt +++ b/packages/verify/docs/llms.txt @@ -7,7 +7,7 @@ Mac computers are available to organizations on a current paid Revyl plan. See computers.md#availability-and-errors. - [Getting started](getting-started.md): install, authenticate, init, run a script -- [API](api.md): open() and session profiles (Revyl runs a profile from .revyl/config.yaml before open() returns), attach(), hosted children, navigate(), cdp() for Playwright and Puppeteer on web, report(), agent steps, screenshot(), exec(), file/process methods, close() +- [API](api.md): open() and session profiles (Revyl runs a profile from .revyl/config.yaml before open() returns; profile plus sessionProfileProjectId reads it from the project's default branch in Git without a local config, script or branch; the project ID must be a UUID and profile must be a name, not empty or 'none'), attach(), hosted children, navigate(), cdp() for Playwright and Puppeteer on web, report(), agent steps, screenshot(), exec(), file/process methods, close() - [Configuration](configuration.md): verify.config.ts targets, environment variables, the init and whoami commands - [Web](web.md): Revyl web sessions, URLs and builds, sign-in, steps, and exact actions - [Mobile](mobile.md): iOS and Android devices, installing apps, and exact actions @@ -18,6 +18,10 @@ Mac computers are available to organizations on a current paid Revyl plan. See c - [Errors](errors.md): every error code and what to do about it - [For coding agents](agents.md): the workflow and rules for agents using Verify, and the coordinate rule for exact actions +## Session profiles + +For an implicit checkout session.default_profile on web, iOS or Android, Verify checks GET /api/v1/backend-capabilities?contract=session_profile_starts. The device_session_session_profile_picks capability switches the request from named to default with the same name, checkout files and source, so Revyl can skip defaults for untargeted apps. A missing capability or failed read preserves named. Explicit profiles and Mac computer defaults always send named without this read. + ## Exact actions and coordinates Prefer a description, such as `tap({ target: 'Sign in button' })`: Revyl finds the element on the current screen, and you never handle coordinates. Otherwise a point is `{ x, y }` in screenshot pixels on every platform: whole numbers from the top-left corner of the image `screenshot()` returns. So a position you read off a screenshot goes to `tap()`, `type()`, `swipe()` and every other exact action unchanged. `screenSize()` returns the screenshot's width and height, and `locate()` and the points `tap()`, `doubleTap()`, `longPress()` and `type()` return use the same pixels. A point outside the screenshot is refused with `INVALID_ARGUMENT` before any action is sent, and the message names the valid range. On iOS, Verify converts the pixels to the screen's points for you. On Web they equal CSS pixels at the default device scale factor of 1, and you still pass screenshot pixels at any other. This holds from TypeScript 0.4.1, Python 0.2.1 and Go v0.3.1; earlier versions took iOS points. On a Mac computer a point is in screenshot pixels too, and `tap({ target })` returns the point it clicked in the same pixels. Verify refuses a negative or fractional point before sending it, and Revyl refuses one past the screen's edge without clicking; both throw `INVALID_ARGUMENT` naming the valid range. See [For coding agents](agents.md#exact-actions-and-coordinates) for a runnable example. diff --git a/packages/verify/src/open.ts b/packages/verify/src/open.ts index b7f03dc..7befc97 100644 --- a/packages/verify/src/open.ts +++ b/packages/verify/src/open.ts @@ -7,7 +7,7 @@ import { DeviceSession, type OpenedSession } from './session.js'; import { ComputerSession } from './computer-session.js'; import type { LocalAgent } from './agent/loop.js'; import { chooseAgent, type ModelOption } from './agent/providers.js'; -import { isLegacyProfileRefusal, planSessionProfile, type SessionProfilePlan } from './session-profile.js'; +import { isLegacyProfileRefusal, planSessionProfile, supportsSessionProfileDefaults, type SessionProfilePlan } from './session-profile.js'; export interface OpenOptions { /** The config file to read target names from. Defaults to the nearest verify.config.ts at or above the current folder. */ @@ -21,10 +21,12 @@ export interface OpenOptions { /** Runs every instruction and validation on a custom agent from localAgent(). Pass model or agent, not both. */ agent?: LocalAgent; /** - * A session profile from session.profiles in .revyl/config.yaml, such as 'signed-in', that Revyl runs before open() returns, + * A session profile from session.profiles in .revyl/config.yaml locally or in sessionProfileProjectId's Git repository, + * such as 'signed-in', that Revyl runs before open() returns, * or 'none' for no profile. Left out, the project's session.default_profile runs when it sets one. Web, iOS, Android and Mac only. */ profile?: string; + sessionProfileProjectId?: string; } export interface AttachOptions extends Pick { @@ -84,11 +86,14 @@ export async function open(target: string | TargetConfig, options: OpenOptions = if (agent && (resolved.platform === 'mac' || resolved.platform === 'linux')) { throw new VerifyError('NOT_AVAILABLE_ON_PLATFORM', 'Your own model runs steps on browsers and devices, not on computers.'); } - const profile = await planSessionProfile(options.profile, resolved.platform, process.cwd()); + const profile = await planSessionProfile(options.profile, resolved.platform, process.cwd(), options.sessionProfileProjectId); const credentials = await credentialsForUse(options); const log = options.log === false ? undefined : (options.log ?? ((line: string) => void process.stderr.write(`[verify] ${line}\n`))); const client = new RevylClient({ token: credentials.token, backendUrl: options.backendUrl }); const chosen = resolved; + if (profile?.implicit && chosen.platform !== 'mac' && await supportsSessionProfileDefaults(client)) { + profile.fields.session_profile.instruction = 'default'; + } const start = (plan: SessionProfilePlan | undefined): Promise => chosen.platform === 'mac' || chosen.platform === 'linux' ? ComputerSession.start(client, chosen, { stepTimeout, log, appUrl: options.appUrl, ...(plan ? { profile: plan } : {}) }) diff --git a/packages/verify/src/session-profile.ts b/packages/verify/src/session-profile.ts index 96fedeb..1ab3f2e 100644 --- a/packages/verify/src/session-profile.ts +++ b/packages/verify/src/session-profile.ts @@ -3,16 +3,24 @@ import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from 'nod import { dirname, join, posix, resolve, sep } from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; import { parse as parseYaml } from 'yaml'; -import type { RawResponse } from './api/client.js'; +import type { RawResponse, RevylClient } from './api/client.js'; import type { Platform } from './api/types.js'; import { VerifyError, isVerifyError, type RefusalReason } from './errors.js'; /** How a session profile run ended, as Revyl reports it. */ -export type SessionProfileOutcome = 'succeeded' | 'script_failed' | 'script_timed_out' | 'script_unavailable' | 'output_invalid' | 'runner_failed'; +export type SessionProfileOutcome = + | 'succeeded' + | 'script_failed' + | 'script_timed_out' + | 'script_unavailable' + | 'output_invalid' + | 'runner_failed' + | 'script_execution_unknown' + | 'cancelled_before_script_execution'; /** The session_profile fields a start or create request carries. */ export interface SessionProfileFields { - session_profile: { instruction: 'named'; name: string }; + session_profile: { instruction: 'named' | 'default'; name: string }; session_profile_source?: { project_id: string; git_branch_name?: string }; session_profile_files?: { script: string; @@ -38,6 +46,18 @@ export interface ReportedSessionProfile { missingGitBranchName?: string; } +export async function supportsSessionProfileDefaults(client: RevylClient): Promise { + try { + const response = await client.json('GET', '/api/v1/backend-capabilities', { + query: { contract: 'session_profile_starts' }, + retry: false, + }); + return isMapping(response) && Array.isArray(response.capabilities) && response.capabilities.includes('device_session_session_profile_picks'); + } catch { + return false; + } +} + const NONE = 'none'; const PROFILE_NAME = /^[a-z0-9-]{1,64}$/; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -56,9 +76,17 @@ const NONE_HINT = "profile: 'none'"; /** * Plans the session profile open() sends: an explicit name, or the project's session.default_profile when profile is - * undefined. Undefined when nothing is sent, which is always the case for profile 'none'. Reads .revyl/config.yaml at or above cwd. + * undefined. A project ID requires an explicit name and bypasses local config. Otherwise reads .revyl/config.yaml at or above cwd. */ -export async function planSessionProfile(profile: unknown, platform: Platform, cwd: string): Promise { +export async function planSessionProfile(profile: unknown, platform: Platform, cwd: string, sessionProfileProjectId?: string): Promise { + if (sessionProfileProjectId !== undefined) { + if (typeof sessionProfileProjectId !== 'string' || sessionProfileProjectId.length !== 36 || !UUID.test(sessionProfileProjectId)) { + throw new VerifyError('INVALID_ARGUMENT', 'open(): sessionProfileProjectId must be a Revyl project UUID.'); + } + if (typeof profile !== 'string' || profile === NONE || PROFILE_NAME.exec(profile)?.[0] !== profile) { + throw new VerifyError('INVALID_ARGUMENT', "open(): sessionProfileProjectId requires profile to name a session profile (1-64 lowercase letters, digits or hyphens), not 'none'."); + } + } if (profile !== undefined && (typeof profile !== 'string' || (profile !== NONE && !PROFILE_NAME.test(profile)))) { throw new VerifyError('INVALID_ARGUMENT', "open(): profile must be a session profile name from session.profiles in .revyl/config.yaml (1-64 lowercase letters, digits or hyphens), or 'none'."); } @@ -67,6 +95,15 @@ export async function planSessionProfile(profile: unknown, platform: Platform, c if (profile === undefined) return undefined; throw new VerifyError('NOT_AVAILABLE_ON_PLATFORM', `open(): session profiles run on web, iOS, Android and Mac sessions, not ${platform}. Leave out profile.`); } + if (sessionProfileProjectId !== undefined) { + return { + name: profile as string, + fields: { + session_profile: { instruction: 'named', name: profile as string }, + session_profile_source: { project_id: sessionProfileProjectId }, + }, + }; + } const configPath = findConfig(cwd); if (!configPath) { if (profile === undefined) return undefined; @@ -507,6 +544,8 @@ const OUTCOME_FIXES: Record = { script_unavailable: 'Revyl could not find its script: commit it, or check session.profiles in .revyl/config.yaml. A script name with no .revyl/scripts file must be a Library Script in your Revyl organization.', output_invalid: 'An output file the script wrote broke a rule, as the reason says. Fix what the script writes there.', runner_failed: 'It failed on Revyl\'s side. Open the session again.', + script_execution_unknown: 'The runner or session stopped after the script may have started, so the script may have run. Check the session before retrying.', + cancelled_before_script_execution: 'The session stopped before the script started. Retry the profile when the session can remain active long enough to run it.', }; /** SESSION_PROFILE_FAILED for a profile Revyl reported as failed. Revyl stops the session itself. */ @@ -527,12 +566,12 @@ export function profileNotReportedError(platform: Platform, viewerUrl: string): } const REFUSALS: Record string }> = { - session_profile_undefined: { code: 'CONFIG_INVALID', fix: (plan) => `Check that session.profiles in ${plan.configPath ?? '.revyl/config.yaml'} defines it and that project.id names the project that holds it.` }, + session_profile_undefined: { code: 'CONFIG_INVALID', fix: (plan) => plan.configPath ? `Check that session.profiles in ${plan.configPath} defines it and that project.id names the project that holds it.` : "Check that the project's .revyl/config.yaml in Git defines the session profile and that sessionProfileProjectId names that project." }, session_profile_source_required: { code: 'INVALID_ARGUMENT', fix: () => 'Update Verify to the latest version; it sends the project with every named profile.' }, session_profile_files_need_named: { code: 'INVALID_ARGUMENT', fix: () => 'Update Verify to the latest version; it sends checkout files only with a named profile.' }, session_profile_script_unavailable: { code: 'SESSION_PROFILE_FAILED', fix: () => 'Commit the script or add it to .revyl/scripts, or create the Library Script with that name in your Revyl organization.' }, repository_connection_missing: { code: 'CONFIG_INVALID', fix: () => "Connect the repository's GitHub or GitLab app to the project in Revyl, then open the session again." }, - project_not_found: { code: 'CONFIG_INVALID', fix: (plan) => `project.id in ${plan.configPath ?? '.revyl/config.yaml'} isn't a project in this API key's organization. Use a key from that organization, or fix project.id.` }, + project_not_found: { code: 'CONFIG_INVALID', fix: (plan) => plan.configPath ? `project.id in ${plan.configPath} isn't a project in this API key's organization. Use a key from that organization, or fix project.id.` : "sessionProfileProjectId isn't a project in this API key's organization. Use a key from that organization, or fix sessionProfileProjectId." }, repository_unavailable: { code: 'API_ERROR', fix: () => "Revyl couldn't read the repository after 3 attempts. Try again in a few minutes." }, }; diff --git a/packages/verify/src/session.ts b/packages/verify/src/session.ts index 6149448..d180534 100644 --- a/packages/verify/src/session.ts +++ b/packages/verify/src/session.ts @@ -1113,7 +1113,10 @@ export class DeviceSession implements Session { if (!plan?.name) return true; if (profile?.status === 'failed') throw profileFailedError(profile, plan, this.viewerUrl); if (!active) return false; - if (!profile) throw profileNotReportedError(this.platform, this.viewerUrl); + if (!profile) { + if (plan.fields.session_profile.instruction === 'default') return true; + throw profileNotReportedError(this.platform, this.viewerUrl); + } return profile.status === 'succeeded'; } diff --git a/python/README.md b/python/README.md index f9ef84d..9ba28c8 100644 --- a/python/README.md +++ b/python/README.md @@ -171,6 +171,7 @@ For async code use `async with await async_attach(computer_id) as computer`, the - `model`: runs every instruction and validation on your own model instead of Revyl's agent; see [Your own model](#your-own-model). Browsers and devices only; computers raise `NOT_AVAILABLE_ON_PLATFORM`. - `agent`: the same with a custom agent from `local_agent()`. Pass `model` or `agent`, not both. - `profile`: a session profile from your project's `.revyl/config.yaml`, such as `"signed-in"`, that Revyl runs before `open()` returns, or `"none"` for no profile. Left out, the project's `session.default_profile` runs when it sets one. Web, iOS, Android and Mac computers. See [Session profiles](#session-profiles). +- `session_profile_project_id`: a Revyl project UUID to read the named session profile from Git instead of your checkout. Requires `profile` to name a session profile, not `"none"`. Verify reads no local `.revyl/config.yaml` and sends no local script or Git branch. ## Session profiles @@ -195,14 +196,31 @@ with open(web, profile="none") as session: | `profile` | What Verify sends | | --- | --- | | `"signed-in"` | That profile, with the project and the script from this checkout. | -| left out | The project's `session.default_profile`, the same way, when `.revyl/config.yaml` sets one. Otherwise nothing, so the start request is the same as before profiles existed. | +| left out | The checkout's `session.default_profile` when set. On web, iOS and Android, a capable backend skips it if the project doesn't target the launched app. Otherwise nothing is sent. | | `"none"` | No profile, not even the default: Verify sends no profile fields, so the start request is the same as before profiles existed. Needs no `.revyl/config.yaml`. | -Profiles work on web, iOS, Android and Mac computers. On a Linux computer, a profile name raises `NOT_AVAILABLE_ON_PLATFORM` before anything is sent, and no default runs; `"none"` is accepted. Hosted sessions (`computer.open()`), `attach()` and `current_computer()` never run a profile: they take no `profile` argument, so passing one raises `TypeError`. `async_open()` takes `profile` the same way. +Profiles work on web, iOS, Android and Mac computers. On a Linux computer, a profile name raises `NOT_AVAILABLE_ON_PLATFORM` before anything is sent, and no default runs; `"none"` is accepted without a project option. Hosted sessions (`computer.open()`), `attach()` and `current_computer()` never run a profile: they take no `profile` or `session_profile_project_id` argument, so passing either raises `TypeError`. `async_open()` takes both options the same way as `open()`. + +For an implicit checkout default on web, iOS or Android, Verify reads `GET /api/v1/backend-capabilities?contract=session_profile_starts`. If `capabilities` includes `device_session_session_profile_picks`, it sends `instruction="default"` with the default's name and the same checkout files and source. Revyl runs it when the project targets the launched app, or when no registered app launches; otherwise the session starts without a profile. A missing capability or a failed read keeps today's `instruction="named"` request. Explicit profiles and Mac computer defaults always use `named` and make no capability request. + +### Without a checkout + +Pass `session_profile_project_id` with a named `profile` to use the project's session profile from Git, without any local `.revyl/config.yaml`: + +```python +with open( + Target(platform="mac"), + profile="signed-in", + session_profile_project_id="0b9e6f3a-1c2d-4e5f-8a9b-0c1d2e3f4a5b", +) as session: + session.exec("pwd") +``` + +Verify sends `session_profile` with `instruction="named"` and the profile name, and `session_profile_source` with only `project_id`. It sends no `session_profile_files` or `git_branch_name`; Revyl reads the project's default branch in Git. A local config, even if present, is ignored. An invalid project UUID or a missing, empty or `"none"` profile raises `INVALID_ARGUMENT` before any request. Refusals, repository retries and waiting for the profile follow the same rules as checkout starts; an explicit profile is never silently skipped on an older backend. ### Where Verify reads the profile -Verify reads `.revyl/config.yaml` in the current folder (`os.getcwd()`) or the nearest folder above it that has one: the file `revyl init` writes in your app's checkout. It needs `project.id` and the profile under `session.profiles`, and reads nothing else from the file: +Without `session_profile_project_id`, Verify reads `.revyl/config.yaml` in the current folder (`os.getcwd()`) or the nearest folder above it that has one: the file `revyl init` writes in your app's checkout. It needs `project.id` and the profile under `session.profiles`, and reads nothing else from the file: ```yaml project: @@ -248,6 +266,8 @@ Neither errors nor logs contain the script's content or output. A refusal keeps | `script_unavailable` | The script isn't in this checkout or in Git, or the Library Script is missing | Commit the script or add it to `.revyl/scripts`, or create the Library Script | | `output_invalid` | A file the script wrote broke a rule; `failure_reason` names the file and the line | Fix what the script writes there | | `runner_failed` | Something failed on Revyl's side | Open the session again | +| `script_execution_unknown` | The run ended after Revyl let the script start because its runner was lost or the session stopped, timed out, or was cancelled, so the script may have run | Check the session before retrying | +| `cancelled_before_script_execution` | The session stopped, timed out, or was cancelled before the script started | Retry the profile when the session can remain active long enough to run it | ## Exact actions diff --git a/python/src/revyl_verify/__init__.py b/python/src/revyl_verify/__init__.py index b16a550..5fe7d61 100644 --- a/python/src/revyl_verify/__init__.py +++ b/python/src/revyl_verify/__init__.py @@ -3,6 +3,7 @@ import os import sys from collections.abc import Callable +from dataclasses import replace from typing import Literal from ._agent import ( @@ -162,9 +163,14 @@ def open( model: ModelOption | None = None, agent: LocalAgent | None = None, profile: str | None = None, + session_profile_project_id: str | None = None, _cancellation: Cancellation | None = None, ) -> Session: - from ._session_profile import is_legacy_profile_refusal, plan_session_profile + from ._session_profile import ( + is_legacy_profile_refusal, + plan_session_profile, + supports_session_profile_defaults, + ) from ._transport import Client if not isinstance(target, Target): @@ -177,12 +183,26 @@ def open( "NOT_AVAILABLE_ON_PLATFORM", "Your own model runs steps on browsers and devices, not on computers.", ) - plan = plan_session_profile(profile, target.platform, os.getcwd()) + plan = plan_session_profile(profile, target.platform, os.getcwd(), session_profile_project_id) install_signal_cleanup() seconds(step_timeout, 1, 3600, "step_timeout") progress = _progress(log) viewer = origin(app_url or "https://app.revyl.ai", app=True) client = Client(backend_url, app_url, _cancellation) + if ( + plan is not None + and plan.implicit + and not computer + and supports_session_profile_defaults(client, _cancellation) + ): + plan = replace( + plan, + uses_default_instruction=True, + fields={ + **plan.fields, + "session_profile": {"instruction": "default", "name": plan.name}, + }, + ) start = (ComputerSession if computer else Session).start try: session = start(client, viewer, target, step_timeout, progress, _cancellation, profile=plan) diff --git a/python/src/revyl_verify/_async.py b/python/src/revyl_verify/_async.py index cb24ea1..4c326df 100644 --- a/python/src/revyl_verify/_async.py +++ b/python/src/revyl_verify/_async.py @@ -237,6 +237,7 @@ async def async_open( model: ModelOption | None = None, agent: LocalAgent | None = None, profile: str | None = None, + session_profile_project_id: str | None = None, ) -> AsyncSession: from . import open @@ -250,6 +251,7 @@ async def async_open( model=model, agent=agent, profile=profile, + session_profile_project_id=session_profile_project_id, _cancellation=cancellation, ) ) diff --git a/python/src/revyl_verify/_session.py b/python/src/revyl_verify/_session.py index 4ba5cba..15db468 100644 --- a/python/src/revyl_verify/_session.py +++ b/python/src/revyl_verify/_session.py @@ -465,6 +465,8 @@ def _profile_done(self, profile: ReportedSessionProfile | None, active: bool) -> if not active: return False if profile is None: + if plan.uses_default_instruction: + return True raise profile_not_reported_error(self.platform, self.viewer_url) return profile.status == "succeeded" diff --git a/python/src/revyl_verify/_session_profile.py b/python/src/revyl_verify/_session_profile.py index 4c2284e..a4a9e41 100644 --- a/python/src/revyl_verify/_session_profile.py +++ b/python/src/revyl_verify/_session_profile.py @@ -13,7 +13,16 @@ from ._git_branch import detect_git_branch from ._models import UUID_PATTERN, Platform -from ._transport import Json, RefusalReason, Response, SessionProfileOutcome, VerifyError +from ._transport import ( + Cancellation, + Client, + Deadline, + Json, + RefusalReason, + Response, + SessionProfileOutcome, + VerifyError, +) _NONE = "none" _PROFILE_NAME = re.compile(r"[a-z0-9-]{1,64}") @@ -30,6 +39,7 @@ class SessionProfilePlan: config_path: str | None fields: dict[str, Json] implicit: bool = False + uses_default_instruction: bool = False @dataclass(frozen=True) @@ -41,6 +51,19 @@ class ReportedSessionProfile: missing_git_branch_name: str | None = None +def supports_session_profile_defaults(client: Client, cancellation: Cancellation | None) -> bool: + try: + response = client.json( + "GET", + "/api/v1/backend-capabilities?contract=session_profile_starts", + deadline=Deadline(30, cancellation), + ) + except VerifyError: + return False + capabilities = response.get("capabilities") + return isinstance(capabilities, list) and "device_session_session_profile_picks" in capabilities + + class _ConfigLoader(yaml.SafeLoader): def construct_mapping(self, node: yaml.MappingNode, deep: bool = False) -> dict[Any, Any]: seen: set[Any] = set() @@ -74,8 +97,22 @@ def construct_mapping(self, node: yaml.MappingNode, deep: bool = False) -> dict[ def plan_session_profile( - profile: object, platform: Platform, cwd: str + profile: object, platform: Platform, cwd: str, session_profile_project_id: str | None = None ) -> SessionProfilePlan | None: + if session_profile_project_id is not None: + if not isinstance(session_profile_project_id, str) or not UUID_PATTERN.fullmatch( + session_profile_project_id + ): + raise VerifyError( + "INVALID_ARGUMENT", + "open(): session_profile_project_id must be a Revyl project UUID.", + ) + if not isinstance(profile, str) or profile == _NONE or not _PROFILE_NAME.fullmatch(profile): + raise VerifyError( + "INVALID_ARGUMENT", + "open(): session_profile_project_id requires profile to name a session profile " + "(1-64 lowercase letters, digits or hyphens), not 'none'.", + ) if profile is not None and ( not isinstance(profile, str) or (profile != _NONE and not _PROFILE_NAME.fullmatch(profile)) ): @@ -94,6 +131,15 @@ def plan_session_profile( "open(): session profiles run on web, iOS, Android and Mac sessions, " f"not {platform}. Leave out profile.", ) + if session_profile_project_id is not None: + return SessionProfilePlan( + name=cast(str, profile), + config_path=None, + fields={ + "session_profile": {"instruction": "named", "name": cast(str, profile)}, + "session_profile_source": {"project_id": session_profile_project_id}, + }, + ) config_path = _find_config(cwd) if config_path is None: if profile is None: @@ -346,6 +392,14 @@ def missing_branch_notice( "output_invalid": "An output file the script wrote broke a rule, as the reason says. Fix " "what the script writes there.", "runner_failed": "It failed on Revyl's side. Open the session again.", + "script_execution_unknown": ( + "The runner or session stopped after the script may have started, so the script may have " + "run. Check the session before retrying." + ), + "cancelled_before_script_execution": ( + "The session stopped before the script started. Retry the profile when the session can " + "remain active long enough to run it." + ), } @@ -383,6 +437,9 @@ def _config_name(plan: SessionProfilePlan) -> str: lambda plan: ( f"Check that session.profiles in {_config_name(plan)} defines it and that " "project.id names the project that holds it." + if plan.config_path + else "Check that the project's .revyl/config.yaml in Git defines the session profile " + "and that session_profile_project_id names that project." ), ), "session_profile_source_required": ( @@ -417,6 +474,9 @@ def _config_name(plan: SessionProfilePlan) -> str: lambda plan: ( f"project.id in {_config_name(plan)} isn't a project in this API key's " "organization. Use a key from that organization, or fix project.id." + if plan.config_path + else "session_profile_project_id isn't a project in this API key's organization. " + "Use a key from that organization, or fix session_profile_project_id." ), ), "repository_unavailable": ( diff --git a/python/src/revyl_verify/_transport.py b/python/src/revyl_verify/_transport.py index 1a30294..eb11817 100644 --- a/python/src/revyl_verify/_transport.py +++ b/python/src/revyl_verify/_transport.py @@ -70,6 +70,8 @@ "script_unavailable", "output_invalid", "runner_failed", + "script_execution_unknown", + "cancelled_before_script_execution", ] Json: TypeAlias = "None | bool | int | float | str | list[Json] | dict[str, Json]"