AI Data Tasks¶
Show your users short AI data tasks inside your app, such as picking the better of two answers.
The SDK carries the task screens as one HTML page, ContributionPage.html(context). Your app shows
it in a WebView and answers four calls from it. The page fetches a task from the project the user
picked, shows the consent screen and the task, and sends the answer with a
proof that the SDK signs. Your app never sees the task,
the answer, the score or the proof.
When to use it¶
- Your app rewards its users for completing tasks, for example from an "Earn rewards" button
- DEA has projects open for your app
Prerequisites¶
- The SDK is installed and initialized with your
appIdandappKey. See the Quick Start and Accounts and keys. attest()answeredPASSED. DEA refuses a task request signed by a key it has not registered.- An app user id for each user. It is required: the project list and every task carry it as
publisherUserId. See App user ids. - An
android.webkit.WebViewwith JavaScript on.
How a task runs¶
| Step | Your app | The page |
|---|---|---|
| 1 | Lists the projects open to the user, and shows them in its own screen | |
| 2 | Opens a screen with a WebView, and loads the page for the picked project |
Asks for its boot values |
| 3 | Delivers the boot values | Fetches a task, and shows the consent screen when DEA asks for it, then the task |
| 4 | Answers the page's calls: ready, attest, signRequest, signContribution |
Sends the answer to DEA |
| 5 | Closes the screen when the outcome arrives | Posts one outcome |
Usage¶
1. List the projects¶
The page runs a task on one project, which the user picks first. The project list is not part of the page: your app requests it from DEA and shows it.
| Item | Value |
|---|---|
| Request | POST, to ContributionHosts.API_BASE followed by /api/tasks/projects |
| Headers | Content-Type: application/json, Accept: application/json, and X-App-Key with the SDK's appKey |
| Body | {"h_proof": "<signed request>"}, signed by signRequest(eventType = "projects", claims) |
| Claims to sign | publisher_user_id: your app user id. platform: android. sdk_version: SDK_VERSION |
Answer 200 |
{"projects": [...]}. Each project has project_id, name, pattern_id (the task type) and pattern_name. Show them in this order |
Answer 204 |
No project is open to this user |
| Another answer | Refused. The body's errorCode says why |
import ai.dea.base.ContributionHosts
import ai.dea.sdk.DeaSdk
import ai.dea.sdk.SDK_VERSION
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
/** The projects open to this user. Blocking: call it off the main thread. */
fun listProjects(userId: String): JSONArray {
val dea = DeaSdk.instance ?: throw IllegalStateException("the SDK is not initialized")
val proof = dea.signRequest(
eventType = "projects",
claims = mapOf(
"publisher_user_id" to userId,
"platform" to "android",
"sdk_version" to SDK_VERSION,
),
) ?: throw IOException("not signed: ${dea.lastRequestRefusal}")
val conn = URL(ContributionHosts.API_BASE + "/api/tasks/projects").openConnection() as HttpURLConnection
try {
conn.requestMethod = "POST"
conn.connectTimeout = 15_000
conn.readTimeout = 15_000
conn.doOutput = true
conn.setRequestProperty("Content-Type", "application/json")
conn.setRequestProperty("Accept", "application/json")
dea.appKey?.let { conn.setRequestProperty("X-App-Key", it) }
conn.outputStream.use { it.write(JSONObject().put("h_proof", proof).toString().toByteArray()) }
return when (val status = conn.responseCode) {
200 -> JSONObject(conn.inputStream.bufferedReader().use { it.readText() })
.optJSONArray("projects") ?: JSONArray()
204 -> JSONArray() // no project is open to this user
else -> throw IOException("refused $status: ${conn.errorStream?.bufferedReader()?.use { it.readText() }}")
}
} finally {
conn.disconnect()
}
}
2. Load the page¶
Load ContributionPage.html(context) into the WebView as a string, with
ContributionHosts.API_BASE as its base URL:
The base URL is required. The page hashes the task and the answer with Web Crypto, which works only
in a secure context, and it sends its requests to its own origin. With no base URL, or another one,
the page stops with PAGE_INSECURE, or DEA refuses its requests.
ContributionHosts holds the hosts this build of the SDK talks to. Your app passes them to the page
in the boot message:
| Constant | Boot value | What it is |
|---|---|---|
ContributionHosts.API_BASE |
apiBase |
DEA's API origin, and the page's base URL |
ContributionHosts.WIDGET_ORIGIN |
widgetOrigin |
The origin the task's widget is downloaded from |
ContributionHosts.MEDIA_ORIGIN |
mediaOrigin |
The origin of the task's images |
3. Install the bridge¶
The page and your app talk through two functions. Each takes one JSON object, as a string.
| Function | Direction | Who defines it |
|---|---|---|
window.deaHost.post(json) |
Page to app | Your app, before the page's own script runs |
window.deaPage.deliver(json) |
App to page | The page. Your app calls it with evaluateJavascript |
On Android:
- Add a JavaScript interface to the
WebViewwithaddJavascriptInterface. - Insert a
<script>that defineswindow.deaHostbefore the page's</head>. It calls the interface with a random key. Drop every message without that key: the interface is visible to every frame of the page, and only the page's own script has the key. - Let the
WebViewnavigate only toabout:,data:andContributionHosts.API_BASE.
The interface is called on a background thread. Call evaluateJavascript on the main thread.
4. Answer the page¶
| Message | Direction | What your app does |
|---|---|---|
{"t": "ready"} |
Page to app | Deliver the boot message. The page sends ready every 100 ms until the boot message arrives |
{"t": "boot", ...} |
App to page | Starts the first task. See the boot values below |
{"t": "call", "id", "method", "args"} |
Page to app | Deliver {"t": "result", "id", "value"} with the answer below, or {"t": "error", "id", "message"}. Answer each call within 30 seconds |
{"t": "event", "event"} |
Page to app | A step of the task. Nothing to answer |
{"t": "outcome", "outcome", "errorCode"} |
Page to app | The task ended. See How a task ends |
{"t": "start", "projectId"} |
App to page | Runs another task on the page, for example after submitted |
{"t": "close"} |
App to page | Ends the task on screen. The page posts closed |
The boot values:
| Field | Value |
|---|---|
appKey |
The SDK's appKey |
publisherUserId |
Your app user id |
projectId |
The project_id of the project the user picked |
apiBase |
ContributionHosts.API_BASE |
widgetOrigin |
ContributionHosts.WIDGET_ORIGIN |
mediaOrigin |
ContributionHosts.MEDIA_ORIGIN |
sdkVersion |
SDK_VERSION |
The four calls:
method |
args |
value to answer |
|---|---|---|
ready |
None | null, once the SDK is initialized |
attest |
None | {"verdict": "passed"}: the verdict of attest(), in lower case |
signRequest |
The claims to sign, with event_type |
The string that signRequest(eventType = event_type, claims) returns, or null |
signContribution |
item_id and artifact_hash |
{"tuple": {"h_proof": "<proof>"}}, from signRequest(eventType = "contribution", claims, scored = true) |
Sign the claims as the page sends them, without event_type, which goes in eventType. When the
claims carry platform and sdk_version, set them to android and SDK_VERSION. Add no claim:
DEA refuses a request with a claim the route does not take.
When signRequest returns null for signContribution, answer
{"reason": "<lastRequestRefusal>", "outcome": "refused"}. When lastRequestRefusal contains
-33, the session is not sufficient yet: add
"code": -33. The page then asks the user to take a moment with the task and shows it again.
attest() and signRequest() block: answer the calls off the main thread.
5. Run another task, or close¶
The page posts one outcome for each task. After submitted, deliver
{"t": "start", "projectId": "<the same project>"} to show another task on the same page. Use the
same project for every task until the user leaves the screen. After no_task, the project has
nothing left for this user: show the project list again.
Example¶
A task screen¶
This Activity loads the page, answers it and closes on the outcome. Start it with the user's app
user id and the project_id the user picked:
import ai.dea.base.ContributionHosts
import ai.dea.sdk.DeaSdk
import ai.dea.sdk.SDK_VERSION
import ai.dea.sdk.contribution.ContributionPage
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.webkit.JavascriptInterface
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import org.json.JSONObject
import java.util.UUID
import java.util.concurrent.Executors
/** One AI data task. Start it with the extras "userId" and "projectId". */
class TaskActivity : AppCompatActivity() {
private val key = UUID.randomUUID().toString() // only the page's own script has it
private val worker = Executors.newSingleThreadExecutor() // attest() and signRequest() block
private lateinit var web: WebView
private lateinit var userId: String
private lateinit var projectId: String
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
userId = requireNotNull(intent.getStringExtra("userId"))
projectId = requireNotNull(intent.getStringExtra("projectId"))
web = WebView(this)
web.settings.javaScriptEnabled = true
web.settings.domStorageEnabled = true
web.webViewClient = PageOnly()
web.addJavascriptInterface(Bridge(), "DeaHostChannel")
setContentView(web)
// The bridge, ahead of the page's own script.
val bridge = "<script>window.deaHost = { post: function (m) { " +
"DeaHostChannel.post(${JSONObject.quote(key)}, m); } };</script>"
val page = ContributionPage.html(this).replaceFirst("</head>", "$bridge</head>")
// The page, with the API origin as its base URL.
web.loadDataWithBaseURL(ContributionHosts.API_BASE, page, "text/html", "utf-8", null)
}
override fun onDestroy() {
web.destroy()
worker.shutdown()
super.onDestroy()
}
/** Page to app. Called on a background thread. */
private inner class Bridge {
@JavascriptInterface
fun post(from: String, message: String) {
if (from != key) return // not the page
val msg = runCatching { JSONObject(message) }.getOrNull() ?: return
when (msg.optString("t")) {
"ready" -> runOnUiThread { deliver(boot()) }
"call" -> worker.execute {
answer(msg.getInt("id"), msg.getString("method"), msg.optJSONObject("args"))
}
"outcome" -> runOnUiThread {
finished(msg.getString("outcome"), msg.optString("errorCode").ifEmpty { null })
}
}
}
}
private fun boot(): JSONObject = JSONObject()
.put("t", "boot")
.put("appKey", DeaSdk.instance?.appKey ?: JSONObject.NULL)
.put("publisherUserId", userId)
.put("projectId", projectId)
.put("apiBase", ContributionHosts.API_BASE)
.put("widgetOrigin", ContributionHosts.WIDGET_ORIGIN)
.put("mediaOrigin", ContributionHosts.MEDIA_ORIGIN)
.put("sdkVersion", SDK_VERSION)
/** The four calls. Runs on the worker thread. */
private fun answer(id: Int, method: String, args: JSONObject?) {
val dea = DeaSdk.instance
?: return reply(JSONObject().put("t", "error").put("id", id).put("message", "the SDK is not initialized"))
val value: Any = when (method) {
"ready" -> JSONObject.NULL
"attest" -> JSONObject().put("verdict", dea.attest().verdict.name.lowercase())
"signRequest" -> sign(dea, args?.optString("event_type").orEmpty(), args, scored = false)
?: JSONObject.NULL
"signContribution" -> {
val proof = sign(dea, "contribution", args, scored = true)
if (proof != null) {
JSONObject().put("tuple", JSONObject().put("h_proof", proof))
} else {
val why = dea.lastRequestRefusal ?: "nothing signed"
JSONObject().put("reason", why).put("outcome", "refused")
.apply { if ("-33" in why) put("code", -33) } // not sufficient yet
}
}
else -> return reply(JSONObject().put("t", "error").put("id", id).put("message", "no method $method"))
}
reply(JSONObject().put("t", "result").put("id", id).put("value", value))
}
/** Signs the claims the page sent, as sent. Only platform and sdk_version are the app's to set. */
private fun sign(dea: DeaSdk, eventType: String, args: JSONObject?, scored: Boolean): String? {
val claims = LinkedHashMap<String, Any?>()
args?.let { a -> a.keys().forEach { name -> if (name != "event_type") claims[name] = a.getString(name) } }
if ("platform" in claims) claims["platform"] = "android"
if ("sdk_version" in claims) claims["sdk_version"] = SDK_VERSION
return dea.signRequest(eventType = eventType, claims = claims, scored = scored)
}
private fun reply(message: JSONObject) = runOnUiThread { deliver(message) }
/** App to page. Main thread only. */
private fun deliver(message: JSONObject) {
val json = JSONObject.quote(message.toString())
web.evaluateJavascript("window.deaPage && window.deaPage.deliver($json);", null)
}
private fun finished(outcome: String, errorCode: String?) {
setResult(RESULT_OK, Intent().putExtra("outcome", outcome).putExtra("errorCode", errorCode))
finish()
}
/** The page and the task's frame only: nothing navigates away. */
private class PageOnly : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
val url = request.url
val page = "${url.scheme}://${url.authority}" == ContributionHosts.API_BASE
return !(page || url.scheme == "about" || url.scheme == "data")
}
}
}
Run listProjects off the main thread, show the projects, and start the screen with the one the
user picks. In the Activity that shows your project list:
private val task = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
val outcome = result.data?.getStringExtra("outcome") // null when the user left before the end
if (outcome == "no_task") showProjects() // the project has nothing left: list them again
}
private fun open(userId: String, picked: JSONObject) {
task.launch(
Intent(this, TaskActivity::class.java)
.putExtra("userId", userId)
.putExtra("projectId", picked.getString("project_id")),
)
}
showProjects stands for your own code. ActivityResultContracts is in
androidx.activity.result.contract.
How a task ends¶
The page posts exactly one outcome for each task. When the task ends on one of the page's own
screens (thank you, not sent, task unavailable), the outcome comes after the user taps "Back to the
app".
outcome |
What happened |
|---|---|
submitted |
DEA stored the answer |
consent_declined |
The user tapped "Not now" on the consent screen. Nothing was recorded or sent |
no_task |
The picked project has nothing left for this user. Show the project list again |
widget_unavailable |
The task's widget failed its origin or hash check. Nothing was sent |
not_sent |
The answer could not be sent: retries ran out, DEA refused it, or the session was not sufficient on three tries |
not_attested |
Your app answered attest with a verdict other than passed, the boot message has no appKey, or signRequest answered null. The task did not start |
closed |
Your app delivered close before the task ended |
error |
DEA refused the task or the consent, did not answer, or the page could not start. errorCode names the reason |
errorCode |
Why |
|---|---|
PAGE_NO_BOOT |
No boot message within 30 seconds. Your app hears it only when it receives the page's messages |
PAGE_NO_HOSTS |
The boot message has no apiBase, widgetOrigin or sdkVersion |
PAGE_INSECURE |
The page is not in a secure context: it was loaded without ContributionHosts.API_BASE as its base URL |
PAGE_ERROR |
The page failed while it started a task |
NETWORK |
DEA did not answer |
| Another value | DEA's own code, such as IDENTITY_MISMATCH |
The event messages come in this order: consent_required, task_shown, not_enough_signal (the
same task shows again), sending, and waiting_to_send (no answer from DEA yet, retrying).
Troubleshooting¶
| What you see | Why | What to do |
|---|---|---|
| After 30 seconds the page says "No host bridge is installed", and your app hears nothing | window.deaHost is not defined when the page runs, so the page cannot post to your app |
Insert the bridge script before </head> |
| After 30 seconds the page says "The app did not start this task", and your app hears nothing | Your app drops the page's messages, its outcome included | Add the interface before you load the page, and check its name and the key |
error with PAGE_NO_BOOT |
Your app hears the page, but does not answer ready with the boot message |
Deliver the boot message on every ready |
error with PAGE_INSECURE |
The page was loaded with no base URL or another one | Load it with loadDataWithBaseURL(ContributionHosts.API_BASE, ...) |
not_attested |
attest() did not answer PASSED, appKey is null, or signRequest returned null (read lastRequestRefusal) |
See Attest and Accounts and keys |
error with CLAIM_PROFILE |
A signed request carries a claim the route does not take, or an app user id that is empty or longer than 128 characters | Sign the claims as the page sends them, and change only platform and sdk_version |
error with IDENTITY_MISMATCH |
This device key is bound to another app user id | See App user ids |
not_sent soon after the user answers |
Your app answered signContribution with a refusal without "code": -33, or with that code three times |
Add "code": -33 when lastRequestRefusal contains -33, so the page shows the task again |
| The task ends 30 seconds after a call | Your app did not answer that call | Answer every call with a result or an error message |
API¶
| Member | Returns | Description |
|---|---|---|
ContributionPage.html(context) |
String |
The task page. Throws IOException when the page is missing from the SDK's assets |
ContributionHosts.API_BASE |
String |
DEA's API origin: the page's base URL, and the host of the project list |
ContributionHosts.WIDGET_ORIGIN |
String |
The origin of the task's widget. Boot value widgetOrigin |
ContributionHosts.MEDIA_ORIGIN |
String |
The origin of the task's images. Boot value mediaOrigin |
signRequest(eventType, claims, scored, sessionId) |
String? |
Signs a task request with the device key; null when nothing was signed. scored = true adds the session's score. Blocking |
lastRequestRefusal |
String? |
Why the last signRequest returned null |
attest() |
Attestation |
Registers the device key. Blocking. See Attest |
appKey |
String? |
Boot value appKey, and the X-App-Key header of the project list |
SDK_VERSION |
String |
Boot value sdkVersion, and the sdk_version claim |
ContributionPage is in ai.dea.sdk.contribution, ContributionHosts in ai.dea.base, and
SDK_VERSION in ai.dea.sdk.