> ## Documentation Index
> Fetch the complete documentation index at: https://docs.uplink.build/llms.txt
> Use this file to discover all available pages before exploring further.

# Invoking connector actions

> Connect accounts, refresh them in the background, and issue user tokens from your backend

Every unit of work a connector performs — "fetch Progressive policies", "list Strava activities", "grab the latest paystub" — is an **action**. The user grants your app a set of actions when they connect, and every later run must stay inside that grant.

There are two moments to invoke actions:

* **Connect** — the first time a user connects a connector. Creates the connection and grant, then runs the first actions.
* **Refresh** — later runs on an existing connection.

`UplinkConnect` handles both with the sign-in sheet and the on-device browser. You can run them in a blocking sheet or in the background.

## Blocking sheet

`UplinkConnect.present` connects and `UplinkConnect.run` refreshes. Each shows one sheet, runs every action in it in order, and returns after the user taps Done. Any failed action throws.

```swift theme={null}
// Connect: consent, sign-in, then the first actions.
let connected = try await UplinkConnect.present(
    from: viewController,
    client: client,
    connectorId: "@atomic/spotify",
    grantedActions: ["fetchAccount", "fetchLibrary"],
    runActions: ["fetchAccount", "fetchLibrary"],
    consumingAppName: "MyApp"
)

// Refresh the same connection later.
let refreshed = try await UplinkConnect.run(
    from: viewController,
    client: client,
    connectorId: "@atomic/spotify",
    connectionId: connected.connectionId,
    actions: ["fetchAccount"],
    consumingAppName: "MyApp"
)

for actionResult in refreshed.actionResults {
    print(actionResult.action, actionResult.snapshot.status)
}
```

**Parameters:**

* `connectorId` — the catalog connector id, e.g. `"@atomic/spotify"`.
* `grantedActions` — every action your app wants scope for, not just the ones you run now. The grant is fixed at connect time; adding actions later means connecting again.
* `runAction` / `runActions` — what to run on connect, in order. Omit both and the first granted action runs.
* `actions` — what to run on refresh. Must be non-empty and inside the grant; otherwise nothing starts.
* `input` — optional input for a single action, e.g. `["limit": 20]`.
* `versionRef` — optional. Pins a bundle version; omit it to use the connector's current version.
* `consumingAppName` — your app's name, shown on the consent screen.

Don't loop `run` per action: each call is its own session and its own sign-in. Pass all the actions to one call.

`UplinkConnect.presentPicker` is a variant of `present` that lists the catalog first and asks you for the grant once the user picks a connector.

## Background runs

`UplinkRunTracker` runs connects and refreshes in the background, so people keep using your app while sign-in and data pulls finish. A floating pill shows runs in progress; a run that needs the user to sign in again turns amber and waits for a tap.

```swift theme={null}
import SwiftUI
import UplinkConnect
import UplinkUI

// Once, at app start.
let tracker = UplinkRunTracker(client: client, consumingAppName: "MyApp")
tracker.onCompleted = { result in
    // Called once for every run that succeeds, wherever it started.
    save(result)
}

// Once, at the root of your view hierarchy.
RootView().uplinkRuns(tracker)
```

Connect with a picker, or with a connector you already know:

```swift theme={null}
// Picker → consent → sign-in. The sheet closes itself after sign-in;
// the run continues in the background.
// Returning nil cancels the flow.
tracker.connect(from: viewController) { detail in
    guard !detail.defaultActions.isEmpty else { return nil }
    return UplinkConnectRunConfig(
        grantedActions: detail.defaultActions,
        runActions: detail.defaultActions
    )
}

// Or skip the picker.
await tracker.connect(
    from: viewController,
    connectorId: "@atomic/progressive",
    config: UplinkConnectRunConfig(grantedActions: ["fetchAll"], runAction: "fetchAll")
)
```

Refresh an existing connection. If a run for that connection is already in flight, you get that run back:

```swift theme={null}
let run = await tracker.refresh(
    connectorId: "@atomic/progressive",
    connectionId: connectionId,
    actions: ["fetchAll"]
)
```

Each `UplinkRun` is `@Observable`. Read `phase` (`.starting`, `.connecting`, `.needsSignIn`, `.running`, `.succeeded`, `.failed`), `stepText`, and `result`, or drop in the SDK's views:

```swift theme={null}
struct ConnectionRow: View {
    let connectionId: String
    let tracker: UplinkRunTracker

    var body: some View {
        VStack(alignment: .leading) {
            if let run = tracker.run(forConnection: connectionId) {
                UplinkRunStatusLine(run: run)
                UplinkRunProgressBar(run: run)
                UplinkRunSignInChip(run: run, tracker: tracker)
            }
        }
        // Keep this run out of the floating pill while the row is on screen.
        .uplinkRunShown(connectionId, in: tracker)
    }
}
```

`await tracker.cancel(run)` stops a run on the server, `tracker.retry(run)` restarts a failed one, and `tracker.dismiss(run)` clears a finished one.

## Which actions to run

Each action on a connector can carry a `schedule`:

```json theme={null}
{
  "name": "fetchAccount",
  "schedule": { "onConnect": true, "refresh": "24h" }
}
```

* `schedule.onConnect: true` — the connector author suggests running this action when a user connects.
* `schedule.refresh` — a free-form hint (`"1h"`, `"24h"`, `"manual"`) for how quickly the action's data goes stale. Your app decides whether to honor it.

The catalog rolls these up into `defaultActions` on each connector: the actions with `onConnect: true`, in order. It can be empty, and `run` requires at least one action, so check first:

```swift theme={null}
let actions = row.connector.defaultActions
if !actions.isEmpty {
    await tracker.refresh(
        connectorId: row.connection.connectorId,
        connectionId: row.connection.id,
        actions: actions
    )
}
```

`defaultActions` is a hint. A billing-only app can run just `fetchAccount` even if the connector suggests more.

## Listing and deleting connections

```swift theme={null}
// Every connection the signed-in user has in your project.
let rows = try await client.connectors.listConnections()
for row in rows {
    print(row.connector.displayName, row.connection.id, row.grants.count)
}

// Delete a connection. Grants and invocations cascade.
try await client.connectors.deleteConnection(id: connectionId)
```

Each `ConnectionWithGrants` carries the `connection`, its `grants`, and the `connector`'s catalog entry, including `defaultActions` and `produces`.

To browse the catalog yourself, `client.connectors.list(tag:search:)` returns `[ConnectorListItem]` and `client.connectors.detail(id:)` returns a `ConnectorDetail` with each action's `permissionDescription`.

## Build your own flow

`UplinkConnect` is built on `UplinkUI` and the [Native iOS SDK](https://docs.uplink.build/api-reference/ios.md). To build your own UI, call the API directly and attach a device worker to the returned session yourself. Without a worker, the connector has no browser to run in and the invocation never progresses.

```swift theme={null}
import UIKit
import Uplink
import UplinkUI

@MainActor
func connectHeadless(from viewController: UIViewController) async throws {
    // 1. Create the connection and start its first actions.
    let started = try await client.connectors.quickstart(
        connectorId: "@atomic/progressive",
        grantedActions: ["fetchAll"],
        runAction: "fetchAll"
    )

    // 2. Attach an on-device browser to the run's session.
    let worker = await Worker(controller: viewController)
    try await worker.connect(session: started.sessionUrl)
    Task { await worker.accept() }

    // 3. Wait for every invocation, in order.
    let ids = started.invocations?.map(\.invocationId) ?? [started.invocationId]
    for id in ids {
        let handle = client.connectors.observe(invocationId: id)
        let status = await handle.awaitTerminal()
        print(id, status, handle.output.map { String(decoding: $0, as: UTF8.self) } ?? "")
    }

    // 4. Release the browser.
    await worker.close()
}
```

* `quickstart` creates the connection and starts the first actions in one call. If the run can't start, the connection is rolled back — a throw means nothing persisted. Failures after the run starts are **not** rolled back; delete the connection yourself if a failed first fetch means "not connected" in your app.
* `run(connectionId:actions:)` starts actions on an existing connection, all on one session.
* Both return a `sessionUrl` to attach the worker to, and `invocations` in action order.
* `cancelRun(sessionId:)` cancels every invocation on a session.

The worker hosts the connector's browser in `viewController`, which is where the user signs in. Keep a strong reference to it until the run ends. See [Displaying invocation state](https://docs.uplink.build/connectors-ios/invocation-state.md) for tracking sign-in and progress.

## User tokens

`UplinkClient` calls the Uplink Connectors service directly. Every request carries a short-lived **user token** for the signed-in end user, which your backend requests from Uplink. Your OAuth client secret never leaves your backend.

Your backend needs one endpoint that:

1. Authenticates the request against your own IdP (Supabase, Auth0, Clerk, Firebase, custom OIDC).
2. Exchanges that user's id for a user token at Uplink's `/oauth/token`, authenticated with an OAuth client that is pinned to your project and has the `sessions:write` scope.
3. Returns the token to the app.

```bash theme={null}
curl -u "$UPLINK_CLIENT_ID:$UPLINK_CLIENT_SECRET" https://api.uplink.build/oauth/token \
  -d grant_type=urn:ietf:params:oauth:grant-type:token-exchange \
  -d subject_token_type=urn:uplink:params:oauth:token-type:user-id \
  -d subject_token="$YOUR_USER_ID"
# → { "access_token": "…", "expires_in": 3600, … }
```

Return `access_token` from `userTokenProvider`. The token is bound to that user and your project for an hour and carries no scopes, so the app can only act as that user through Connectors.

## What's next

> [card] [Displaying invocation state](https://docs.uplink.build/connectors-ios/invocation-state.md)
>
> Observe progress and sign-in state, and render a live stepper

> [card] [Semantic schemas](https://docs.uplink.build/connectors-ios/semantic-schemas.md)
>
> Decode output into vocabulary types


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.