httpapi

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 57 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package httpapi exposes the target registry and streaming endpoint over HTTP.

Index

Constants

View Source
const (
	InputToMin = 0
	InputToMax = 3
)

InputToMin and InputToMax bound the rotate action's "to" field -- quarter turns clockwise, so 0..3 is the whole range a display can report. Both handleInput's own check and apischema's generated schema (fieldOverrides, internal/apischema/schema.go) read these constants rather than repeating the numbers, so TestRotateToRangeMatchesTheConstants can catch the two drifting apart at the type rather than only at whatever cases a test happened to try.

View Source
const (
	HeaderViewer = "X-Loupe-Viewer"
	HeaderAgent  = "X-Loupe-Agent"
)

Request headers /api/input reads to tell a viewer from an agent.

View Source
const ErrCodeAVDExists = "avdExists"

ErrCodeAVDExists is the 409 of POST /api/avds and POST /api/devices when a device of that name exists. The CLI names an AVD after its profile and has no flag to choose another name, so a profile can be created once; on /api/devices it means a device with the requested name exists on that platform, an AVD or a simulator.

View Source
const ErrCodeAmbiguous = "ambiguous"

ErrCodeAmbiguous is POST /api/input's 409 when a tap's match names more than one node and no index. Candidates lists them; nothing was touched.

View Source
const ErrCodeBusy = "busy"

ErrCodeBusy is POST /api/devices/shutdown's and DELETE /api/devices's 409 while another shutdown or delete of the same target is still running.

View Source
const ErrCodeCertChanged = "certChanged"

ErrCodeCertChanged is POST /api/servers' 502 when the peer's certificate does not match its pin. Removing the server and adding it again takes the new certificate.

View Source
const ErrCodeClaimed = "claimedBy"

ErrCodeClaimed is the 409 an agent gets for input on a target another agent has claimed, and for claiming or releasing one. `claim` names the holder. Nothing was sent to the device. There is no retry time: the claim lasts until its holder releases it or stops calling for claimLease.

View Source
const ErrCodeConfirmFingerprint = "confirmFingerprint"

ErrCodeConfirmFingerprint is POST /api/servers' 409 when the peer's certificate does not verify against the system roots, or no longer matches the fingerprint the request carried. No token has been sent to the peer. Sending the request again with the answer's fingerprint pins it.

View Source
const ErrCodeCreating = "creating"

ErrCodeCreating is the 409 of POST /api/avds and POST /api/devices while another creation runs, from either. Two CLI creates would share one system image download, and one slot keeps the target list's single pending row honest.

View Source
const ErrCodeHandsOff = "handsOff"

ErrCodeHandsOff is the 409 every agent gets for input on a target the person has marked hands off. It lasts until they clear it.

View Source
const ErrCodeHubHeld = "hubHeld"

ErrCodeHubHeld is POST /api/input's 409 when Device Hub holds an iOS simulator's buttons and keyboard and this server has not claimed it. The action that takes them back, "reclaim", closes that simulator's apps, so a client asks its user before sending it.

View Source
const ErrCodeHumanHeld = "humanHeld"

ErrCodeHumanHeld is POST /api/input's 409 when a viewer has used the target within the human hold, or has a finger down on it now. Nothing was sent to the device. RetryAfterMs says when the hold lapses if nobody touches it again, and the Retry-After header says the same in whole seconds.

View Source
const ErrCodeInterrupted = "interrupted"

ErrCodeInterrupted is POST /api/input's 409 when the person interrupted the caller with a flag (kind "interrupt") it has not read since. ID is the flag's. The device may have changed under the caller: it reads the flag with GET /api/flags?id=, which lifts the refusal, and decides from the screen as it is now whether what it was doing still applies.

View Source
const ErrCodeNoCameraShim = "noCameraShim"

ErrCodeNoCameraShim is the launch action's 422 on a physical iPhone with a camera image staged, when the app cannot be given the camera shim: it is not development-signed, or no local identity shares its team.

View Source
const ErrCodeNoFFmpeg = "noFFmpeg"

ErrCodeNoFFmpeg is GET /api/record/{id}/frames's 501 when ffmpeg is not on PATH, in /opt/homebrew/bin or in /usr/local/bin.

View Source
const ErrCodeNoLaunchActivity = "noLaunchActivity"

ErrCodeNoLaunchActivity is the launch action's 422 when the package is installed and has no launcher activity, so it opens only with "activity" named.

View Source
const ErrCodeNoMatch = "noMatch"

ErrCodeNoMatch is POST /api/input's 404 when a tap's match names no node on the screen, after waiting waitMs for one. Nothing was touched.

View Source
const ErrCodeNoPaste = "noPaste"

ErrCodeNoPaste is a /api/drop where no Paste item appeared: the point is not a field that takes an image. The client falls back to /api/media.

View Source
const ErrCodeNoSuchActivity = "noSuchActivity"

ErrCodeNoSuchActivity is the launch action's 404 when the named activity is not one the package declares.

View Source
const ErrCodeNoURLHandler = "noHandler"

ErrCodeNoURLHandler is the openURL action's 422 when nothing on the device handles the URL, such as a custom scheme whose app is not installed.

View Source
const ErrCodeNotInstalled = "notInstalled"

ErrCodeNotInstalled is the launch action's 404 when the target has no app by that name.

View Source
const ErrCodeNotSupported = "notSupported"

ErrCodeNotSupported is POST /api/devices/shutdown's and DELETE /api/devices's 422 when the target is not an AVD or simulator this server can act on, or is not in a state the action applies to (a shut-down AVD has nothing to shut down). It is also GET /api/logcat's 422 for a format or a since the target's log cannot give.

View Source
const ErrCodePasteFailed = "pasteFailed"

ErrCodePasteFailed is a /api/drop where Paste was tapped and the field's value did not change, after a second try.

View Source
const ErrCodePhoneDeliveryUnknown = "phoneDeliveryUnknown"

ErrCodePhoneDeliveryUnknown is POST /api/input's 503 when a send to a physical iPhone went out and whether the phone received it is unknown: simcap reported a failure after sending, or did not reply in its budget. The input may have landed, so do not retry blindly: a second try could tap twice, press Home twice or double a character. CoreDevice gives no delivery receipt, so even a 200 means sent and the capability still answered.

View Source
const ErrCodePhoneUnreachable = "phoneUnreachable"

ErrCodePhoneUnreachable is POST /api/input's 503 when a physical iPhone did not accept the input: CoreDevice refused it before anything was sent, the server woke the tunnel with devicectl and sent it once more, and CoreDevice refused again. Nothing reached the phone, so retrying is safe. `error` has CoreDevice's text and devicectl's outcome. It never covers a send that went out; that is ErrCodePhoneDeliveryUnknown.

View Source
const ErrCodeRecording = "recording"

ErrCodeRecording is POST /api/record's 409 when the target is already recording, and the 409 for fetching the MP4, a contact sheet or a DELETE of a recording that has not ended. Stop it first.

View Source
const ErrCodeRunnerStarting = "runnerStarting"

ErrCodeRunnerStarting is POST /api/input's 503 when a touch on an iPhone below iOS 27 found its XCUITest runner not answering yet. Nothing was sent and the touch started the runner, so retrying in a few seconds is safe.

View Source
const ErrCodeRunnerUnavailable = "runnerUnavailable"

ErrCodeRunnerUnavailable is POST /api/input's 422 when a touch on an iPhone below iOS 27 cannot reach a runner at all: none is built, or the phone is on Wi-Fi, which usbmuxd does not carry. `error` says which.

View Source
const ErrCodeServerDown = "serverDown"

ErrCodeServerDown is POST /api/servers' 502 when the peer cannot be reached, and the reason on the rows of a peer that stopped answering.

View Source
const ErrCodeSharedClipboardOff = "disabled"

ErrCodeSharedClipboardOff is /api/clipboard/shared's 409 while this server's sharedClipboard is off, including a long-poll that was waiting when it was turned off.

View Source
const ErrCodeSimcapOutdated = "simcapOutdated"

ErrCodeSimcapOutdated is /api/drop's 501 when simcap was built before it could put an image on the pasteboard. Rebuilding it (make simcap) fixes it; it is 501 like ErrCodeNoFFmpeg, a tool this server lacks, not a device that failed.

View Source
const ErrCodeTouchRejected = "touchRejected"

ErrCodeTouchRejected is POST /api/input's 409 when a tap or swipe reached the device and Android's input dispatcher threw it away, usually because a pointer is stuck down (docs/internals/traps.md, trap 50). The error carries the dispatcher's reason. Nothing moved on the screen.

View Source
const ErrCodeUnsupported = "unsupported"

ErrCodeUnsupported is a /api/drop on a target that cannot paste an image. It is not ErrCodeNotSupported because the client was written against "unsupported".

View Source
const ErrCodeUnsupportedProtocol = "unsupportedProtocol"

ErrCodeUnsupportedProtocol is POST /api/servers' 502 when the owner ends the stream connection with session.EndedUnsupportedProtocol: it speaks no version of the session protocol this server does.

View Source
const (

	// FlagInterrupt is FlagRequest.Kind for stopping a driving agent.
	FlagInterrupt = "interrupt"
)
View Source
const HeaderSession = "X-Loupe-Session"

HeaderSession names the agent's session, so two sessions sharing an agent name are still told apart. A claim made with one is held by that session.

View Source
const MaxSequenceSteps = 50

MaxSequenceSteps bounds one POST /api/sequence. A flow longer than this is better split, so a failure partway reports where it stopped soon enough.

View Source
const QUICALPN = session.QUICALPN

QUICALPN is session.QUICALPN, for the startup banner.

Variables

View Source
var ErrJustShutDown = errors.New("target was just shut down")

ErrJustShutDown is what Acquire returns for a target whose shutdown or delete is running or returned within shutDownGrace, or one shut down while this open was running. The handlers match it to close with the same reason the original close gave.

View Source
var InputActions = []string{"tap", "swipe", "pinch", "text", "key", "button", "rotate", "reclaim", "hardwareKeyboard", "launch", "openURL", "move", "wait"}

InputActions lists every action handleInput's switch dispatches on, in the order that switch checks them. It exists so nothing else has to copy the list by hand: apischema builds POST /api/input's request schema directly from it (see internal/apischema/schema.go's inputActionSchemas), and TestEveryInputActionDispatches drives each entry through handleInput and requires it not fall through to the "unknown action" branch -- so an action added to the switch and forgotten here fails a test rather than silently shipping a schema an agent's generated client cannot see.

View Source
var InputMatchFields = map[string][]string{
	"tap":  {"match"},
	"wait": {"match"},
}

InputMatchFields names the actions that can find their point in the view hierarchy instead of being given one, and the fields that do it. A body carrying any of them is checked against this set rather than InputRequiredFields, and must not also carry the fields it replaces: a tap with both a match and an x would leave the caller guessing which one won. apischema gives each of these actions a second oneOf variant from this table, so the schema and validateInputRequest agree.

View Source
var InputRequiredFields = map[string][]string{
	"tap":     {"x", "y"},
	"swipe":   {"x", "y", "x2", "y2"},
	"pinch":   {"x", "y", "scale"},
	"text":    {"text"},
	"key":     {"keycode"},
	"button":  {"button"},
	"rotate":  nil,
	"reclaim": nil,

	"hardwareKeyboard": {"on"},

	"launch":  {"package"},
	"openURL": {"url"},
	"move":    {"x", "y"},

	"wait": {"ms"},
}

InputRequiredFields names the JSON fields handleInput requires present -- not merely non-zero, since x=0 and keycode=0 are both coordinates and codes a caller can genuinely mean -- for each action in InputActions. validateInputRequest checks the raw decoded body against this table before the switch below ever runs, and apischema builds POST /api/input's oneOf request schema from the same table (inputActionSchemas), so the wire contract and the handler's own validation cannot drift apart. A field named here and missing from the request is a 400 naming it; ms and to, which no action requires, stay optional (a swipe with no ms takes defaultSwipeMs, and a rotate with no to cycles from the current rotation). A tap's match stands in for its x and y: see InputMatchFields.

Functions

func NewToken

func NewToken() string

NewToken returns a fresh shared secret. 32 bytes because this guards a device someone can drive, not a page they can read.

func QUICConnFrom

func QUICConnFrom(ctx context.Context) (*quic.Conn, bool)

QUICConnFrom recovers the connection. The second return distinguishes "no connection was stashed" from "a nil one was", which is what lets a test tell a ConnContext that ran from one that was replaced.

func WithQUICConn

func WithQUICConn(ctx context.Context, conn *quic.Conn) context.Context

WithQUICConn stashes the QUIC connection on a request context.

This is wired as the http3.Server's ConnContext *before* webtransport.ConfigureHTTP3Server runs, because that function chains to whatever ConnContext it finds rather than replacing it. Setting it afterwards would drop webtransport-go's own hook and produce trap 14's fourth row, a `missing QUIC connection` from Upgrade with nothing in the server log.

Types

type AVDCreator

type AVDCreator struct {
	// contains filtered or unexported fields
}

AVDCreator runs `android emulator create <profile>` in the background and reports it as a target row until it ends. Only one runs at a time.

func NewAVDCreator

func NewAVDCreator(cli, sdk, avdHome string, registered func(time.Time, []target.AVD), trace func(map[string]any)) *AVDCreator

NewAVDCreator returns a creator for the CLI at cli, or nil when cli is "" and there is nothing to run.

type AVDProfile

type AVDProfile struct {
	// Name is what the CLI takes, and what the AVD it creates is called.
	Name  string `json:"name"`
	Label string `json:"label"`
	// Exists is true when an AVD of that name is installed, which the CLI
	// refuses to create again.
	Exists bool `json:"exists"`
}

AVDProfile is one entry of GET /api/avds/profiles.

type AVDProfilesResponse

type AVDProfilesResponse struct {
	Profiles []AVDProfile `json:"profiles"`
	// Creating names the profile being created, when one is.
	Creating string `json:"creating,omitempty"`
}

AVDProfilesResponse is GET /api/avds/profiles.

type AuthResponse added in v0.2.0

type AuthResponse struct {
	// Method is master, session or none.
	Method  string       `json:"method"`
	Session *SessionInfo `json:"session,omitempty"`
	// Pairing is false when the session store could not be read and only
	// the master token works.
	Pairing bool `json:"pairing"`
	// CanPair says whether the caller may mint codes.
	CanPair bool `json:"canPair"`
}

AuthResponse is GET /api/auth: how the caller is authenticated, and whether this server pairs at all. A server from before pairing answers 404.

type CameraResponse added in v0.2.0

type CameraResponse struct {
	Target string `json:"target"`
	OK     bool   `json:"ok"`
	// Applies is when the app looking through the camera sees the change:
	// cameraOpen, boot, live or launch.
	Applies target.CameraApplies `json:"applies"`
	Width   int                  `json:"width,omitempty"`
	Height  int                  `json:"height,omitempty"`
	TookMs  int64                `json:"tookMs"`
}

CameraResponse is what POST and DELETE /api/camera answer on success.

type ClaimInfo

type ClaimInfo struct {
	Target  string    `json:"target"`
	Agent   string    `json:"agent,omitempty"`
	Session string    `json:"session,omitempty"`
	Link    string    `json:"link,omitempty"`
	Since   time.Time `json:"since"`
	// IdleMs is how long since the holder's last call; the claim lapses at
	// claimLease.
	IdleMs int64 `json:"idleMs"`
}

ClaimInfo is a claim as /api/targets, /api/claims and a claimedBy 409 show it. Agent and Session are what the holder sent; Link, when present, is an https URL the holder says leads back to it.

type ClaimRequest

type ClaimRequest struct {
	Agent   string `json:"agent,omitempty"`
	Session string `json:"session,omitempty"`
	Link    string `json:"link,omitempty"`
}

ClaimRequest is POST /api/claims' optional body. Agent and Session default to the X-Loupe-Agent and X-Loupe-Session headers.

type ClipboardRequest

type ClipboardRequest struct {
	Text string `json:"text"`
	// Paste also puts the text into whatever field has focus. On a
	// simulator that is typed, since iOS asks before an app reads a
	// pasteboard another process set.
	Paste bool `json:"paste,omitempty"`
}

ClipboardRequest is POST /api/clipboard's body.

type ClipboardResponse

type ClipboardResponse struct {
	Target string `json:"target"`
	Text   string `json:"text"`
}

ClipboardResponse is what GET /api/clipboard returns.

type ConfigResponse

type ConfigResponse struct {
	Path   string        `json:"path"`
	Fields []configField `json:"fields"`
	// HostPasteboard names the Mac whose pasteboard this server mirrors into
	// the shared clipboard (clipshare.HostID), so Handset joins unless it is
	// on that same Mac. Absent when the server mirrors none.
	HostPasteboard string `json:"hostPasteboard,omitempty"`
}

type ConfigStore

type ConfigStore struct {
	// contains filtered or unexported fields
}

ConfigStore is the server's half of the settings contract: it owns the file, applies what can be applied without a restart, and knows which settings a command-line flag is overriding.

The flag set is the part that is easy to leave out and expensive to leave out. A flag beats the file at startup, so a UI that writes maxFps to the file while -max-fps is on the command line has changed nothing the running server will read. Saying so in the response is the difference between a setting that did not apply and a setting that appears to have applied.

func NewConfigStore

func NewConfigStore(path string, cur config.Config, pinned map[string]bool, startup config.Config, apply func(config.Config)) *ConfigStore

NewConfigStore builds a store over path, starting from cur. pinned names the settings a flag is overriding, and apply receives every accepted change so the live settings reach the manager.

func (*ConfigStore) Current

func (s *ConfigStore) Current() config.Config

Current returns a copy of the live configuration.

func (*ConfigStore) Path

func (s *ConfigStore) Path() string

Path is where the configuration is persisted.

type Conn

type Conn interface {
	// SendFrame delivers one encoded access unit. deadline is when the frame
	// stops being worth showing; a transport that can abandon an in-flight
	// frame should do so rather than finish sending something already stale.
	//
	// A transport that abandons a frame must return errFrameAbandoned. Nothing
	// above this can tell a reset frame from a delivered one otherwise, and
	// both the goodput measurement and the keyframe wait depend on the
	// difference.
	SendFrame(f session.OutMsg, deadline time.Time) error
	// SendControl delivers a control message: init, stats or pong.
	SendControl(b []byte) error
	// Recv returns the next message from the client, blocking until one
	// arrives or the connection ends.
	Recv() ([]byte, error)
	// Keepalive nudges the connection so idle intermediaries do not reap it.
	Keepalive() error
	// Name identifies the transport in traces.
	Name() string
	Close() error
}

Conn is one viewer's connection, independent of how it is carried.

The interface exists so the pacing, shedding and tracing logic is written once. Those decisions are about latency and the client's own measurements, not about framing, so a second transport should inherit them rather than reimplement them and drift.

type CrashList

type CrashList struct {
	Target  string               `json:"target"`
	Crashes []target.CrashReport `json:"crashes"`
}

CrashList is GET /api/crashes's answer.

type CreateAVDRequest

type CreateAVDRequest struct {
	Profile string `json:"profile"`
}

CreateAVDRequest is POST /api/avds.

type CreateAVDResponse

type CreateAVDResponse struct {
	ID string `json:"id"`
}

CreateAVDResponse is POST /api/avds's 202. The creation goes on after it; its progress is the target row with this id.

type CreateDeviceRequest

type CreateDeviceRequest struct {
	Platform string `json:"platform"`
	OS       string `json:"os"`
	Device   string `json:"device"`
	Name     string `json:"name"`
}

CreateDeviceRequest is POST /api/devices.

type CreateDeviceResponse

type CreateDeviceResponse struct {
	ID string `json:"id"`
}

CreateDeviceResponse is POST /api/devices's 202. The creation goes on after it; its progress is the target row with this id, and its end is the job in GET /api/devices/options.

type DeviceCreator

type DeviceCreator struct {
	// contains filtered or unexported fields
}

DeviceCreator creates an AVD with avdmanager or a simulator with simctl, from what is installed, and reports it as a target row until it ends.

func NewDeviceCreator

func NewDeviceCreator(cfg DeviceCreatorConfig) *DeviceCreator

NewDeviceCreator returns a creator, or nil when neither platform can create.

type DeviceCreatorConfig

type DeviceCreatorConfig struct {
	Manager *Manager
	// SDK is the Android SDK root; AVDManager is the avdmanager binary, ""
	// when there is none, and AVDHome where AVDs are installed. Android is
	// offered when AVDManager and RegisterAVDs are both set.
	SDK        string
	AVDManager string
	AVDHome    string
	// RegisterAVDs is called with every installed AVD after a creation, and
	// when that scan began, so the new one becomes a target. It must skip
	// names already registered, and names Unregister forgot after the scan
	// began (Manager.RegisterScanned).
	RegisterAVDs func(scannedAt time.Time, installed []target.AVD)
	// Simcap is the built simcap helper. iOS is offered when it is set, which
	// the caller does only once simctl lists simulators and simcap runs: a new
	// simulator would not reach the picker otherwise.
	Simcap string
	Trace  func(map[string]any)
}

DeviceCreatorConfig says what a DeviceCreator can make.

type DeviceJob

type DeviceJob struct {
	ID       string `json:"id"`
	Platform string `json:"platform"`
	Name     string `json:"name"`
	// State is creating, createFailed or done.
	State     string `json:"state"`
	Error     string `json:"error,omitempty"`
	CreatedID string `json:"createdId,omitempty"`
	// Warning is set on a "done" job whose AVD exists and works but lacks the
	// keys loupe patches into config.ini (keyboard, GPU, Play Store flag).
	Warning string `json:"warning,omitempty"`
}

DeviceJob is the creation in flight or the last one.

type DeviceModel

type DeviceModel struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	// Group is phone, foldable or tablet.
	Group string `json:"group"`
	Size  string `json:"size,omitempty"`
}

DeviceModel is one entry of a platform's devices list.

type DeviceOS

type DeviceOS struct {
	ID     string `json:"id"`
	Label  string `json:"label"`
	Detail string `json:"detail,omitempty"`
}

DeviceOS is one entry of a platform's os list: an installed system image or simulator runtime.

type DeviceOptionsResponse

type DeviceOptionsResponse struct {
	Platforms     []DevicePlatform    `json:"platforms"`
	ExistingNames map[string][]string `json:"existingNames"`
	Job           *DeviceJob          `json:"job,omitempty"`
	// ProfilesFallback is true when avdmanager is absent and the android CLI
	// is not: the client then offers /api/avds/profiles for Android.
	ProfilesFallback bool `json:"profilesFallback"`
}

DeviceOptionsResponse is GET /api/devices/options.

type DevicePlatform

type DevicePlatform struct {
	ID      string        `json:"id"`
	Label   string        `json:"label"`
	OS      []DeviceOS    `json:"os"`
	Devices []DeviceModel `json:"devices"`
	// Pairs maps an os id to the ids of the devices it can be created with.
	Pairs    map[string][]string `json:"pairs"`
	NameRule string              `json:"nameRule"`
}

DevicePlatform is one platform GET /api/devices/options offers.

type DropResponse added in v0.2.0

type DropResponse struct {
	Target string `json:"target"`
	OK     bool   `json:"ok"`
	TookMs int64  `json:"tookMs"`
}

DropResponse is what POST /api/drop answers on success.

type ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"`
	// Code names an error a client acts on rather than only shows. It is
	// empty for every error but the ErrCode constants below.
	Code string `json:"code,omitempty"`
	// RetryAfterMs is how long to wait before trying again, set only with
	// ErrCodeHumanHeld.
	RetryAfterMs int64 `json:"retryAfterMs,omitempty"`
	// ID names the recording that caused an ErrCodeRecording 409 on a start,
	// when it is known, and the flag behind an ErrCodeInterrupted 409.
	ID string `json:"id,omitempty"`
	// Claim is the claim that caused an ErrCodeClaimed 409.
	Claim *ClaimInfo `json:"claim,omitempty"`
	// Fingerprint is the certificate an ErrCodeConfirmFingerprint 409 asks
	// to have confirmed, as hex SHA-256 of its DER.
	Fingerprint string `json:"fingerprint,omitempty"`
	// Candidates are the nodes behind an ErrCodeAmbiguous 409, without
	// their children, or an ErrCodeNoMatch 404's when an index ran past
	// them.
	Candidates []*target.Node `json:"candidates,omitempty"`
}

ErrorResponse is the body every JSON error response on this API shares: one string naming what went wrong. It replaces what used to be an ad hoc map[string]string{"error": ...} built fresh at each call site -- the two marshal identically, but only a named type gives apischema (see internal/apischema) something to point a $ref at, and a caller something to unmarshal into without guessing the shape.

The handful of plain-text 405s built with http.Error directly ("POST only", "GET only" in agent.go and events.go) are not this type: they predate it, are not JSON, and are left alone deliberately -- see internal/apischema's endpoints table for where they are named instead of schematized.

type Extension

type Extension struct {
	Name  string `json:"name"`
	Label string `json:"label"`
	// Path is where clients reach it, "/api/ext/{name}/".
	Path string `json:"path"`
}

Extension is one registered extension.

type ExtensionRequest

type ExtensionRequest struct {
	// Name is the path segment clients reach it under, /api/ext/{name}/.
	Name string `json:"name"`
	// URL is where the extension listens: http or https on 127.0.0.1, ::1
	// or localhost.
	URL string `json:"url"`
	// Label is a name to show a person, defaulting to Name.
	Label string `json:"label,omitempty"`
}

ExtensionRequest is POST /api/extensions's body.

type ExtensionsResponse

type ExtensionsResponse struct {
	Extensions []Extension `json:"extensions"`
}

ExtensionsResponse is GET /api/extensions's body.

type Flag added in v0.2.0

type Flag struct {
	ID     uint64 `json:"id"`
	Target string `json:"target"`
	// Kind is "interrupt" for a flag that stopped an agent, else empty.
	Kind string `json:"kind,omitempty"`
	// Rev changes whenever the flag does; GET ?after= compares it.
	Rev  uint64 `json:"rev"`
	Note string `json:"note,omitempty"`
	// Width and Height are the screen in device pixels when flagged, 0 when
	// the target could not say.
	Width  int       `json:"width,omitempty"`
	Height int       `json:"height,omitempty"`
	Region *FlagRect `json:"region,omitempty"`
	// ClaimedBy is the agent holding the target when it was flagged.
	ClaimedBy string `json:"claimedBy,omitempty"`
	// To is who the person sent it to; absent means every session.
	To *FlagRecipient `json:"to,omitempty"`
	// Delivery is how sending it to a T3 thread went, once it has gone.
	Delivery *FlagDelivery `json:"delivery,omitempty"`
	// Watching is true while the person is still reproducing.
	Watching bool         `json:"watching"`
	Start    FlagSnapshot `json:"start"`
	// End, Events and EventsTruncated arrive when a watch ends.
	End    *FlagSnapshot `json:"end,omitempty"`
	Events []FlagEvent   `json:"events,omitempty"`
	// EventsTruncated means some of the person's input is missing: the
	// session's event ring wrapped, or the session restarted, mid-watch.
	EventsTruncated bool `json:"eventsTruncated,omitempty"`
}

Flag is one flag as the API returns it.

type FlagDelivery added in v0.2.0

type FlagDelivery struct {
	// State is "sending", "sent" or "failed".
	State string `json:"state"`
	Error string `json:"error,omitempty"`
	// Thread is the T3 thread it went to, a new one's id included.
	Thread string `json:"thread,omitempty"`
	// Dir holds the flag's screenshots and UI tree as sent.
	Dir string `json:"dir,omitempty"`
	// Output is the end of what a command wrote, or a webhook replied.
	Output string `json:"output,omitempty"`
}

FlagDelivery is how a flag sent to T3, a command or a webhook fared.

type FlagDestinationsResponse added in v0.2.0

type FlagDestinationsResponse struct {
	// T3 is absent when no t3Projects are configured.
	T3 *T3Destinations `json:"t3,omitempty"`
	// Commands and Webhooks are destinations.json's, by name only: what
	// they run or where they post never leaves the server.
	Commands []NamedDestination `json:"commands,omitempty"`
	Webhooks []NamedDestination `json:"webhooks,omitempty"`
	// Error says why destinations.json could not be read.
	Error string `json:"error,omitempty"`
}

FlagDestinationsResponse is GET /api/flags/destinations: where a flag can go besides a loupe mcp session.

type FlagEndRequest added in v0.2.0

type FlagEndRequest struct {
	Note   string         `json:"note,omitempty"`
	Region []float64      `json:"region,omitempty"`
	To     *FlagRecipient `json:"to,omitempty"`
}

FlagEndRequest is POST /api/flags/end's optional body. An interrupt is posted the moment the person stops the agent, so what they then write arrives with the end, and so may who it is for: To then names the one session that must read it before driving again. On any other flag all three are ignored.

type FlagEvent added in v0.2.0

type FlagEvent struct {
	T    int64  `json:"t"` // unix milliseconds
	Kind string `json:"kind"`
	// From and To are [x, y] in device pixels; To only for a swipe.
	From    []int  `json:"from,omitempty"`
	To      []int  `json:"to,omitempty"`
	Text    string `json:"text,omitempty"`
	Button  string `json:"button,omitempty"`
	Keycode int    `json:"keycode,omitempty"`
}

FlagEvent is one input of the person's during a watch, in device pixels.

type FlagListener added in v0.2.0

type FlagListener struct {
	Agent   string `json:"agent,omitempty"`
	Session string `json:"session,omitempty"`
	// Holds is true when this session holds the target asked about.
	Holds bool `json:"holds,omitempty"`
	// Target and IdleMs, on an active session, are the device it last
	// called about and how long ago.
	Target string `json:"target,omitempty"`
	IdleMs int64  `json:"idleMs,omitempty"`
}

FlagListener is a session waiting on GET /api/flags for new flags, as loupe mcp does.

type FlagListenersResponse added in v0.2.0

type FlagListenersResponse struct {
	Listeners []FlagListener `json:"listeners"`
	// Active is the sessions that called the agent API in the last 15
	// minutes but are not waiting on flags, as a session driving over HTTP
	// is not: nothing is pushed to them, but a flag can be sent to one.
	Active []FlagListener `json:"active"`
	// ClaimedBy is the agent holding ?target=, listening or not.
	ClaimedBy string `json:"claimedBy,omitempty"`
	// Holder is the session holding ?target=, listening or not, to send a
	// flag to with to.
	Holder *FlagRecipient `json:"holder,omitempty"`
}

FlagListenersResponse is GET /api/flags/listeners: who would hear a flag raised now, and who holds the target.

type FlagRecipient added in v0.2.0

type FlagRecipient struct {
	Agent   string `json:"agent,omitempty"`
	Session string `json:"session,omitempty"`
	// T3Thread is a T3 thread's id, as /api/flags/destinations lists it.
	T3Thread string `json:"t3Thread,omitempty"`
	// T3Project starts a new thread in that T3 project.
	T3Project string `json:"t3Project,omitempty"`
	// Command runs that program from destinations.json.
	Command string `json:"command,omitempty"`
	// Webhook posts to that webhook from destinations.json.
	Webhook string `json:"webhook,omitempty"`
}

FlagRecipient is who a flag was sent to: a loupe mcp session by its agent and session names, or a T3 Code thread, or a new thread in a T3 project from the t3Projects setting, or a command or webhook from destinations.json by its name. Exactly one of these.

func (*FlagRecipient) External added in v0.2.0

func (r *FlagRecipient) External() string

External names r for an agent that was not sent the flag.

func (*FlagRecipient) IsExternal added in v0.2.0

func (r *FlagRecipient) IsExternal() bool

IsExternal reports whether the server delivers to r itself, rather than a loupe mcp session reading it.

func (*FlagRecipient) IsT3 added in v0.2.0

func (r *FlagRecipient) IsT3() bool

IsT3 reports whether r is a T3 thread or project rather than a session.

type FlagRect added in v0.2.0

type FlagRect struct {
	X      int `json:"x"`
	Y      int `json:"y"`
	Width  int `json:"width"`
	Height int `json:"height"`
}

FlagRect is a region in device pixels, as /api/ui reports them.

type FlagRequest added in v0.2.0

type FlagRequest struct {
	// Note is what the person typed, if anything.
	Note string `json:"note,omitempty"`
	// Region is what the person marked, as fractions of the screen:
	// [left, top, right, bottom], each in [0, 1]. Absent marks the whole
	// screen.
	Region []float64 `json:"region,omitempty"`
	// Watch keeps the flag open until POST /api/flags/end, collecting the
	// person's input in between.
	Watch bool `json:"watch,omitempty"`
	// Kind is empty, or "interrupt": the person is stopping an agent that
	// is driving. It is pushed at once, before the person has written
	// anything, and stays open like a watch: the posting viewer holds the
	// target until POST /api/flags/end, which may carry the note and region.
	Kind string `json:"kind,omitempty"`
	// To sends the flag to one session, as GET /api/flags/listeners names
	// it: loupe mcp pushes it to that session only, and an interrupt stops
	// that session rather than the claim's holder. Absent sends it to all.
	To *FlagRecipient `json:"to,omitempty"`
}

FlagRequest is POST /api/flags's body.

type FlagSnapshot added in v0.2.0

type FlagSnapshot struct {
	T int64 `json:"t"` // unix milliseconds
	// Screenshot is the path of the PNG, the region outlined in red;
	// empty when the capture failed, and ScreenshotError says why.
	Screenshot      string `json:"screenshot,omitempty"`
	ScreenshotError string `json:"screenshotError,omitempty"`
	// UI is the interactive tree, as /api/ui?interactive=1 returns it. Only
	// GET /api/flags?id= carries it; a list leaves it out.
	UI      []*target.Node `json:"ui,omitempty"`
	UIError string         `json:"uiError,omitempty"`
}

FlagSnapshot is the screen at one moment of a flag.

type FlagsResponse added in v0.2.0

type FlagsResponse struct {
	// Rev is the newest revision on the server; pass it as ?after= to wait
	// for the next change.
	Rev   uint64 `json:"rev"`
	Flags []Flag `json:"flags"`
}

FlagsResponse is GET /api/flags's list.

type HandoffResponse

type HandoffResponse struct {
	URL string `json:"url"`
}

HandoffResponse is GET /api/handoff's body.

type HandsOffResponse

type HandsOffResponse struct {
	Target   string `json:"target"`
	HandsOff bool   `json:"handsOff"`
	Warning  string `json:"warning,omitempty"`
}

HandsOffResponse is POST /api/devices/handsoff's 200. Warning is set when the change took effect but could not be saved.

type InputRequest

type InputRequest struct {
	Action string `json:"action"`
	X      int    `json:"x,omitempty"`
	Y      int    `json:"y,omitempty"`
	X2     int    `json:"x2,omitempty"`
	Y2     int    `json:"y2,omitempty"`
	// Scale is the pinch action's zoom: above 1 spreads two fingers apart,
	// below 1 brings them together. See target.Simulator.Pinch for the
	// spreads it becomes.
	Scale float64 `json:"scale,omitempty"`
	// Ms is the swipe or pinch duration. Zero takes the default; a swipe that is too
	// fast is read as a fling and scrolls further than asked.
	Ms      int    `json:"ms,omitempty"`
	Text    string `json:"text,omitempty"`
	Keycode int    `json:"keycode,omitempty"`
	// To is the rotate action's target, 0..3 quarter turns. Nil means "the
	// next one": handleInput reads the current rotation and adds one, mod 4,
	// which is what a rotate button with no state of its own needs to cycle
	// the display. A pointer so an explicit 0 (back to portrait) is
	// distinguishable from "not given" -- a plain int could not tell those
	// apart.
	To *int `json:"to,omitempty"`
	// Button names a device button for the "button" action -- see
	// target.ButtonKeycode. Distinct from Keycode/"key": a button press names
	// what it presses, not a raw code, so an iOS target could resolve the
	// same name to its own HID event.
	Button string `json:"button,omitempty"`
	// On is the hardwareKeyboard action's direction: true connects a
	// hardware keyboard, which hides the target's on-screen one. A pointer
	// so a missing field is told apart from an explicit false.
	On *bool `json:"on,omitempty"`
	// Package is the launch action's app: an Android package name, or an
	// iOS simulator's bundle ID.
	Package string `json:"package,omitempty"`
	// Activity is the launch action's Android activity, qualified or
	// starting with "."; empty opens the launcher activity.
	Activity string `json:"activity,omitempty"`
	// URL is the openURL action's link, handed to whatever the device has
	// registered for it. Only its scheme and host are traced.
	URL string `json:"url,omitempty"`
	// Match is a tap's node, named by its id, text or desc instead of a
	// point. handleInput dumps the view hierarchy, taps the one node it
	// names at its center, and answers with that node. See InputMatchFields.
	Match *target.Match `json:"match,omitempty"`
}

InputRequest is one action in device pixels, the same space /api/ui reports. Action is the only field with no omitempty, but it is not the only one handleInput requires: which of X/Y/X2/Y2/Text/Keycode/Button are required depends on Action, and handleInput checks their presence in the decoded JSON body, not their Go zero value here (see validateInputRequest and InputRequiredFields) -- x=0 and keycode=0 are both values a caller can legitimately mean, and a struct field alone cannot distinguish "sent 0" from "omitted". Every field still defaults to its Go zero value when the action does not require it (a "tap" with no Ms/Text/Keycode is exactly as valid as one that sends them and gets zeros back), which is why they keep omitempty regardless. apischema builds POST /api/input's request schema as a oneOf, one variant per InputActions entry with InputRequiredFields[action] required, so a generated client sees this as a sealed type rather than one flat object with everything optional.

type InputResponse added in v0.2.0

type InputResponse struct {
	OK      bool         `json:"ok"`
	Matched *target.Node `json:"matched,omitempty"`
}

InputResponse is POST /api/input's 200. Matched is the node a tap with a match landed on, without its children, so a caller can see what it hit.

type InstallResponse

type InstallResponse struct {
	Target string `json:"target"`
	OK     bool   `json:"ok"`
	Output string `json:"output"`
	Code   string `json:"code,omitempty"`
	Reason string `json:"reason,omitempty"`
	Bytes  int64  `json:"bytes"`
	TookMs int64  `json:"tookMs"`
	// Package is the installed app's package name, read from the APK with
	// aapt2, or ?package= when aapt2 could not read it. Empty when neither
	// gave one; PackageError then says why.
	Package      string `json:"package,omitempty"`
	PackageError string `json:"packageError,omitempty"`
	// Launch is present when ?launch=1 asked to open the app. It is a
	// separate verdict: the install above stands whatever it says.
	Launch *LaunchResponse `json:"launch,omitempty"`
}

InstallResponse is what POST /api/install answers, on success (200) and when the package manager refused the APK (422). Output is adb's own text either way. Code is the INSTALL_FAILED_* reason, which is what a caller branches on; it is empty on success.

type LaunchResponse

type LaunchResponse struct {
	OK           bool   `json:"ok"`
	Activity     string `json:"activity,omitempty"`
	Error        string `json:"error,omitempty"`
	Code         string `json:"code,omitempty"`
	RetryAfterMs int64  `json:"retryAfterMs,omitempty"`
	TookMs       int64  `json:"tookMs"`
}

LaunchResponse is the outcome of ?launch=1 on /api/install. Code is notInstalled, noLaunchActivity or humanHeld when it is one of those.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager owns the set of known targets and the sessions running against them.

func NewManager

func NewManager(opts target.Options) *Manager

NewManager builds an empty manager with the given default stream options.

func (*Manager) AVDNames

func (m *Manager) AVDNames() []string

AVDNames lists the AVDs registered as targets, running or not.

func (*Manager) Acquire

func (m *Manager) Acquire(ctx context.Context, targetID string) (*session.Session, error)

Acquire returns the session for a target, starting one if needed. Every successful Acquire must be paired with a Release.

func (*Manager) AdaptiveBitRate

func (m *Manager) AdaptiveBitRate() bool

AdaptiveBitRate reports whether new sessions run the bitrate controller.

func (*Manager) AllStats

func (m *Manager) AllStats() []map[string]any

AllStats returns the live counters for every running session.

func (*Manager) ClearEnded

func (m *Manager) ClearEnded(id string, armed time.Time)

ClearEnded lifts the refusal EndSession armed, but only if armed is still the entry there: a later EndSession's guard is not this caller's to lift. A shut down or delete that failed left the device up, and "Start it" must reach it at once.

func (*Manager) ClearShutDown

func (m *Manager) ClearShutDown(id string)

ClearShutDown lifts the reopen guard for an explicit Start, but only when the target was shut down: a deleted target stays refused, and so does one whose shutdown is still running. The guard stops automatic reconnects; a person pressing Start is not one.

func (*Manager) EndSession

func (m *Manager) EndSession(id, reason string) time.Time

EndSession tells the viewers of one target's session why it is ending, then closes it. The target stays registered. A target with no session is a no-op.

For "shutDown" and "deleted" it arms the reopen guard and returns its token. The guard refuses every open until the caller reports the outcome: FinishEnded when the device went down, which starts shutDownGrace, or ClearEnded when it did not. Any other reason returns the zero time.

func (*Manager) FinishEnded

func (m *Manager) FinishEnded(id string, armed time.Time)

FinishEnded reports that the shutdown EndSession armed armed for has returned, so the guard expires shutDownGrace from now rather than from the request's start. A later EndSession's guard is left alone.

func (*Manager) HasViewer

func (m *Manager) HasViewer(id uint64) bool

HasViewer reports whether id is attached to any session now. The picker's actions on one target carry the viewer id of the session open on another, and claims and hands-off must not count that person as an agent.

func (*Manager) Info

func (m *Manager) Info(ctx context.Context, id string) (TargetInfo, bool)

Info returns the picker's row for one target.

func (*Manager) LocalTargets

func (m *Manager) LocalTargets(ctx context.Context) []TargetInfo

LocalTargets is Targets without the peers' rows: what GET /api/targets answers a hub that polls it with ?local=1, so two servers that peer with each other list one another's devices once.

func (*Manager) Options

func (m *Manager) Options() target.Options

Options returns the stream options new sessions will be opened with.

func (*Manager) PauseIdleEmulators

func (m *Manager) PauseIdleEmulators(ctx context.Context)

PauseIdleEmulators pauses idle headless emulators, and shuts down ones idle for longer, until ctx ends.

func (*Manager) Register

func (m *Manager) Register(t target.Target)

Register adds or replaces a target.

func (*Manager) RegisterScanned

func (m *Manager) RegisterScanned(t target.Target, scannedAt time.Time) bool

RegisterScanned registers t unless its id is already a target, or Unregister forgot it after scannedAt, when the scan that found it began. It reports whether t was registered.

func (*Manager) Registered added in v0.2.0

func (m *Manager) Registered(id string) bool

Registered reports whether id is a registered target. Unlike Target it never rescans the AVD directory, so the rescan itself may call it.

func (*Manager) Release

func (m *Manager) Release(targetID string)

Release signals that a viewer has left. When the last one goes and no hold is outstanding (see session.Hold), the session is scheduled for teardown after the idle grace period. A hold counts as a viewer here and in the reaper.

func (*Manager) RescanAVDs added in v0.2.0

func (m *Manager) RescanAVDs() bool

RescanAVDs looks for AVDs created outside loupe, at most once per avdRescanEvery. It reports whether it scanned.

func (*Manager) Session

func (m *Manager) Session(id string) (*session.Session, bool)

Session looks up the running session for a target, if one exists. Unlike Acquire it never opens a device: a target with no viewers and no one driving it through /api/input has nothing to report, which is not an error -- GET /api/events reads this and answers an empty list rather than 404. It can also return a session that has already ended but is still waiting out idleGrace before the reaper deletes it from m.sessions; reading its ring is harmless, since EventsAfter and EventsSince both work off state that Close does not touch.

func (*Manager) SetADBDown

func (m *Manager) SetADBDown(reason string)

SetADBDown records that adb has stopped answering, and why, or with "" that it answers again. A target already streaming keeps its session: the scrcpy server it runs has its own forwarded socket and does not need adb to go on.

func (*Manager) SetAVDRescan added in v0.2.0

func (m *Manager) SetAVDRescan(f func())

SetAVDRescan sets the function that re-reads the AVD directory and registers what is new.

func (*Manager) SetAdaptiveBitRate

func (m *Manager) SetAdaptiveBitRate(on bool)

SetAdaptiveBitRate turns the bitrate controller on or off for sessions opened from now on. Like the stream options it does not reach a session that is already running, which is why the settings API reports it as applying next session.

func (*Manager) SetClaimed added in v0.2.0

func (m *Manager) SetClaimed(f func(id string) bool)

SetClaimed sets the check for a live claim on a target.

func (*Manager) SetClientBuffer

func (m *Manager) SetClientBuffer(ms int)

SetClientBuffer sets the jitter-buffer ceiling new sessions report to their viewers. Sessions already open keep the value they were built with, for the same reason SetOptions does: init is cached per session.

func (*Manager) SetClipShare added in v0.2.0

func (m *Manager) SetClipShare(s *clipshare.Service)

SetClipShare joins every local session to the shared clipboard: a device copy is published from the session, and each shared change is written to every other target with a live session. Call it before any session opens; one opened earlier does not feed it.

func (*Manager) SetEmulatorPause

func (m *Manager) SetEmulatorPause(d time.Duration)

SetEmulatorPause sets how long a headless emulator goes unused before it is paused, or 0 for never. The loop reads it on each pass, so it applies to emulators already running.

func (*Manager) SetEmulatorShutdown

func (m *Manager) SetEmulatorShutdown(d time.Duration)

SetEmulatorShutdown sets how long a headless emulator goes unused before it is shut down, or 0 for never. Like the pause, it applies at once.

func (*Manager) SetHumanHold

func (m *Manager) SetHumanHold(d time.Duration)

SetHumanHold sets how long a viewer's last input holds new sessions' targets against agents. Sessions already open keep the hold they opened with, like SetClientBuffer.

func (*Manager) SetIOSSimcap

func (m *Manager) SetIOSSimcap(bin string)

SetIOSSimcap names the simcap that streams physical iPhones, for devices already listed and those to come.

func (*Manager) SetOptions

func (m *Manager) SetOptions(o target.Options)

SetOptions replaces the options new sessions will be opened with.

Running sessions keep the options they were opened with. scrcpy takes its encoder settings at launch and offers no way to change them afterwards, so applying these to a live session would mean tearing it down and rebuilding it -- a visible interruption in exchange for a setting the user can get by reconnecting.

func (*Manager) SetPeerCaller

func (m *Manager) SetPeerCaller(c target.PeerCaller)

SetPeerCaller sets how a PeerTarget calls the owner's HTTP routes. Call it before SetPeerRows, like SetPeerDialer.

func (*Manager) SetPeerDialer

func (m *Manager) SetPeerDialer(d target.PeerDialer)

SetPeerDialer sets how a PeerTarget opens its stream. Call it before SetPeerRows: targets registered earlier keep the dialer they were made with.

func (*Manager) SetPeerRows

func (m *Manager) SetPeerRows(rows []TargetInfo)

SetPeerRows replaces the peers' rows with rows, whose ids are already "<server>/<owner id>", and registers a PeerTarget for each so the handlers' s.mgr.Target(id) resolves it. A row that has gone ends its session and is forgotten like a deleted device, so a viewer is told rather than left on a dead stream.

func (*Manager) SetSimulatorSlim

func (m *Manager) SetSimulatorSlim(on bool)

SetSimulatorSlim sets whether boots a simulator target starts from now on are slim (target/simslim.go). A simulator already booted keeps the services it booted with until it next boots.

func (*Manager) SetTrace

func (m *Manager) SetTrace(tr *trace.Writer)

SetTrace attaches a trace writer so session termination is recorded. Without it a stream that ends on its own is indistinguishable in the trace from one that is merely quiet: every counter freezes either way.

func (*Manager) SetXCRunner

func (m *Manager) SetXCRunner(dir string)

SetXCRunner names the built XCUITest runner's products directory, for devices already listed and those to come.

func (*Manager) Shutdown

func (m *Manager) Shutdown()

Shutdown closes every running session.

func (*Manager) SimulatorNames

func (m *Manager) SimulatorNames() []string

SimulatorNames lists the names of the simulators registered as targets, as of the last listing.

func (*Manager) SyncDevices

func (m *Manager) SyncDevices(devices []target.DeviceInfo, build func(target.DeviceInfo) target.Target)

SyncDevices brings the registered adb devices in line with what adb lists now. A new serial is registered through build; a known one whose state or model changed is rebuilt, since an ADBTarget keeps the state it was built with; one adb no longer lists is kept and marked "missing" rather than removed, so the picker can say where it went instead of it silently vanishing from under a viewer that had it selected.

An emulator is the exception. One whose AVD has a target -- devices carry the name once target.AVDResolver has read it -- is that target running, not a device of its own, so it is attached to the AVD rather than listed twice. An AVD adb no longer lists has stopped, and is detached so the next Open boots it again.

func (*Manager) SyncIOSDevices

func (m *Manager) SyncIOSDevices(devs []target.IOSDeviceInfo)

SyncIOSDevices brings the registered physical iOS devices in line with a devicectl listing. devicectl keeps a paired device listed while the Mac cannot reach it, so presence is "device" while it has a transport and "offline" while it does not, and a device it stops listing, unpaired, is kept and marked missing. A change of transport, cable to Wi-Fi or back, is traced, since it changes what the device can carry.

func (*Manager) SyncSimulators

func (m *Manager) SyncSimulators(sims []target.SimInfo, simcap string)

SyncSimulators brings the registered iOS simulators in line with a simctl listing. A new one is registered; a known one takes the fresh listing, so "Boots on open" follows a simulator booted or shut down from Xcode. One simctl no longer lists has been deleted and is dropped. A deleted simulator never comes back, and test runs create and delete them all day. One still being watched is kept and marked missing, so its viewer can say where it went, and is dropped by the first listing after its session ends.

func (*Manager) SyncSimulatorsAt

func (m *Manager) SyncSimulatorsAt(listedAt time.Time, sims []target.SimInfo, simcap string)

SyncSimulatorsAt is SyncSimulators for a listing whose simctl call began at listedAt. A listing that began before the one last applied is dropped: the 5s poll can start before `simctl create` returns and apply after the creator's own sync, and would mark the new simulator missing until the next poll.

func (*Manager) Target

func (m *Manager) Target(id string) (target.Target, bool)

Target looks up a registered target by id. It reports whether one exists rather than returning a nil interface, because a nil target.Target inside a non-nil interface value is not nil and the caller's check would pass.

func (*Manager) Targets

func (m *Manager) Targets(ctx context.Context) []TargetInfo

Targets lists everything registered, marking which already have a session.

Describing each target costs an adb call, so it happens outside m.mu and in parallel across targets -- collecting the snapshot under the lock and then releasing it before any of that work starts, so a slow device cannot block a concurrent Acquire or a second call to Targets. A target that only implements target.Target, not target.Describer (there are none today, but nothing requires there to be), is listed with its Description fields omitted rather than skipped.

The order is fixed -- devices, then physical iOS devices, then emulators, then simulators, then the pattern, each by ID -- because a client polling the list reads a new order as a changed list and rebuilds a picker the viewer may have open.

func (*Manager) Unregister

func (m *Manager) Unregister(id string)

Unregister ends a target's session as deleted and forgets the target. It marks the id gone, so a simctl listing or an AVD scan that began before now cannot register it again.

func (*Manager) WakeEmulator added in v0.2.0

func (m *Manager) WakeEmulator(ctx context.Context, id string)

WakeEmulator resumes the emulator behind id if it is paused and restarts its idle clock. It does nothing for any other target.

type MediaResponse

type MediaResponse struct {
	Target string `json:"target"`
	OK     bool   `json:"ok"`
	Name   string `json:"name"`
	Kind   string `json:"kind"`
	Bytes  int64  `json:"bytes"`
	TookMs int64  `json:"tookMs"`
}

MediaResponse is what POST /api/media answers on success.

type NamedDestination added in v0.2.0

type NamedDestination struct {
	Name  string `json:"name"`
	Label string `json:"label"`
}

NamedDestination is a command or webhook a flag can be sent to.

type OKResponse

type OKResponse struct {
	OK bool `json:"ok"`
}

OKResponse is the body a handler sends when there is nothing to report but success -- /healthz and a successful /api/input action. Like ErrorResponse, this replaces an ad hoc map literal built at each call site so apischema has a named type to describe.

type Overlay

type Overlay struct {
	ID     string `json:"id"`
	Source string `json:"source"`
	Label  string `json:"label,omitempty"`
	// Image is the path to GET the image from, with the token left for the
	// client to add, or empty when the overlay has none. It changes with
	// every post, so a client may cache by it.
	Image string `json:"image,omitempty"`
	// Width and Height are the image's size in pixels, 0 without one.
	Width  int `json:"width,omitempty"`
	Height int `json:"height,omitempty"`
	// Rect is where the image goes, as fractions of the screen.
	Rect    [4]float64   `json:"rect"`
	Opacity float64      `json:"opacity"`
	Boxes   []OverlayBox `json:"boxes,omitempty"`
}

Overlay is one overlay as viewers and GET /api/overlays get it.

type OverlayBox

type OverlayBox struct {
	// Rect is [x1, y1, x2, y2] as fractions of the screen.
	Rect  [4]float64 `json:"rect"`
	Label string     `json:"label,omitempty"`
	Kind  string     `json:"kind,omitempty"`
}

OverlayBox is a box as viewers get it.

type OverlayBoxRequest

type OverlayBoxRequest struct {
	// Bounds is [x1, y1, x2, y2].
	Bounds [4]int `json:"bounds"`
	Label  string `json:"label,omitempty"`
	// Kind is a hint for how to draw it: "diff" (something that differs) or
	// "note". Clients draw any other value as a note.
	Kind string `json:"kind,omitempty"`
}

OverlayBoxRequest is one labelled rectangle, in the request's pixel space.

type OverlayDeleteResponse

type OverlayDeleteResponse struct {
	Removed int `json:"removed"`
}

OverlayDeleteResponse is DELETE /api/overlays's body.

type OverlayRequest

type OverlayRequest struct {
	// ID names the overlay. Posting an existing ID replaces it.
	ID string `json:"id"`
	// Source names the extension that posted it, for a client's label and
	// for DELETE ?source=.
	Source string `json:"source"`
	Label  string `json:"label,omitempty"`
	// Image is a base64 PNG or JPEG, or empty for boxes only.
	Image string `json:"image,omitempty"`
	// Screen is the [width, height] in pixels that Bounds and every box are
	// in. It defaults to the target's screen size, or failing that the
	// image's own size, which is right for an image the size of a screenshot.
	Screen *[2]int `json:"screen,omitempty"`
	// Bounds is where the image goes, [x1, y1, x2, y2]; the whole screen if
	// omitted.
	Bounds *[4]int `json:"bounds,omitempty"`
	// Opacity is the image's starting opacity, 0 to 1; 0.5 if omitted. A
	// client may let the person change it.
	Opacity *float64            `json:"opacity,omitempty"`
	Boxes   []OverlayBoxRequest `json:"boxes,omitempty"`
}

OverlayRequest is POST /api/overlays's body.

type OverlaysResponse

type OverlaysResponse struct {
	Overlays []Overlay `json:"overlays"`
}

OverlaysResponse is GET /api/overlays's body, and MsgOverlay's.

type PairRequest added in v0.2.0

type PairRequest struct {
	Code string `json:"code"`
	// Kind is browser, bearer or peer. A browser gets its session as a
	// cookie and a 204; the others get the token in the body.
	Kind  string `json:"kind"`
	Label string `json:"label,omitempty"`
}

PairRequest is POST /api/pair's body.

type PairResponse added in v0.2.0

type PairResponse struct {
	ID        string    `json:"id"`
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expiresAt"`
}

PairResponse is a bearer or peer session, returned once.

type PairingInfo added in v0.2.0

type PairingInfo struct {
	ID        string    `json:"id"`
	Target    []string  `json:"target,omitempty"`
	Label     string    `json:"label,omitempty"`
	CanPair   bool      `json:"canPair,omitempty"`
	Parent    string    `json:"parent"`
	CreatedAt time.Time `json:"createdAt"`
	ExpiresAt time.Time `json:"expiresAt"`
}

PairingInfo is a pending code as GET /api/pairings lists it, without the code.

type PairingRequest added in v0.2.0

type PairingRequest struct {
	// Target is the targets the paired device should open, carried to the
	// pairing link. Not secret, and not a restriction.
	Target []string `json:"target,omitempty"`
	// Label names the device the code is for. The redeemer's own label wins.
	Label string `json:"label,omitempty"`
	// CanPair lets the session the code is redeemed for mint codes itself.
	CanPair bool `json:"canPair,omitempty"`
}

PairingRequest is POST /api/pairings' body.

type PairingResponse added in v0.2.0

type PairingResponse struct {
	ID        string    `json:"id"`
	Code      string    `json:"code"`
	ExpiresAt time.Time `json:"expiresAt"`
}

PairingResponse is a freshly minted code. Code is returned here and never again.

type PutResponse

type PutResponse struct {
	Changed         []string      `json:"changed"`
	RestartRequired []string      `json:"restartRequired"`
	Pinned          []string      `json:"pinned"`
	Fields          []configField `json:"fields"`
}

type RecordListResponse

type RecordListResponse []RecordMeta

RecordListResponse is GET /api/record: every recording, newest first.

type RecordMeta

type RecordMeta = record.Meta

RecordMeta is one recording's metadata, in progress or finished.

type RecordStartResponse

type RecordStartResponse struct {
	ID string `json:"id"`
}

RecordStartResponse is POST /api/record's 201.

type RevokeResponse added in v0.2.0

type RevokeResponse struct {
	Revoked []string `json:"revoked"`
}

RevokeResponse lists the sessions a DELETE signed out, cascade included.

type Route

type Route struct {
	Method string
	Path   string
}

Route is one method+path pair Handler actually serves.

func Routes

func Routes() []Route

Routes returns every method+path pair Handler registers, in registration order, excluding "/" -- the catch-all that serves the static client bundle, not a JSON endpoint. It exists so a route-coverage test outside this package (apischema, which already imports httpapi for its response types) can walk the same table Handler itself registers from, keyed the same way its own endpoint entries are: by method and path together, not path alone.

type SequenceRequest added in v0.2.0

type SequenceRequest struct {
	Steps []InputRequest `json:"steps"`
}

SequenceRequest is POST /api/sequence's body: the steps to run in order, each exactly what POST /api/input would take.

type SequenceResponse added in v0.2.0

type SequenceResponse struct {
	OK     bool           `json:"ok"`
	Failed *int           `json:"failed,omitempty"`
	Error  string         `json:"error,omitempty"`
	Code   string         `json:"code,omitempty"`
	Steps  []SequenceStep `json:"steps"`
}

SequenceResponse answers POST /api/sequence. OK is true when every step returned 200. Otherwise Failed is the index of the step that did not, the response carries that step's status, Steps stops at it, and Error and Code repeat its own, so a caller that keys on a code (humanHeld, claimedBy) reads it where it would for a single input.

type SequenceStep added in v0.2.0

type SequenceStep struct {
	Status int             `json:"status"`
	Body   json.RawMessage `json:"body,omitempty"`
}

SequenceStep is one step's answer: its POST /api/input status and body.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server wires the manager to HTTP routes and serves the browser client.

func NewServer

func NewServer(mgr *Manager, web fs.FS, tracer *trace.Writer) *Server

NewServer builds the HTTP handler set. web is the filesystem holding the browser client, normally an embedded one. tracer may be nil.

func (*Server) Build

func (s *Server) Build() string

Build returns the content hash of the client assets.

func (*Server) EnableWebTransport

func (s *Server) EnableWebTransport(wt *webtransport.Server)

EnableWebTransport attaches the HTTP/3 server that upgrades WebTransport sessions. Without it the /wt endpoint reports 404 and clients use WebSocket.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the configured mux.

Every route's methods list is enforced here, centrally, before its handler ever runs -- net/http's ServeMux routes on the path alone, so without this a route table entry naming only GET would still answer a PUT with whatever the handler happened to do (nothing, for most of them: several never checked r.Method at all). Adding a method to a route's list without a handler branch for it is therefore not silently permissive.

func (*Server) KeepAwake

func (s *Server) KeepAwake(k *awake.Keeper)

KeepAwake attaches the keeper that holds off idle sleep while loupe is in use.

func (*Server) ServeQUIC

func (s *Server) ServeQUIC(qc *quic.Conn)

ServeQUIC runs one connection that negotiated session.QUICALPN. It returns when the viewer ends.

func (*Server) SetAAPT2

func (s *Server) SetAAPT2(path string)

SetAAPT2 gives /api/install the aapt2 binary it reads package names with. Empty leaves the name to ?package=.

func (*Server) SetAVDCreator

func (s *Server) SetAVDCreator(c *AVDCreator)

SetAVDCreator enables /api/avds. Nil leaves both routes answering 404. The creator shares its one-at-a-time slot with the DeviceCreator, whichever is set first.

func (*Server) SetClaimsPath added in v0.2.0

func (s *Server) SetClaimsPath(path string) error

SetClaimsPath loads the claims from path and keeps them there.

func (*Server) SetClipShare added in v0.2.0

func (s *Server) SetClipShare(c *clipshare.Service)

SetClipShare serves c on /api/clipboard/shared and bridges it to every peer. Call it before SetPeers.

func (*Server) SetConfig

func (s *Server) SetConfig(store *ConfigStore)

SetConfig attaches a settings store. Without one, /api/config answers 404 rather than pretending to have settings it cannot persist.

func (*Server) SetDestinationsPath added in v0.2.0

func (s *Server) SetDestinationsPath(path string)

SetDestinationsPath names destinations.json, read on each use so an edit to it needs no restart.

func (*Server) SetDeviceCreator

func (s *Server) SetDeviceCreator(c *DeviceCreator)

SetDeviceCreator enables /api/devices. Nil leaves both routes answering 404 (GET /api/devices/options still answers, if the android CLI is there, with profilesFallback). The creator shares its slot with the AVDCreator.

func (*Server) SetHandoffURL

func (s *Server) SetHandoffURL(u string)

SetHandoffURL sets the link another device can open: the startup banner's phone link, whose host the TLS certificate covers. Empty turns /api/handoff off.

func (*Server) SetHandsOffPath

func (s *Server) SetHandsOffPath(path string) error

SetHandsOffPath loads the hands-off set from path and keeps it there.

func (*Server) SetPeers

func (s *Server) SetPeers(reg *peer.Registry)

SetPeers attaches the peer registry and keeps this server's merged rows in step with it: every poll, add and remove re-merges.

func (*Server) SetRecordings

func (s *Server) SetRecordings(st *record.Store)

SetRecordings gives /api/record its store. Without one both record routes answer 501.

func (*Server) SetSessionsPath added in v0.2.0

func (s *Server) SetSessionsPath(path string) error

SetSessionsPath loads the session store from path and keeps it there. An unreadable file leaves pairing off rather than starting empty, since the first write would then sign every device out; the master token still works.

func (*Server) SetToken

func (s *Server) SetToken(t string)

SetToken enables authentication. An empty token disables it, which is what -no-auth does; the warning belongs at startup, not here.

type ServerAddRequest

type ServerAddRequest struct {
	Name        string `json:"name,omitempty"`
	URL         string `json:"url"`
	Token       string `json:"token"`
	Fingerprint string `json:"fingerprint,omitempty"`
}

ServerAddRequest is POST /api/servers' body. Name is optional and is derived from the host when empty. Fingerprint repeats the one a 409 confirmFingerprint answer carried, once the person has checked it; the peer's certificate is then pinned to it.

type ServerInfo

type ServerInfo struct {
	Name string `json:"name"`
	URL  string `json:"url"`
	// State is "up" while the last poll of the peer succeeded, else "down".
	State   string `json:"state"`
	Targets int    `json:"targets"`
	// RTTMs is how long the last successful poll took.
	RTTMs int64 `json:"rttMs"`
	// Warning is set on the add response when the owner answered over HTTP
	// but the QUIC probe could not confirm streaming works.
	Warning string `json:"warning,omitempty"`
}

ServerInfo is a peer as GET /api/servers shows it. It never carries the token.

type SessionInfo added in v0.2.0

type SessionInfo struct {
	ID         string     `json:"id"`
	Kind       string     `json:"kind"`
	Label      string     `json:"label,omitempty"`
	Parent     string     `json:"parent"`
	CanPair    bool       `json:"canPair,omitempty"`
	CreatedAt  time.Time  `json:"createdAt"`
	LastUsedAt time.Time  `json:"lastUsedAt"`
	ExpiresAt  time.Time  `json:"expiresAt"`
	RevokedAt  *time.Time `json:"revokedAt,omitempty"`
	UserAgent  string     `json:"userAgent,omitempty"`
	RemoteAddr string     `json:"remoteAddr,omitempty"`
	// Current marks the caller's own session.
	Current bool `json:"current,omitempty"`
}

SessionInfo is a session row without its hash.

type SettingsConflictResponse

type SettingsConflictResponse struct {
	Error       string            `json:"error"`
	Failed      []string          `json:"failed"`
	NotRestored []string          `json:"notRestored,omitempty"`
	Settings    *[]target.Setting `json:"settings,omitempty"`
}

SettingsConflictResponse is what a PUT returns when applying a change failed partway through and some settings had to be rolled back. Failed names the setting that failed and everything after it in table order, which never ran at all -- always an array, never omitted, because Failed carries no omitempty in the schema and there is always at least one name in it on this path (see putSettings). NotRestored, when present, names any already-applied setting whose rollback write itself failed -- best effort, not guaranteed.

Settings is a pointer, not a plain slice, because the field's presence and its value are two separate facts and only a pointer can carry both: the re-read after a rollback either succeeds, in which case the caller gets whatever ds.Settings() returned -- however that happens to marshal, [] or null included -- or it fails, in which case the key is absent entirely so a caller does not mistake "settings" was never read for "there are no settings". A plain []target.Setting with omitempty cannot make that distinction: encoding/json's omitempty drops an empty slice exactly the same way it drops a nil one, which would silently change what a caller already relying on the field's presence sees. See TestSettingsConflictResponseMatchesTheOldMapEncoding, which pins this against the map-literal encoding this type replaced.

type SettingsPutRequest

type SettingsPutRequest struct {
	Changes map[string]any `json:"changes"`
}

SettingsPutRequest carries only the settings the caller wants to change, the same "changes" shape /api/config uses, so a PUT never has to restate every field to change one of them.

type SettingsResponse

type SettingsResponse struct {
	Settings []target.Setting `json:"settings"`
}

SettingsResponse is what both GET and a successful PUT return: the full, freshly-read set of settings, the same shape /api/config uses so a caller never has to guess whether a write actually took. Settings carries no omitempty -- the schema promises an array -- so both callers that build one (getSettings and putSettings' success path) normalize a nil target.DeviceSettings.Settings result to [] before constructing it, the same null-array fix already made for handleUI's Nodes, PUT /api/config's changed and SettingsConflictResponse.Failed.

type SharedClipboardRequest added in v0.2.0

type SharedClipboardRequest struct {
	Text string `json:"text"`
	ID   string `json:"id,omitempty"`
	At   int64  `json:"at,omitempty"`
}

SharedClipboardRequest is POST /api/clipboard/shared's body. ID and At are optional and filled in by the server; a peer bridge sends both so the value keeps the identity it had where it was copied.

type T3Destinations added in v0.2.0

type T3Destinations struct {
	// Error says why T3 could not be asked, the CLI missing for one.
	Error    string          `json:"error,omitempty"`
	Projects []T3ProjectInfo `json:"projects"`
}

T3Destinations lists T3 Code's projects and threads.

type T3ProjectInfo added in v0.2.0

type T3ProjectInfo struct {
	Path    string         `json:"path"`
	Name    string         `json:"name"`
	Threads []T3ThreadInfo `json:"threads"`
	Error   string         `json:"error,omitempty"`
}

T3ProjectInfo is a configured project and its open threads.

type T3ThreadInfo added in v0.2.0

type T3ThreadInfo struct {
	ID       string `json:"id"`
	Title    string `json:"title"`
	Status   string `json:"status"`
	Provider string `json:"provider,omitempty"`
	Model    string `json:"model,omitempty"`
	// UpdatedAt is unix milliseconds.
	UpdatedAt int64 `json:"updatedAt"`
}

T3ThreadInfo is one thread a flag can be sent to.

type TargetInfo

type TargetInfo struct {
	ID     string `json:"id"`
	Kind   string `json:"kind"`
	Label  string `json:"label"`
	Active bool   `json:"active"`
	// BootsOnOpen is true for a registered AVD that ensureBooted has never
	// seen attached, so opening it will boot the emulator rather than join
	// something already running. Omitted (rather than false) for every target
	// that is not a target.Booter at all -- a device, a running emulator
	// already adopted as an ADBTarget, or synthetic -- since those never
	// boot anything on Open and "false" would otherwise be indistinguishable
	// from "not applicable".
	BootsOnOpen bool `json:"bootsOnOpen,omitempty"`
	// Serial is the adb serial a running AVD is attached as. A client that
	// saved the serial before AVDs had ids of their own matches on it.
	Serial string `json:"serial,omitempty"`
	// Headless is true for a running AVD whose emulator has no window on the
	// Mac, read from its qemu process, so it holds for one Android Studio
	// started too. Omitted for one with its window and for everything else.
	Headless bool `json:"headless,omitempty"`
	// Paused is true for a running AVD paused for being idle. The next open
	// or agent call resumes it.
	Paused bool `json:"paused,omitempty"`
	// Server names the peer that owns the target. Omitted for this server's
	// own rows. On a peer's row, ID is "<server>/<owner's id>" and every
	// other field is the owner's, apart from Active and LastError, which
	// are about sessions on this server.
	Server string `json:"server,omitempty"`
	target.Description

	// Available is false for a device adb cannot stream right now, and State
	// and Reason say why. State is adb's own word, or "missing".
	Available bool   `json:"available"`
	State     string `json:"state,omitempty"`
	Reason    string `json:"reason,omitempty"`
	// LastError is why the last attempt to open this target failed, if it did.
	LastError string `json:"lastError,omitempty"`

	// Claim is the agent that has claimed this target, if one has.
	Claim *ClaimInfo `json:"claim,omitempty"`
	// HandsOff is true when the person has marked the target off limits to
	// every agent.
	HandsOff bool `json:"handsOff,omitempty"`
	// DrivenBy names the agent whose input last went through on this target,
	// for 10s after it did, whether or not a session is open.
	DrivenBy string `json:"drivenBy,omitempty"`
}

TargetInfo is the JSON shape returned by the targets endpoint. Description is embedded rather than nested so its fields (os, osVersion, apiLevel, form) sit at the top level of the JSON; a target that cannot describe itself, or has not yet, simply omits them rather than guessing.

type UIResponse

type UIResponse struct {
	Target   string         `json:"target"`
	Width    int            `json:"width"`
	Height   int            `json:"height"`
	Rotation int            `json:"rotation"`
	Nodes    []*target.Node `json:"nodes"`
	// Composables and ComposeError are set only for ?compose=1. A compose
	// failure never fails the request: the uiautomator tree still comes
	// back, with ComposeError saying why it carries no names.
	Composables  []*composetree.Composable `json:"composables,omitempty"`
	ComposeError string                    `json:"composeError,omitempty"`
}

UIResponse is what /api/ui returns. Width and Height are on the wire because every coordinate below them is a device pixel, and a caller that wants to reason about a fraction of the screen cannot get there from the tree alone.

type WebhookFlag added in v0.2.0

type WebhookFlag struct {
	Flag Flag `json:"flag"`
	// Message is the flag as an agent would be sent it.
	Message string `json:"message"`
	// Start and End are PNGs, base64 in JSON; End only once a watch ended.
	Start []byte `json:"start,omitempty"`
	End   []byte `json:"end,omitempty"`
}

WebhookFlag is the body POSTed to a webhook. The screenshots travel in it because the receiver usually cannot reach this server.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL