picked 0.0.111-next.3 → 0.0.111-next.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/docs/explanation/app-authentication.md +178 -0
  3. package/docs/explanation/apps.md +169 -0
  4. package/docs/explanation/conditions-and-the-logic-engine.md +12 -2
  5. package/docs/explanation/feature-flag-allocation.md +5 -3
  6. package/docs/how-to/apps/add-a-page-to-the-dashboard.md +257 -0
  7. package/docs/how-to/apps/add-a-workflow-tool.md +199 -0
  8. package/docs/how-to/apps/add-an-mcp-server-to-an-app.md +210 -0
  9. package/docs/how-to/apps/connect-a-third-party-service-with-oauth.md +307 -0
  10. package/docs/how-to/apps/create-an-app-in-the-dashboard.md +162 -0
  11. package/docs/how-to/apps/deploy-an-app.md +201 -0
  12. package/docs/how-to/apps/develop-an-app-locally.md +152 -0
  13. package/docs/how-to/apps/host-an-app-on-vercel.md +226 -0
  14. package/docs/how-to/apps/install-an-app.md +116 -0
  15. package/docs/how-to/apps/link-to-an-installation-from-your-site.md +134 -0
  16. package/docs/how-to/apps/read-project-data-from-an-app.md +225 -0
  17. package/docs/how-to/apps/rotate-an-app-key.md +130 -0
  18. package/docs/how-to/apps/run-code-when-a-workspace-publishes.md +148 -0
  19. package/docs/how-to/apps/store-data-for-an-installation.md +230 -0
  20. package/docs/how-to/apps/test-an-app.md +359 -0
  21. package/docs/how-to/apps/upgrade-or-uninstall-an-app.md +97 -0
  22. package/docs/how-to/apps/use-an-app-tool-in-a-workflow.md +112 -0
  23. package/docs/index.md +6 -3
  24. package/docs/reference/apps/app-kit.md +811 -0
  25. package/docs/reference/apps/environment.md +116 -0
  26. package/docs/reference/apps/manifest.md +311 -0
  27. package/docs/reference/apps/protocol.md +497 -0
  28. package/docs/reference/dashboard/apps.md +504 -0
  29. package/docs/reference/dashboard/external-apis.md +5 -0
  30. package/docs/reference/dashboard/features.mdx +5 -5
  31. package/docs/reference/dashboard/labels.md +25 -8
  32. package/docs/reference/dashboard/lead-search.md +6 -6
  33. package/docs/reference/dashboard/reports.mdx +13 -5
  34. package/docs/reference/dashboard/workflow-tools.md +14 -0
  35. package/docs/reference/glossary.md +153 -140
  36. package/docs/reference/management-api/authentication.md +36 -27
  37. package/docs/reference/management-api/authorization-and-scopes.md +73 -21
  38. package/docs/reference/management-api/schema/api-key.md +10 -10
  39. package/docs/reference/management-api/schema/app.md +726 -0
  40. package/docs/reference/management-api/schema/auth.md +7 -7
  41. package/docs/reference/management-api/schema/common.md +54 -35
  42. package/docs/reference/management-api/schema/feature.md +1 -1
  43. package/docs/reference/management-api/schema/feedback.md +1 -1
  44. package/docs/reference/management-api/schema/index.md +35 -20
  45. package/docs/reference/management-api/schema/label.md +31 -8
  46. package/docs/reference/management-api/schema/organization.md +66 -66
  47. package/docs/reference/management-api/schema/project.md +5 -5
  48. package/docs/reference/management-api/schema/report.md +1 -1
  49. package/docs/reference/management-api/schema/shopify.md +19 -19
  50. package/docs/reference/management-api/schema/workflow.md +6 -1
  51. package/docs/reference/management-api/schema/workspace.md +2 -2
  52. package/docs/reference/sdk/analytics-events.md +42 -36
  53. package/docs/reference/sdk/conditions.md +3 -3
  54. package/docs/reference/sdk/fields.md +5 -4
  55. package/docs/reference/sdk/index.md +4 -4
  56. package/docs/reference/sdk/plugins/create-experience.md +11 -9
  57. package/docs/reference/sdk/plugins/hotjar.md +2 -2
  58. package/docs/reference/sdk/plugins/sentry.md +2 -2
  59. package/docs/reference/sdk/plugins/shopify.md +2 -2
  60. package/docs/reference/sdk/predicates.md +5 -5
  61. package/docs/reference/sdk/type-generation.md +24 -19
  62. package/docs/reference/tools/admin-api-client.md +15 -0
  63. package/docs/reference/tools/cli.md +192 -41
  64. package/docs/reference/tools/mcp.md +30 -9
  65. package/docs/tutorials/first-app.md +308 -0
  66. package/package.json +4 -4
  67. package/docs/explanation/how-pickedql-works.md +0 -76
  68. package/docs/how-to/analytics/index.md +0 -324
  69. package/docs/reference/management-api/schema/analytics.md +0 -75
  70. package/docs/reference/pickedql/data-sources.md +0 -174
  71. package/docs/reference/pickedql/dimensions.md +0 -103
  72. package/docs/reference/pickedql/filtering.md +0 -64
  73. package/docs/reference/pickedql/index.md +0 -18
  74. package/docs/reference/pickedql/schema.md +0 -172
  75. package/docs/reference/pickedql/virtual-functions.md +0 -248
@@ -0,0 +1,230 @@
1
+ ---
2
+ type: how-to
3
+ layout: docs
4
+ ---
5
+
6
+ # How to store data for an installation
7
+
8
+ This guide shows you how to keep data for one installation of your app in Picked. Each
9
+ installation owns a set of labels. Your server keeps settings, IDs and credentials there,
10
+ and needs no database of its own.
11
+
12
+ You need an app with a server that uses `@picked/app-kit`, and the private key of the app.
13
+ [Build and install your first app](/tutorials/first-app) makes these.
14
+
15
+ ## 1. Make an installation client
16
+
17
+ Each label operation goes through an installation client. Make the client from the request
18
+ that your server answers:
19
+
20
+ | Request | Client |
21
+ | ---------------------------------------------- | --------------------------------------------------------------------------------------- |
22
+ | A lifecycle event, an app event or a tool call | `installationClientFor(event, { privateKey })` |
23
+ | A request from a page of the app | `installationClientFor(session, { privateKey, sessionToken: sessionTokenOf(request) })` |
24
+ | Work outside a request, with `offlineAccess` | `createInstallationClient({ apiUrl, installationId, privateKey })` |
25
+
26
+ A request from Picked contains a token for the installation. The client uses that token.
27
+ For a page request, the client gets a token with the session token of the person. For more
28
+ about tokens, refer to [How to read project data from an app](/how-to/apps/read-project-data-from-an-app).
29
+
30
+ The installation token reads and writes the labels of its own installation. It needs no
31
+ scope for this. The `scopes` of the manifest do not change it.
32
+
33
+ ```ts [src/server.ts]
34
+ import {
35
+ createAppHandler,
36
+ installationClientFor,
37
+ json,
38
+ readAppEnvironment,
39
+ readSession,
40
+ sessionTokenOf,
41
+ } from '@picked/app-kit/server'
42
+ import { serve } from '@picked/app-kit/node'
43
+
44
+ const port = process.env.APP_PORT ?? '4103'
45
+ const { privateKey, pickedKeys } = readAppEnvironment(process.env, port)
46
+
47
+ const handler = createAppHandler({
48
+ pickedKeys,
49
+ async onInstall(event) {
50
+ const client = installationClientFor(event, { privateKey })
51
+ await client.labels.set([
52
+ { namespace: 'settings', key: 'installed_at', type: 'text', value: new Date().toISOString() },
53
+ ])
54
+ },
55
+ async fallback(request) {
56
+ const { pathname } = new URL(request.url)
57
+ if (pathname === '/api/settings') {
58
+ const session = await readSession(request, pickedKeys)
59
+ if (session === null) return json({ error: 'unauthenticated' }, 401)
60
+ const client = installationClientFor(session, {
61
+ privateKey,
62
+ sessionToken: sessionTokenOf(request),
63
+ })
64
+ return json({ labels: await client.labels.list() })
65
+ }
66
+ return json({ error: 'not_found' }, 404)
67
+ },
68
+ })
69
+
70
+ serve(handler, Number(port))
71
+ ```
72
+
73
+ ## 2. Set labels
74
+
75
+ Call `client.labels.set` with a list of labels. Each label has a `namespace`, a `key`, a
76
+ `type` and a `value`. A namespace and a key each have 1 to 64 characters: lowercase
77
+ letters, digits, `_` or `-`. The `value` is a string that you write as the `type`.
78
+
79
+ ```ts
80
+ await client.labels.set([
81
+ { namespace: 'crm', key: 'account_id', type: 'text', value: 'acct_4821' },
82
+ { namespace: 'crm', key: 'sync_enabled', type: 'boolean', value: 'true' },
83
+ { namespace: 'crm', key: 'batch_size', type: 'number', value: '50' },
84
+ {
85
+ namespace: 'crm',
86
+ key: 'field_map',
87
+ type: 'json',
88
+ value: JSON.stringify({ email: 'Email', company: 'Company' }),
89
+ },
90
+ ])
91
+ ```
92
+
93
+ `set` makes each label, or replaces the label with the same namespace and key. Labels that
94
+ the call does not name do not change. `set` returns `labels`, the labels that it set, and
95
+ `skipped`.
96
+
97
+ Use these options when you need them:
98
+
99
+ - **A credential.** Set `secret: true`. Picked keeps the value in its secret store. Only a
100
+ `text` or `json` label can be secret.
101
+ - **A value for a limited time.** Set `expiresIn` to a number of seconds, from 1 to 31536000. After that time, `list` and `get` do not return the label.
102
+ - **A counter.** Give `increment` in place of `value` on a `number` label.
103
+ - **A value that only one writer can set.** Set `onlyIfAbsent: true`. Picked writes the
104
+ label only when no label with that namespace and key exists. An expired label counts as
105
+ absent.
106
+ - **All the labels or none.** Give `{ atomic: true }` as the second argument. If one
107
+ `onlyIfAbsent` label cannot be written, `set` writes no label.
108
+
109
+ ```ts
110
+ await client.labels.set([
111
+ { namespace: 'crm', key: 'refresh_token', type: 'text', value: refreshToken, secret: true },
112
+ { namespace: 'crm', key: 'synced_count', type: 'number', increment: 1 },
113
+ ])
114
+ ```
115
+
116
+ A secret label cannot have `increment` or `onlyIfAbsent`.
117
+ [Labels](/reference/dashboard/labels#expiry) tells how expiry, increments and conditional
118
+ writes work.
119
+
120
+ ## 3. Let one process do a task at a time
121
+
122
+ To let only one process do a task at a time, set a label with `onlyIfAbsent` and
123
+ `expiresIn`. If a different process holds the label, `set` returns it in `skipped`:
124
+
125
+ ```ts
126
+ const lockId = crypto.randomUUID()
127
+ const { skipped } = await client.labels.set([
128
+ {
129
+ namespace: 'sync',
130
+ key: 'lock',
131
+ type: 'text',
132
+ value: lockId,
133
+ onlyIfAbsent: true,
134
+ expiresIn: 300,
135
+ },
136
+ ])
137
+ if (skipped.length > 0) return
138
+
139
+ try {
140
+ await syncContacts()
141
+ } finally {
142
+ await client.labels.delete([{ namespace: 'sync', key: 'lock', ifValue: lockId }])
143
+ }
144
+ ```
145
+
146
+ With `ifValue`, `delete` removes the label only when it holds that value. If the label
147
+ expires and a different process sets it, `delete` keeps that label.
148
+
149
+ ## 4. Read labels
150
+
151
+ Call `client.labels.list()` for all the labels of the installation. Call
152
+ `client.labels.get(namespace, key)` for one label. `get` returns `undefined` when the label
153
+ does not exist or is expired.
154
+
155
+ ```ts
156
+ const accountId = (await client.labels.get('crm', 'account_id'))?.value
157
+ const fieldMap = await client.labels.get('crm', 'field_map')
158
+ const map: unknown = fieldMap === undefined ? {} : JSON.parse(fieldMap.value)
159
+ ```
160
+
161
+ Each `value` is a string. Parse it as its `type`. A token of the installation reads the
162
+ value of a secret label. Each label also has `secret`, `expiresAt` and `updatedAt`.
163
+
164
+ ## 5. Remove labels
165
+
166
+ Call `client.labels.delete` with the namespace and key of each label. It returns the IDs of
167
+ the labels that it removed.
168
+
169
+ ```ts
170
+ await client.labels.delete([
171
+ { namespace: 'crm', key: 'refresh_token' },
172
+ { namespace: 'crm', key: 'account_id' },
173
+ ])
174
+ ```
175
+
176
+ ## 6. Handle a refused write
177
+
178
+ When Picked refuses a label, `set` and `delete` throw `LabelWriteError`. Its `userErrors`
179
+ tell which label and why:
180
+
181
+ ```ts
182
+ import { LabelWriteError } from '@picked/app-kit/server'
183
+
184
+ try {
185
+ await client.labels.set(labels)
186
+ } catch (error) {
187
+ if (!(error instanceof LabelWriteError)) throw error
188
+ for (const { field, message, code } of error.userErrors) {
189
+ console.warn(`${field.join('.')}: ${message} (${code})`)
190
+ }
191
+ }
192
+ ```
193
+
194
+ An installation has these limits:
195
+
196
+ | Limit | Message |
197
+ | --------------------------- | ------------------------------------------------------ |
198
+ | 100 labels | `An app installation holds at most 100 labels.` |
199
+ | 65,536 bytes for each value | `An app installation label holds at most 65536 bytes.` |
200
+
201
+ Both errors have the code `LABEL_WRITE_INVALID`. When Picked refuses one label of a call, it
202
+ writes no label of that call.
203
+
204
+ ## 7. Know who can see the labels
205
+
206
+ The labels belong to the installation, with the owner type `APP_INSTALLATION`:
207
+
208
+ - A person with `organization_apps/read` on the project can read the labels. The value of
209
+ a secret label is empty for a person.
210
+ - A person with `organization_apps/update` on the project can set and remove them.
211
+ - The installation reads and writes them with its own tokens, without a scope.
212
+
213
+ When a person removes the app from a project, Picked first sends `installation.deleted` to
214
+ your server. The labels are still there, so your server can read a credential and revoke it
215
+ at the other service. Then Picked deletes the labels and the installation. Picked deletes
216
+ them also when your server does not answer or answers with an error. Refer to
217
+ [How to connect an external service with OAuth](/how-to/apps/connect-a-third-party-service-with-oauth#6-revoke-the-grant-when-a-person-removes-the-app).
218
+
219
+ ## Related
220
+
221
+ - [`@picked/app-kit`](/reference/apps/app-kit#labels) — `list`, `get`, `set`, `delete` and
222
+ each field of a label.
223
+ - [Labels](/reference/dashboard/labels) — expiry, increments, conditional writes and
224
+ atomic writes.
225
+ - [App protocol](/reference/apps/protocol#installation-tokens) — what an installation token
226
+ can do.
227
+ - [About app authentication](/explanation/app-authentication) — why an app keeps its data
228
+ in Picked.
229
+ - [Link to an installation from your site](/how-to/apps/link-to-an-installation-from-your-site)
230
+ — open an installation from the value of a label.
@@ -0,0 +1,359 @@
1
+ ---
2
+ type: how-to
3
+ layout: docs
4
+ ---
5
+
6
+ # How to test an app
7
+
8
+ This guide shows you how to test the handler of an app without a Picked API. The tests
9
+ send the app the signed requests that Picked sends, and a test Picked API answers the
10
+ calls that the app makes.
11
+
12
+ You need an app server that uses `createAppHandler` from `@picked/app-kit/server`. The
13
+ examples use [Vitest](https://vitest.dev). Install it in the app directory:
14
+
15
+ ```bash
16
+ npm install --save-dev vitest
17
+ ```
18
+
19
+ ## 1. Build the handler from a function
20
+
21
+ Put the handler in a function that takes the keys and the `fetch` of Picked as options.
22
+ The server gives it the real values, and a test gives it test values.
23
+
24
+ `src/app.ts`:
25
+
26
+ ```ts
27
+ import { createAppHandler, installationClientFor, type PublicKeySet } from '@picked/app-kit/server'
28
+
29
+ export interface LeadScoreOptions {
30
+ privateKey: string
31
+ pickedKeys: PublicKeySet
32
+ pickedFetch?: typeof fetch
33
+ }
34
+
35
+ function scoreLead(email: string, company: string): { score: number; tier: string } {
36
+ const domain = email.split('@')[1]?.toLowerCase() ?? ''
37
+ let score = 20
38
+ if (domain !== '' && domain !== 'gmail.com') score += 40
39
+ if (company.trim() !== '') score += 20
40
+ const tier = score >= 70 ? 'hot' : score >= 40 ? 'warm' : 'cold'
41
+ return { score, tier }
42
+ }
43
+
44
+ export function createLeadScoreApp(options: LeadScoreOptions) {
45
+ return createAppHandler({
46
+ pickedKeys: options.pickedKeys,
47
+ tools: {
48
+ async score_lead(call) {
49
+ const email = typeof call.arguments.email === 'string' ? call.arguments.email : ''
50
+ const company = typeof call.arguments.company === 'string' ? call.arguments.company : ''
51
+ if (!call.run.test) {
52
+ const client = installationClientFor(call, {
53
+ privateKey: options.privateKey,
54
+ ...(options.pickedFetch === undefined ? {} : { fetch: options.pickedFetch }),
55
+ })
56
+ await client.labels.set([
57
+ { namespace: 'lead-score', key: 'calls', type: 'number', increment: 1 },
58
+ ])
59
+ }
60
+
61
+ return scoreLead(email, company)
62
+ },
63
+ },
64
+ })
65
+ }
66
+ ```
67
+
68
+ `src/server.ts` gives the function the real environment:
69
+
70
+ ```ts
71
+ import { readAppEnvironment } from '@picked/app-kit/server'
72
+ import { serve } from '@picked/app-kit/node'
73
+ import { createLeadScoreApp } from './app'
74
+
75
+ const port = '4103'
76
+ const { privateKey, pickedKeys } = readAppEnvironment(process.env, port)
77
+
78
+ serve(createLeadScoreApp({ privateKey, pickedKeys }), Number(port))
79
+ ```
80
+
81
+ ## 2. Make a test Picked API
82
+
83
+ `createFakePicked` from `@picked/app-kit/testing` makes a test Picked API that accepts the
84
+ key of the app. Give the handler the public keys and the `fetch` of the test API:
85
+
86
+ ```ts
87
+ import { generateKeyPair } from '@picked/app-kit'
88
+ import { createFakePicked } from '@picked/app-kit/testing'
89
+ import { createLeadScoreApp } from './app'
90
+
91
+ async function setup() {
92
+ const { privateKey } = await generateKeyPair()
93
+ const picked = await createFakePicked({ appPrivateKey: privateKey })
94
+ const ref = await picked.installationRef('appi_1')
95
+ const handle = createLeadScoreApp({
96
+ privateKey,
97
+ pickedKeys: picked.pickedKeys,
98
+ pickedFetch: picked.fetch,
99
+ })
100
+ return { privateKey, picked, ref, handle }
101
+ }
102
+ ```
103
+
104
+ `picked.installationRef('appi_1')` names an installation, as a request from Picked does.
105
+ It holds a fresh token. By default the organization is `org`, the project is `proj_1`, and
106
+ the API origin is `https://api.picked.test`.
107
+
108
+ The test API does these things:
109
+
110
+ - It signs the requests that you build with it, with a Picked key that only the test API holds.
111
+ - It answers the label operations of the installation client, and keeps the labels.
112
+ - It gives a token to a token request that the private key of the app signs. The request
113
+ must also have a session token from the test API, or the test API must have
114
+ `offlineAccess: true`.
115
+ - It records each GraphQL operation that it gets in `picked.received`.
116
+
117
+ Refer to [`@picked/app-kit`](/reference/apps/app-kit) for each member of the test API.
118
+
119
+ ## 3. Send a signed tool call
120
+
121
+ `toolCall` builds the body of a tool call. `picked.signedRequest` signs it as Picked does.
122
+ The handler is a function from a `Request` to a `Response`, so the test calls it directly:
123
+
124
+ ```ts
125
+ import { toolCall } from '@picked/app-kit/testing'
126
+ import { describe, expect, it } from 'vitest'
127
+
128
+ describe('score_lead', () => {
129
+ it('scores a lead and counts the call', async () => {
130
+ const { picked, ref, handle } = await setup()
131
+
132
+ const response = await handle(
133
+ await picked.signedRequest(
134
+ 'https://lead-score.test/tools/score_lead',
135
+ toolCall(ref, 'score_lead', { email: 'ada@acme.com', company: 'Acme' }),
136
+ ),
137
+ )
138
+
139
+ expect(response.status).toBe(200)
140
+ await expect(response.json()).resolves.toEqual({ output: { score: 80, tier: 'hot' } })
141
+ })
142
+ })
143
+ ```
144
+
145
+ The handler answers these statuses to a tool call:
146
+
147
+ | Status | Body | When |
148
+ | ------ | --------------------------------------------------- | ----------------------------------------------------- |
149
+ | `200` | `{ "output": { … } }` | The tool returns. |
150
+ | `422` | `{ "error": { "message": "…" } }` | The tool throws. The message is the error message. |
151
+ | `404` | `{ "error": { "message": "Unknown tool <name>" } }` | The handler has no tool with that name. |
152
+ | `401` | `{ "error": "invalid_signature" }` | A key that is not a key of Picked signed the request. |
153
+
154
+ ## 4. Make sure of the labels and the operations
155
+
156
+ The test API keeps the labels of each installation in `picked.labels`, by installation ID and
157
+ then by `<namespace>.<key>`. Add these lines to the test:
158
+
159
+ ```ts
160
+ expect(picked.labels.get('appi_1')?.get('lead-score.calls')).toMatchObject({
161
+ type: 'number',
162
+ value: '1',
163
+ secret: false,
164
+ })
165
+ expect(picked.received.map((operation) => operation.operationName)).toEqual([
166
+ 'AppInstallationLabelsSet',
167
+ ])
168
+ ```
169
+
170
+ Each entry of `picked.received` has the `operationName` and the `variables` of the
171
+ operation. The client sends these operations:
172
+
173
+ | Operation | Sent by |
174
+ | ----------------------------- | ------------------------------------------------------------------- |
175
+ | `AppInstallationLabels` | `client.labels.list` and `client.labels.get` |
176
+ | `AppInstallationLabelsSet` | `client.labels.set` |
177
+ | `AppInstallationLabelsDelete` | `client.labels.delete` |
178
+ | `AppInstallationTokenCreate` | The client, when it has no token that is valid for a minute or more |
179
+
180
+ Here the request carried a token, so the client sent no `AppInstallationTokenCreate`.
181
+
182
+ ## 5. Test a test run
183
+
184
+ A workflow test run sets `run.test` to `true` on each tool call. Give `true` as the last
185
+ argument of `toolCall`:
186
+
187
+ ```ts
188
+ it('counts nothing in a test run', async () => {
189
+ const { picked, ref, handle } = await setup()
190
+
191
+ const response = await handle(
192
+ await picked.signedRequest(
193
+ 'https://lead-score.test/tools/score_lead',
194
+ toolCall(ref, 'score_lead', { email: 'ada@acme.com' }, true),
195
+ ),
196
+ )
197
+
198
+ await expect(response.json()).resolves.toEqual({ output: { score: 60, tier: 'warm' } })
199
+ expect(picked.received).toEqual([])
200
+ })
201
+ ```
202
+
203
+ The call then has the run ID `test_wrun`.
204
+
205
+ ## 6. Send lifecycle events and app events
206
+
207
+ Sign the body of the event, and send it to `/lifecycle` or to `/events`:
208
+
209
+ ```ts
210
+ const installed = await handle(
211
+ await picked.signedRequest('https://lead-score.test/lifecycle', {
212
+ type: 'installation.created',
213
+ ...ref,
214
+ scopes: [],
215
+ }),
216
+ )
217
+ expect(installed.status).toBe(200)
218
+
219
+ const published = await handle(
220
+ await picked.signedRequest('https://lead-score.test/events', {
221
+ type: 'workspace.published',
222
+ ...ref,
223
+ eventId: 'evt_1',
224
+ workspaceId: 'wsp_1',
225
+ workspaceVersionId: 'wspv_1',
226
+ occurredAt: '2026-10-21T00:00:00.000Z',
227
+ }),
228
+ )
229
+ expect(published.status).toBe(200)
230
+ ```
231
+
232
+ The handler answers `{ "ok": true }` after `onInstall`, `onUpgrade`, `onUninstall` or
233
+ `onEvent` returns. The other lifecycle types are `installation.upgraded` and
234
+ `installation.deleted`. Refer to [App protocol](/reference/apps/protocol) for the body of
235
+ each one.
236
+
237
+ ## 7. Send a request from a page
238
+
239
+ A page of the app sends its session token to the server of the app. The function
240
+ `picked.sessionRequest` builds that request, with a session token that the test API signs.
241
+
242
+ A session token from Picked has no installation token. Remove `token` and `tokenExpiresAt`
243
+ from the installation that you give to `sessionRequest`, so that the test session is the
244
+ same:
245
+
246
+ ```ts
247
+ import { installationClientFor, readSession, sessionTokenOf } from '@picked/app-kit/server'
248
+
249
+ it('reads the labels for a page', async () => {
250
+ const { privateKey, picked, ref } = await setup()
251
+ const { token, tokenExpiresAt, ...pageRef } = ref
252
+ const request = await picked.sessionRequest({
253
+ ref: pageRef,
254
+ url: 'https://lead-score.test/api/calls',
255
+ })
256
+
257
+ const session = await readSession(request, picked.pickedKeys)
258
+ expect(session?.userId).toBe('user-test')
259
+ if (session === null) return
260
+
261
+ const client = installationClientFor(session, {
262
+ privateKey,
263
+ sessionToken: sessionTokenOf(request),
264
+ fetch: picked.fetch,
265
+ })
266
+ await client.labels.list()
267
+ expect(picked.received.map((operation) => operation.operationName)).toEqual([
268
+ 'AppInstallationTokenCreate',
269
+ 'AppInstallationLabels',
270
+ ])
271
+ })
272
+ ```
273
+
274
+ The session has no token, so the client gets one with `AppInstallationTokenCreate`. The
275
+ test API gives the token without `offlineAccess`, because the session token comes with
276
+ the request. In your app, put the lines that read the session in the route that serves
277
+ the page, and give the request to `handle`.
278
+
279
+ ## 8. Test an app that works on its own
280
+
281
+ An app that declares `offlineAccess` gets tokens with no request from Picked and no
282
+ session token. Make the test API with `offlineAccess: true`:
283
+
284
+ ```ts
285
+ const picked = await createFakePicked({ appPrivateKey: privateKey, offlineAccess: true })
286
+ ```
287
+
288
+ Without it, the test API refuses such a token. Picked gives the same message:
289
+
290
+ ```
291
+ The installation has no offline access; use the token Picked sends with each request
292
+ ```
293
+
294
+ ## 9. Send an MCP request
295
+
296
+ `picked.mcpRequest` builds an MCP request as Picked forwards it from the dashboard. It
297
+ signs the request for one installation:
298
+
299
+ ```ts
300
+ const response = await handle(
301
+ await picked.mcpRequest('https://lead-score.test/mcp', ref, {
302
+ jsonrpc: '2.0',
303
+ id: 1,
304
+ method: 'tools/list',
305
+ }),
306
+ )
307
+ ```
308
+
309
+ The handler gives the request and the installation to `mcp.handle`.
310
+
311
+ ## 10. Make Picked refuse a write
312
+
313
+ To test what the app does when Picked refuses a label, put a function between the app
314
+ and the `fetch` of the test API. This one refuses each label write with the user error that Picked gives for a value of the wrong type:
315
+
316
+ ```ts
317
+ const refusing: typeof fetch = async (input, init) =>
318
+ typeof init?.body === 'string' && init.body.includes('AppInstallationLabelsSet')
319
+ ? Response.json({
320
+ data: {
321
+ labelsSet: {
322
+ labels: [],
323
+ skipped: [],
324
+ userErrors: [
325
+ {
326
+ field: ['labels', '0', 'value'],
327
+ message: 'Value cannot be read as NUMBER.',
328
+ code: 'VALUE_INVALID_FOR_TYPE',
329
+ },
330
+ ],
331
+ },
332
+ },
333
+ })
334
+ : picked.fetch(input, init)
335
+ ```
336
+
337
+ Give `refusing` to the app as `pickedFetch`. `client.labels.set` then throws a
338
+ `LabelWriteError`. The handler answers `422` with the message
339
+ `labels.0.value: Value cannot be read as NUMBER.`.
340
+
341
+ The test API answers only the label operations and `AppInstallationTokenCreate`. Use the same
342
+ method to answer a different GraphQL operation that your app sends.
343
+
344
+ ## 11. Run the tests
345
+
346
+ ```bash
347
+ npx vitest run
348
+ ```
349
+
350
+ ## Related
351
+
352
+ - [`@picked/app-kit`](/reference/apps/app-kit) — `createFakePicked`, `toolCall` and the
353
+ installation client.
354
+ - [App protocol](/reference/apps/protocol) — the requests that Picked sends, and how it
355
+ signs them.
356
+ - [How to store data for an installation](/how-to/apps/store-data-for-an-installation) —
357
+ labels, secret labels and their limits.
358
+ - [How to add a workflow tool to an app](/how-to/apps/add-a-workflow-tool) — tool calls and
359
+ test runs.
@@ -0,0 +1,97 @@
1
+ ---
2
+ type: how-to
3
+ layout: docs
4
+ ---
5
+
6
+ # How to upgrade or uninstall an app
7
+
8
+ This guide shows you how to move an installed app to its newest version. It also shows you
9
+ how to uninstall an app from a project. Before you start, the app must be installed on the
10
+ project.
11
+
12
+ ## Upgrade an app
13
+
14
+ An installation keeps its version until you upgrade it. When a newer version is available,
15
+ the installed app shows the badge **New version available**.
16
+
17
+ You must have these scopes in the project:
18
+
19
+ - `organization_apps/update`, to upgrade the installation.
20
+ - Each scope that the new version asks for.
21
+
22
+ ### 1. Open the apps of the project
23
+
24
+ 1. Open the project.
25
+ 2. In the project switcher, choose **Apps**.
26
+ 3. Find the app on the tab **Installed**.
27
+
28
+ ### 2. Read the new access
29
+
30
+ 1. Choose **Upgrade** next to the app. On the page of the app, **Upgrade** is at the top of
31
+ the page.
32
+ 2. Read the window `Upgrade <name> to version <version>?`.
33
+
34
+ The window shows each scope that the new version asks for:
35
+
36
+ - A scope with the badge **New** is access that the installation does not have now.
37
+ - Below `It no longer asks for:`, the window shows the access that the installation loses.
38
+ - If the new version can work when you are not in the dashboard, the window tells you that
39
+ the app works on its own.
40
+
41
+ ### 3. Accept the upgrade
42
+
43
+ 1. Choose **Upgrade**.
44
+
45
+ The installation moves to the newest version and gets the access of that version. A release
46
+ installation moves to the newest release version. A dev installation moves to the newest dev
47
+ version. The badge **New version available** is removed. Picked tells the app about the
48
+ upgrade before the upgrade is complete.
49
+
50
+ If the app refuses the upgrade, or Picked cannot get to the app, the installation keeps its
51
+ version and its access. The banner at the top of the page shows
52
+ `<name> did not accept the upgrade`. If you do not have a scope of the new version, the
53
+ banner shows `Cannot grant scopes you do not hold: <scopes>`. Refer to the
54
+ [errors of the apps page](/reference/dashboard/apps#errors).
55
+
56
+ ## Uninstall an app
57
+
58
+ You must have the scope `organization_apps/delete` in the project.
59
+
60
+ 1. In the project switcher, choose **Apps**.
61
+ 2. Choose **`Uninstall`** next to the app. On the page of the app, **`Uninstall`** is at the
62
+ top of the page.
63
+ 3. Read the window `Uninstall <name>?`.
64
+ 4. Choose **`Uninstall`**.
65
+
66
+ The app moves to the tab **Available**. If you uninstall from the page of the app, the apps
67
+ page of the project opens. Picked tells the app first. Then Picked removes these items:
68
+
69
+ - The tokens of the installation.
70
+ - The labels that the app keeps for the project.
71
+ - The workflow tools of the app. A run stops at a node that uses one of these tools. The
72
+ node does not use its error exit.
73
+ - The page of the app in the project, and its cards in the window that publishes a
74
+ workspace.
75
+
76
+ Picked removes the installation also when the app does not answer. You cannot undo this
77
+ step. If you install the app again, it does not get back the labels that it kept.
78
+
79
+ ## API and MCP
80
+
81
+ You can also do this task with the [Management API](/reference/management-api/schema), the [MCP server](/reference/tools/mcp), or code that you send to [`picked_run`](/reference/tools/mcp-run).
82
+
83
+ | Task | GraphQL | MCP tool | Run |
84
+ | --- | --- | --- | --- |
85
+ | Find the new version | [`appInstallations`](/reference/management-api/schema/app#appinstallations) | None | None |
86
+ | Upgrade the app | [`appInstallationUpgrade`](/reference/management-api/schema/app#appinstallationupgrade) | None | None |
87
+ | Uninstall the app | [`appUninstall`](/reference/management-api/schema/app#appuninstall) | None | None |
88
+
89
+ `appInstallationUpgrade` and `appUninstall` need the session of a user. An API key cannot
90
+ do them. Set `acceptedScopes` to the `scopes` in the `manifest` of the `availableVersion` of
91
+ the installation. Set `acceptedOfflineAccess` to the `offlineAccess` of that manifest.
92
+
93
+ ## Related
94
+
95
+ - [Apps](/reference/dashboard/apps) — the consent window and each error.
96
+ - [How to install an app](/how-to/apps/install-an-app) — put an app on a project.
97
+ - [About apps](/explanation/apps) — versions and installations.