diff --git a/doc/connections/tracks/local-and-aggregators.md b/doc/connections/tracks/local-and-aggregators.md index 7e4958b0f22..21dc9932e4d 100644 --- a/doc/connections/tracks/local-and-aggregators.md +++ b/doc/connections/tracks/local-and-aggregators.md @@ -32,5 +32,6 @@ Paperclip combines native `AppDefinition` entries with public aggregator snapsho - **Observations are not grants:** `tool_connection_app_snapshots` and `tool_connection_app_syncs` store read-only account observations scoped to `(company, gateway, viewing human, effective credential version)` via `/api/tool-connections/:connectionId/aggregator/apps` (`/sync`, `/refresh`). They are never executable connections or authorization grants. - **Explicit human choice for fallback:** `connections_search` owns next-step instructions. Falling back to an external aggregator requires an explicit `ask_user_questions` answer (`providerQuestion`) persisted and validated via `selectionInteractionId` in `connection_request`. A decline stays effective across continuations. - **Direct Composio app setup vs. Arcade task draft:** Composio calls `COMPOSIO_MANAGE_CONNECTIONS` directly from the board (no task created, hosted auth link not persisted in audit/results; management console at `https://dashboard.composio.dev/~/org/connect/apps`). Arcade opens a task draft (`navigateOnCreate`) so the assigned agent verifies tools and requests human authorization via `connection_request` with frozen `toolNames`. +- If Composio cannot return a sign-in link for Buffer, Plugins offers direct setup with Buffer's MCP server. Use a Buffer API key from **Settings → API** and select **Key or token** in Paperclip. To connect through Composio, configure a custom Buffer OAuth app in a Composio Platform project and use a session from that project. [Buffer MCP setup](https://developers.buffer.com/guides/integrations/other-ai-tools.html) · [Composio's Buffer requirements](https://composio.dev/toolkits/buffer) · [Composio Platform auth configs](https://docs.composio.dev/kb/guide/dashboard-auth-configs-navigation) - **Managed inventory bounds:** Arcade discovery paginates its admin account list using a separate user-owned project key (never substituting an OAuth gateway token). Executor reads its MCP integration inventory or fixed read-only `connections.list`/`integrations.list` calls — never arbitrary generated code. - **Acceptance fixtures:** `server/src/__tests__/aggregator-app-discovery.test.ts`, `server/src/__tests__/aggregator-app-sync.test.ts`, `ui/src/pages/apps/Browse.test.tsx`, `tests/aggregator-accounts/test-drive.ts`. diff --git a/packages/plugins/sandbox-providers/boxd/package.json b/packages/plugins/sandbox-providers/boxd/package.json index 10e0d78a7ec..ce0930e13c4 100644 --- a/packages/plugins/sandbox-providers/boxd/package.json +++ b/packages/plugins/sandbox-providers/boxd/package.json @@ -55,7 +55,7 @@ "devDependencies": { "@types/node": "^24.0.0", "typescript": "^7.0.2", - "vitest": "^4.1.8" + "vitest": "^5.1.2" }, "engines": { "node": ">=24.11.0" diff --git a/packages/plugins/sandbox-providers/cloudflare/bridge-template/package.json b/packages/plugins/sandbox-providers/cloudflare/bridge-template/package.json index ff3d0b20d1d..6152f445d35 100644 --- a/packages/plugins/sandbox-providers/cloudflare/bridge-template/package.json +++ b/packages/plugins/sandbox-providers/cloudflare/bridge-template/package.json @@ -15,7 +15,7 @@ "devDependencies": { "@cloudflare/workers-types": "^5.20261120.1", "typescript": "^7.0.2", - "vitest": "^4.1.8", + "vitest": "^5.1.2", "wrangler": "^4.170.0" }, "engines": { diff --git a/packages/plugins/sandbox-providers/cloudflare/package.json b/packages/plugins/sandbox-providers/cloudflare/package.json index 3b7d4b2afdd..0243ba6ca5e 100644 --- a/packages/plugins/sandbox-providers/cloudflare/package.json +++ b/packages/plugins/sandbox-providers/cloudflare/package.json @@ -53,7 +53,7 @@ "devDependencies": { "@types/node": "^24.0.0", "typescript": "^7.0.2", - "vitest": "^4.1.8" + "vitest": "^5.1.2" }, "engines": { "node": ">=24.11.0" diff --git a/packages/plugins/sandbox-providers/createos/package.json b/packages/plugins/sandbox-providers/createos/package.json index 47ca81e2f88..82ee71b5fb4 100644 --- a/packages/plugins/sandbox-providers/createos/package.json +++ b/packages/plugins/sandbox-providers/createos/package.json @@ -52,7 +52,7 @@ "devDependencies": { "@types/node": "^24.0.0", "typescript": "^7.0.2", - "vitest": "^4.1.8" + "vitest": "^5.1.2" }, "engines": { "node": ">=24.11.0" diff --git a/packages/plugins/sandbox-providers/e2b/package.json b/packages/plugins/sandbox-providers/e2b/package.json index 532db01dd5d..9a75033432c 100644 --- a/packages/plugins/sandbox-providers/e2b/package.json +++ b/packages/plugins/sandbox-providers/e2b/package.json @@ -55,7 +55,7 @@ "devDependencies": { "@types/node": "^24.0.0", "typescript": "^7.0.2", - "vitest": "^4.1.8" + "vitest": "^5.1.2" }, "engines": { "node": ">=24.11.0" diff --git a/packages/plugins/sandbox-providers/exe-dev/package.json b/packages/plugins/sandbox-providers/exe-dev/package.json index ac17f159082..a7cfc1a1556 100644 --- a/packages/plugins/sandbox-providers/exe-dev/package.json +++ b/packages/plugins/sandbox-providers/exe-dev/package.json @@ -52,7 +52,7 @@ "devDependencies": { "@types/node": "^24.0.0", "typescript": "^7.0.2", - "vitest": "^4.1.8" + "vitest": "^5.1.2" }, "engines": { "node": ">=24.11.0" diff --git a/packages/plugins/sandbox-providers/kubernetes/package.json b/packages/plugins/sandbox-providers/kubernetes/package.json index 77b3dadaffa..649e67abe06 100644 --- a/packages/plugins/sandbox-providers/kubernetes/package.json +++ b/packages/plugins/sandbox-providers/kubernetes/package.json @@ -54,7 +54,7 @@ "devDependencies": { "@types/node": "^24.0.0", "typescript": "^7.0.2", - "vitest": "^4.1.8" + "vitest": "^5.1.2" }, "engines": { "node": ">=24.11.0" diff --git a/packages/plugins/sandbox-providers/modal/package.json b/packages/plugins/sandbox-providers/modal/package.json index c188fa1e5e2..b5d0366d5f5 100644 --- a/packages/plugins/sandbox-providers/modal/package.json +++ b/packages/plugins/sandbox-providers/modal/package.json @@ -55,7 +55,7 @@ "devDependencies": { "@types/node": "^24.0.0", "typescript": "^7.0.2", - "vitest": "^4.1.8" + "vitest": "^5.1.2" }, "engines": { "node": ">=24.11.0" diff --git a/packages/plugins/sandbox-providers/novita/package.json b/packages/plugins/sandbox-providers/novita/package.json index d883d301cb2..42ffb4991d5 100644 --- a/packages/plugins/sandbox-providers/novita/package.json +++ b/packages/plugins/sandbox-providers/novita/package.json @@ -56,7 +56,7 @@ "devDependencies": { "@types/node": "^24.0.0", "typescript": "^7.0.2", - "vitest": "^4.1.8" + "vitest": "^5.1.2" }, "engines": { "node": ">=24.11.0" diff --git a/packages/plugins/sdk/src/workspace-operation-error.ts b/packages/plugins/sdk/src/workspace-operation-error.ts index 2cd247d002d..6bee7252ff5 100644 --- a/packages/plugins/sdk/src/workspace-operation-error.ts +++ b/packages/plugins/sdk/src/workspace-operation-error.ts @@ -18,6 +18,12 @@ export const WORKSPACE_OPERATION_FAILURE_REASONS = [ "storage_pending", /** The selected runtime is not ready. */ "runtime_unavailable", + /** + * The selected runtime is applying an update and refuses new workspaces until + * it finishes. Core holds the run and retries the same workspace for longer + * than a transient failure. + */ + "runtime_updating", /** The selected runtime's saved connection is invalid. */ "runtime_connection_invalid", /** A remote storage or runtime request failed or returned an unusable result. */ diff --git a/packages/shared/src/composio-app-setup.ts b/packages/shared/src/composio-app-setup.ts index 75f544f5647..dfefc5aded0 100644 --- a/packages/shared/src/composio-app-setup.ts +++ b/packages/shared/src/composio-app-setup.ts @@ -1,5 +1,7 @@ import { z } from "zod"; +export const COMPOSIO_SIGN_IN_LINK_MISSING = "composio_sign_in_link_missing"; + export const composioAppSetupSchema = z.discriminatedUnion("action", [ z.object({ action: z.literal("start") }).strict(), z.object({ action: z.literal("status") }).strict(), diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 6cb45924ebf..6dd91e7caab 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -10,7 +10,7 @@ export * from "./responsibility-dashboard.js"; export * from "./responsibility-metrics.js"; export * from "./responsibility-runs.js"; export * from "./responsibility-status-reports.js"; -export { composioAppSetupSchema, composioAppsRefreshSchema, composioAppsSyncSchema, composioAppAccountSchema, type ComposioAppSetupInput, type ComposioAppSetupResult, type ComposioAppAccountInput, type ComposioAppAccount, type ComposioAppSnapshot, type ComposioAppSyncState, type ComposioAppsResponse } from "./composio-app-setup.js"; +export { COMPOSIO_SIGN_IN_LINK_MISSING, composioAppSetupSchema, composioAppsRefreshSchema, composioAppsSyncSchema, composioAppAccountSchema, type ComposioAppSetupInput, type ComposioAppSetupResult, type ComposioAppAccountInput, type ComposioAppAccount, type ComposioAppSnapshot, type ComposioAppSyncState, type ComposioAppsResponse } from "./composio-app-setup.js"; export { agentAdapterTypeSchema, optionalAgentAdapterTypeSchema } from "./adapter-type.js"; export { RUNNER_GOAL_MAX_OBJECTIVE_CHARS, diff --git a/scripts/typecheck-sandbox-providers/pnpm-lock.yaml b/scripts/typecheck-sandbox-providers/pnpm-lock.yaml index 3afc058c3d5..748530e8ade 100644 --- a/scripts/typecheck-sandbox-providers/pnpm-lock.yaml +++ b/scripts/typecheck-sandbox-providers/pnpm-lock.yaml @@ -21,8 +21,8 @@ importers: specifier: ^7.0.2 version: 7.0.2 vitest: - specifier: ^4.1.8 - version: 4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) + specifier: ^5.1.2 + version: 5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) ../../packages/plugins/sandbox-providers/cloudflare: devDependencies: @@ -33,8 +33,8 @@ importers: specifier: ^7.0.2 version: 7.0.2 vitest: - specifier: ^4.1.8 - version: 4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) + specifier: ^5.1.2 + version: 5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) ../../packages/plugins/sandbox-providers/cloudflare/bridge-template: dependencies: @@ -49,11 +49,11 @@ importers: specifier: ^7.0.2 version: 7.0.2 vitest: - specifier: ^4.1.8 - version: 4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) + specifier: ^5.1.2 + version: 5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) wrangler: specifier: ^4.170.0 - version: 4.170.0(@cloudflare/workers-types@5.20261120.1)(@types/node@24.19.2)(vitest@4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1))) + version: 4.170.0(@cloudflare/workers-types@5.20261120.1)(@types/node@24.19.2)(vitest@5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1))) ../../packages/plugins/sandbox-providers/createos: dependencies: @@ -68,8 +68,8 @@ importers: specifier: ^7.0.2 version: 7.0.2 vitest: - specifier: ^4.1.8 - version: 4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) + specifier: ^5.1.2 + version: 5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) ../../packages/plugins/sandbox-providers/e2b: dependencies: @@ -84,8 +84,8 @@ importers: specifier: ^7.0.2 version: 7.0.2 vitest: - specifier: ^4.1.8 - version: 4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) + specifier: ^5.1.2 + version: 5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) ../../packages/plugins/sandbox-providers/exe-dev: devDependencies: @@ -96,8 +96,8 @@ importers: specifier: ^7.0.2 version: 7.0.2 vitest: - specifier: ^4.1.8 - version: 4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) + specifier: ^5.1.2 + version: 5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) ../../packages/plugins/sandbox-providers/kubernetes: dependencies: @@ -115,8 +115,8 @@ importers: specifier: ^7.0.2 version: 7.0.2 vitest: - specifier: ^4.1.8 - version: 4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) + specifier: ^5.1.2 + version: 5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) ../../packages/plugins/sandbox-providers/modal: dependencies: @@ -131,8 +131,8 @@ importers: specifier: ^7.0.2 version: 7.0.2 vitest: - specifier: ^4.1.8 - version: 4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) + specifier: ^5.1.2 + version: 5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) ../../packages/plugins/sandbox-providers/novita: dependencies: @@ -147,8 +147,8 @@ importers: specifier: ^7.0.2 version: 7.0.2 vitest: - specifier: ^4.1.8 - version: 4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) + specifier: ^5.1.2 + version: 5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) packages: @@ -621,6 +621,9 @@ packages: '@jridgewell/sourcemap-codec@1.6.0': resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@jridgewell/trace-mapping@0.3.9': resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} @@ -819,18 +822,12 @@ packages: '@speed-highlight/core@1.2.24': resolution: {integrity: sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==} - '@standard-schema/spec@1.1.0': - resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} - '@types/chai@5.2.3': resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} '@types/deep-eql@4.0.2': resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} - '@types/estree@1.0.10': - resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==} - '@types/estree@1.0.11': resolution: {integrity: sha512-YBdNe5JcjYR0sPhJW1QIeRCmI11YhYvaRuGCs9+WCeTTb+Yhb2BE2XMe5/wAqF10FK5g3+q1PDhQABfT7aX0gg==} @@ -975,13 +972,10 @@ packages: cpu: [x64] os: [win32] - '@vitest/expect@4.1.12': - resolution: {integrity: sha512-vFlTt+YEu9WBpNjdGayNmlMVzrWPi1+sv853/7t2FU7hpO5gAFBKHzQmkCq5Xjpr+evegF2994LQT3hF3mRlqQ==} - - '@vitest/mocker@4.1.12': - resolution: {integrity: sha512-fKShNpKZzupWZuY0z7egydvL0sqW4INEZBEExMBMAa6izlENEVHwoXgdaTCaBZ5fwlr4xf2o1wXC83n9RpO+NA==} + '@vitest/mocker@5.1.2': + resolution: {integrity: sha512-UGc97wUIy0Ji2+9GxzHEJiOhiwkaukgE7VYcUNnjpX3sWnwQ8XogmNXX4WyOukxYgKb8Nh2XFa7KId0ZjpmVhQ==} peerDependencies: - msw: ^2.4.9 + msw: ^2.4.9 || ^3.0.0 vite: ^6.0.0 || ^7.0.0 || ^8.0.0 peerDependenciesMeta: msw: @@ -989,20 +983,8 @@ packages: vite: optional: true - '@vitest/pretty-format@4.1.12': - resolution: {integrity: sha512-XW9O8+Mxx4VpCtkYdMJLZQQwsVryP9wk7cPKDxtXFfwSak6yRh5+2fep/Y0XF/ElBvJHq8bcYdi6aeuai0opZA==} - - '@vitest/runner@4.1.12': - resolution: {integrity: sha512-NKlVKCr5QnCe8jijdMnmkpHHU+WTqiLFR6G0pHji9uRjXK9xJl1k1nTw6F3pOOj2PDcsDt2GKQMI7wIsaT491w==} - - '@vitest/snapshot@4.1.12': - resolution: {integrity: sha512-ko1y1Qgb/slzQ9mr+b89Cuqud8WG1TKtsPD8r7ZUBdvVOGt85Af2HwCqHujrhwJq95hs/9RM7fcAPg57o1vlzw==} - - '@vitest/spy@4.1.12': - resolution: {integrity: sha512-RGq9x4JNGNTZHEJxvN0oSiJjeSCExm0n2gZKKJZHY9cX5AVA6M7VJILBT3ZJ/tJ/0J9uWT7fETV9/btoi//vSg==} - - '@vitest/utils@4.1.12': - resolution: {integrity: sha512-Q3awXrwOfEV+qc3WmO5ONyE0yO7Q1gQ9/oyHxGLZ/pl7N3NO/ZztqQwKLuwMkV+CA1JYSIeO3gkHnRDIo4AVaA==} + '@vitest/spy@5.1.2': + resolution: {integrity: sha512-PQl0/3+p9GaY71+MHywN6oyHfLhVDD5kcbm7oNRldA2F0ExMU3S8RQdnpteJ9gFAdK5P6KCgE6LqCpUgy57KzA==} abort-controller-x@0.5.0: resolution: {integrity: sha512-yTt9CI0x+nRfX6BFMenEGP8ooPvErGH6AbFz20C2IeOLIlDsrw/VHpgne3GsCEuTA410IiFiaLVFKmgM4bKEPQ==} @@ -1141,9 +1123,6 @@ packages: compare-versions@6.1.1: resolution: {integrity: sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==} - convert-source-map@2.0.0: - resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} - cookie@1.1.1: resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} engines: {node: '>=18'} @@ -1344,8 +1323,8 @@ packages: resolution: {integrity: sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==} engines: {node: 20 || >=22} - magic-string@0.30.21: - resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + magic-string@1.4.5: + resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} @@ -1422,8 +1401,8 @@ packages: oauth4webapi@3.8.8: resolution: {integrity: sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==} - obug@2.2.1: - resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} + obug@3.0.0: + resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} engines: {node: '>=12.20.0'} once@1.4.0: @@ -1501,9 +1480,6 @@ packages: '@types/node': optional: true - siginfo@2.0.0: - resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} - smart-buffer@4.2.0: resolution: {integrity: sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==} engines: {node: '>= 6.0.0', npm: '>= 3.0.0'} @@ -1524,9 +1500,6 @@ packages: resolution: {integrity: sha512-pdUVfIWcK0kCgK831ibqkZDcL7I9zljjOu0TQFnA+fiQ6y1CYqYB7RkTOHHO45FGMg5P/Mvk/+4ToQ7gAYAL5Q==} engines: {node: '>=6.0.0'} - stackback@0.0.2: - resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} - std-env@4.3.0: resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} @@ -1565,21 +1538,18 @@ packages: text-decoder@1.2.7: resolution: {integrity: sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==} - tinybench@2.9.0: - resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + tinybench@6.2.5: + resolution: {integrity: sha512-b/8GRMdnY4cqkfCLyaFpTGIv1qwfi3oT0mWaepwT++6Z/ZrYehNfZZ2JDKVLKGhNoEkS3IIB1ELtCT0XS5DtOA==} + engines: {node: '>=20.0.0'} - tinyexec@1.3.1: - resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + tinyexec@1.4.0: + resolution: {integrity: sha512-PV6lIcJQh57aFeJDwx16JNHmgFRh5xguzallrDW1qe8nAghYgr5MKz2K5k7wEyV/ygZhdnIAP8+HZSarHPBCsg==} engines: {node: '>=18'} tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} - tinyrainbow@3.2.0: - resolution: {integrity: sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==} - engines: {node: '>=14.0.0'} - tr46@0.0.3: resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==} @@ -1655,23 +1625,23 @@ packages: yaml: optional: true - vitest@4.1.12: - resolution: {integrity: sha512-5eWdz2yb3ajxWF3C8C4TjkXl7FGm3n2E/VlazALrQHzK7nYMSGFnCZto0bbPNl77AwkOZVLk0YnBAejUu0NiWA==} - engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + vitest@5.1.2: + resolution: {integrity: sha512-VIa2wXV208WraXUbzH+dQUrGcFpPuaiRA8HlhXS8R6/sy9cynw6OMqGj8fmAlH1hot7huTCtWUE14+FdXU3eLw==} + engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} hasBin: true peerDependencies: '@edge-runtime/vm': '*' '@opentelemetry/api': ^1.9.0 - '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 - '@vitest/browser-playwright': 4.1.12 - '@vitest/browser-preview': 4.1.12 - '@vitest/browser-webdriverio': ^4.1.11 - '@vitest/coverage-istanbul': 4.1.12 - '@vitest/coverage-v8': 4.1.12 - '@vitest/ui': 4.1.12 + '@types/node': ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 5.1.2 + '@vitest/browser-preview': 5.1.2 + '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 + '@vitest/coverage-istanbul': 5.1.2 + '@vitest/coverage-v8': 5.1.2 + '@vitest/ui': 5.1.2 happy-dom: '*' jsdom: '*' - vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + vite: ^6.4.0 || ^7.0.0 || ^8.0.0 peerDependenciesMeta: '@edge-runtime/vm': optional: true @@ -1706,9 +1676,9 @@ packages: whatwg-url@5.0.0: resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} - why-is-node-running@2.3.0: - resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} - engines: {node: '>=8'} + why-is-node-running@3.2.1: + resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} + engines: {node: '>=20.11'} hasBin: true workerd@1.20261129.1: @@ -1848,14 +1818,14 @@ snapshots: '@cloudflare/workers-types@5.20261120.1': {} - '@cloudflare/workers-utils@0.60.0(vitest@4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)))': + '@cloudflare/workers-utils@0.60.0(vitest@5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)))': dependencies: '@cspotcode/source-map-support': 0.8.1 chalk: 5.3.0 dotenv: 16.3.1 undici: 7.30.2 optionalDependencies: - vitest: 4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) + vitest: 5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) '@connectrpc/connect-web@2.0.0-rc.3(@bufbuild/protobuf@2.16.0)(@connectrpc/connect@2.0.0-rc.3(@bufbuild/protobuf@2.16.0))': dependencies: @@ -2092,6 +2062,11 @@ snapshots: '@jridgewell/sourcemap-codec@1.6.0': {} + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.3 + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping@0.3.9': dependencies: '@jridgewell/resolve-uri': 3.1.3 @@ -2251,8 +2226,6 @@ snapshots: '@speed-highlight/core@1.2.24': {} - '@standard-schema/spec@1.1.0': {} - '@types/chai@5.2.3': dependencies: '@types/deep-eql': 4.0.2 @@ -2260,8 +2233,6 @@ snapshots: '@types/deep-eql@4.0.2': {} - '@types/estree@1.0.10': {} - '@types/estree@1.0.11': {} '@types/js-yaml@4.0.9': {} @@ -2349,46 +2320,16 @@ snapshots: '@typescript/typescript-win32-x64@7.0.2': optional: true - '@vitest/expect@4.1.12': + '@vitest/mocker@5.1.2(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1))': dependencies: - '@standard-schema/spec': 1.1.0 - '@types/chai': 5.2.3 - '@vitest/spy': 4.1.12 - '@vitest/utils': 4.1.12 - chai: 6.3.0 - tinyrainbow: 3.2.0 - - '@vitest/mocker@4.1.12(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1))': - dependencies: - '@vitest/spy': 4.1.12 + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.1.2 estree-walker: 3.0.3 - magic-string: 0.30.21 + magic-string: 1.4.5 optionalDependencies: vite: 7.3.7(@types/node@24.19.2)(yaml@2.9.1) - '@vitest/pretty-format@4.1.12': - dependencies: - tinyrainbow: 3.2.0 - - '@vitest/runner@4.1.12': - dependencies: - '@vitest/utils': 4.1.12 - pathe: 2.0.3 - - '@vitest/snapshot@4.1.12': - dependencies: - '@vitest/pretty-format': 4.1.12 - '@vitest/utils': 4.1.12 - magic-string: 0.30.21 - pathe: 2.0.3 - - '@vitest/spy@4.1.12': {} - - '@vitest/utils@4.1.12': - dependencies: - '@vitest/pretty-format': 4.1.12 - convert-source-map: 2.0.0 - tinyrainbow: 3.2.0 + '@vitest/spy@5.1.2': {} abort-controller-x@0.5.0: {} @@ -2512,8 +2453,6 @@ snapshots: compare-versions@6.1.1: {} - convert-source-map@2.0.0: {} - cookie@1.1.1: {} debug@4.4.3: @@ -2606,7 +2545,7 @@ snapshots: estree-walker@3.0.3: dependencies: - '@types/estree': 1.0.10 + '@types/estree': 1.0.11 event-target-shim@5.0.1: {} @@ -2718,7 +2657,7 @@ snapshots: lru-cache@11.5.3: {} - magic-string@0.30.21: + magic-string@1.4.5: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 @@ -2799,7 +2738,7 @@ snapshots: oauth4webapi@3.8.8: {} - obug@2.2.1: {} + obug@3.0.0: {} once@1.4.0: dependencies: @@ -2933,8 +2872,6 @@ snapshots: '@img/sharp-win32-x64': 0.35.5 '@types/node': 24.19.2 - siginfo@2.0.0: {} - smart-buffer@4.2.0: {} smol-toml@1.9.1: {} @@ -2954,8 +2891,6 @@ snapshots: source-map-js@1.3.0: {} - stackback@0.0.2: {} - std-env@4.3.0: {} stream-buffers@3.0.3: {} @@ -3025,17 +2960,15 @@ snapshots: transitivePeerDependencies: - react-native-b4a - tinybench@2.9.0: {} + tinybench@6.2.5: {} - tinyexec@1.3.1: {} + tinyexec@1.4.0: {} tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.7) picomatch: 4.0.7 - tinyrainbow@3.2.0: {} - tr46@0.0.3: {} ts-error@1.0.6: {} @@ -3093,28 +3026,22 @@ snapshots: fsevents: 2.3.3 yaml: 2.9.1 - vitest@4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)): + vitest@5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)): dependencies: - '@vitest/expect': 4.1.12 - '@vitest/mocker': 4.1.12(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) - '@vitest/pretty-format': 4.1.12 - '@vitest/runner': 4.1.12 - '@vitest/snapshot': 4.1.12 - '@vitest/spy': 4.1.12 - '@vitest/utils': 4.1.12 + '@types/chai': 5.2.3 + '@vitest/mocker': 5.1.2(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1)) + chai: 6.3.0 es-module-lexer: 2.3.2 expect-type: 1.4.0 - magic-string: 0.30.21 - obug: 2.2.1 - pathe: 2.0.3 + magic-string: 1.4.5 + obug: 3.0.0 picomatch: 4.0.7 std-env: 4.3.0 - tinybench: 2.9.0 - tinyexec: 1.3.1 + tinybench: 6.2.5 + tinyexec: 1.4.0 tinyglobby: 0.2.17 - tinyrainbow: 3.2.0 vite: 7.3.7(@types/node@24.19.2)(yaml@2.9.1) - why-is-node-running: 2.3.0 + why-is-node-running: 3.2.1 optionalDependencies: '@opentelemetry/api': 1.10.0 '@types/node': 24.19.2 @@ -3130,10 +3057,7 @@ snapshots: tr46: 0.0.3 webidl-conversions: 3.0.1 - why-is-node-running@2.3.0: - dependencies: - siginfo: 2.0.0 - stackback: 0.0.2 + why-is-node-running@3.2.1: {} workerd@1.20261129.1: optionalDependencies: @@ -3143,11 +3067,11 @@ snapshots: '@cloudflare/workerd-linux-arm64': 1.20261129.1 '@cloudflare/workerd-windows-64': 1.20261129.1 - wrangler@4.170.0(@cloudflare/workers-types@5.20261120.1)(@types/node@24.19.2)(vitest@4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1))): + wrangler@4.170.0(@cloudflare/workers-types@5.20261120.1)(@types/node@24.19.2)(vitest@5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1))): dependencies: '@cloudflare/kv-asset-handler': 0.5.1 '@cloudflare/unenv-preset': 2.16.2(unenv@2.0.0-rc.24)(workerd@1.20261129.1) - '@cloudflare/workers-utils': 0.60.0(vitest@4.1.12(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1))) + '@cloudflare/workers-utils': 0.60.0(vitest@5.1.2(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(vite@7.3.7(@types/node@24.19.2)(yaml@2.9.1))) '@cspotcode/source-map-support': 0.8.1 '@types/yargs': 17.0.24 cloudflare: 5.2.0 diff --git a/server/src/__tests__/authorization-request-reads.test.ts b/server/src/__tests__/authorization-request-reads.test.ts index 3a61bd4f7ba..b548f3583f1 100644 --- a/server/src/__tests__/authorization-request-reads.test.ts +++ b/server/src/__tests__/authorization-request-reads.test.ts @@ -7,7 +7,7 @@ import { authUsers, companyMemberships, instanceUserRoles, issues, projects } fr import { actorMiddleware } from "../middleware/auth.js"; import { errorHandler } from "../middleware/error-handler.js"; import { issueRoutes } from "../routes/issues.js"; -import { AUTHORIZATION_READ_MAX_AGE_MS, authorizationReadScope, readOncePerRequest } from "../services/authorization-read-scope.js"; +import { AUTHORIZATION_READ_MAX_AGE_MS, authorizationReadScope, readOncePerAuthorizationCheck, readOncePerRequest, withFreshAuthorizationReads } from "../services/authorization-read-scope.js"; import { readInstanceAdmin } from "../services/authorization.js"; import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; import { describeEmbeddedPostgres, seedCompanyWithBoardAccess, useEmbeddedPostgres } from "./helpers/route-test-harness.js"; @@ -178,6 +178,21 @@ describeEmbeddedPostgres("authorization reads per request", () => { describe("authorization read scope boundaries", () => { afterEach(() => { vi.useRealTimers(); }); + it("shares facts only within one authorization check and refreshes before its continuation", async () => { + let reads = 0; + const read = () => readOncePerAuthorizationCheck("grant:company:user:reader:tools:manage_connections", async () => ++reads); + await withFreshAuthorizationReads(async () => { + expect(await read()).toBe(1); + expect(await read()).toBe(1); + await withFreshAuthorizationReads(async () => { expect(await read()).toBe(2); }); + expect(await read()).toBe(1); + }); + expect(await read()).toBe(3); + await withFreshAuthorizationReads(async () => { expect(await read()).toBe(4); }); + await expect(withFreshAuthorizationReads(async () => { await read(); throw new Error("denied"); })).rejects.toThrow("denied"); + expect(await read()).toBe(6); + }); + function countingApp(actor: Express.Request["actor"] = { type: "board", source: "session", userId: "user-1", isInstanceAdmin: false }) { let reads = 0; const gates: Array<() => void> = []; diff --git a/server/src/__tests__/composio-add-account-link.test.ts b/server/src/__tests__/composio-add-account-link.test.ts index 303f8c32a83..6335ec3af81 100644 --- a/server/src/__tests__/composio-add-account-link.test.ts +++ b/server/src/__tests__/composio-add-account-link.test.ts @@ -225,6 +225,24 @@ const support = await getEmbeddedPostgresTestSupport(); expect((await f.access.getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools).toEqual([]); }); + it("identifies a missing Buffer sign-in link in the Plugins setup flow", async () => { + const f = await setupComposioRouteFixture((id) => Response.json({ + jsonrpc: "2.0", + id, + result: { + structuredContent: { data: { results: { buffer: { toolkit: "buffer", accounts: [] } } } }, + }, + })); + + const response = await request(f.app) + .post(`/api/tool-connections/${f.connection.id}/composio/apps/buffer/setup`) + .send({ action: "start" }); + + expect(response.status).toBe(422); + expect(response.body.details).toEqual({ code: "composio_sign_in_link_missing" }); + expect(f.operations).toEqual([{ name: "buffer", action: "list" }, { name: "buffer", action: "add" }]); + }); + it("returns 422 and failed telemetry when Composio returns no trusted link or reports a provider error", async () => { const missingLink = await setupComposioRouteFixture((id) => Response.json({ diff --git a/server/src/__tests__/connection-management.integration.test.ts b/server/src/__tests__/connection-management.integration.test.ts index e58b9a1bd34..26011dbe46b 100644 --- a/server/src/__tests__/connection-management.integration.test.ts +++ b/server/src/__tests__/connection-management.integration.test.ts @@ -1,4 +1,5 @@ import { createToolGatewayService } from "../services/tool-gateway.js"; +import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; import { commitToolActionReview } from "../services/tool-action-review.js"; import { googleWorkspaceSelectedScopes, defaultGitHubReviewPolicy, SLACK_CHAT_BOT_SCOPES, SLACK_BOT_TOOL_SCOPES } from "@paperclipai/shared"; import { createHash, randomBytes, randomUUID, generateKeyPairSync } from "node:crypto"; @@ -299,6 +300,66 @@ describe("connection management with production default agents", () => { expect(profile, JSON.stringify(profile)).toMatchObject({ status: 201 }); }); + it("saves a large connection's agent access without repeating authorization reads for every target and action", async () => { + const f = await server.fixture({ connectionScenario: "fresh" }); + const userId = f.responsibleUserId!; + const cookie = await server.humanSession(userId); + await server.db.insert(principalPermissionGrants).values(["tools:manage_connections", "agents:configure"].map(permissionKey => ({ + companyId: f.companyId, principalType: "user" as const, principalId: userId, permissionKey, + }))).onConflictDoNothing(); + const peers = await server.db.insert(agents).values(Array.from({ length: 40 }, (_, index) => ({ + companyId: f.companyId, name: `Access target ${index}`, adapterType: "process", + }))).returning(); + const [application] = await server.db.insert(toolApplications).values({ companyId: f.companyId, name: "Shared catalog", type: "mcp_http" }).returning(); + const connections = await server.db.insert(toolConnections).values(Array.from({ length: 3 }, (_, index) => ({ + companyId: f.companyId, applicationId: application.id, uid: randomUUID(), name: `Shared account ${index}`, + transport: "mcp_remote" as const, authKind: "none" as const, status: "active" as const, + }))).returning(); + const connection = connections[0]; + await server.db.insert(toolConnectionInstalls).values(connections.map(row => ({ + companyId: f.companyId, connectionId: row.id, targetType: "company" as const, targetId: f.companyId, + }))); + const catalog = await server.db.insert(toolCatalogEntries).values(Array.from({ length: 50 }, (_, index) => ({ + companyId: f.companyId, applicationId: application.id, connectionId: connection.id, + name: `action_${index}`, toolName: `action_${index}`, versionHash: `action_${index}`, + }))).returning(); + const [profile] = await server.db.insert(toolProfiles).values({ + companyId: f.companyId, profileKey: `app:${connection.id}`, name: connection.name, + }).returning(); + await server.db.insert(toolProfileEntries).values(catalog.map(entry => ({ + companyId: f.companyId, profileId: profile.id, selectorType: "catalog_entry" as const, + applicationId: application.id, connectionId: connection.id, catalogEntryId: entry.id, + }))); + const finish = () => fetch(`${server.apiUrl}/api/companies/${f.companyId}/tools/apps/${connection.id}/finish`, { + method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, + body: JSON.stringify({ enabledCatalogEntryIds: catalog.map(entry => entry.id), askFirstCatalogEntryIds: [], access: { agentIds: [f.agentId, peers[0].id] } }), + }); + const meter = meterDatabaseStatements(server.db, server.databaseUrl); + try { + meter.startLog(); + const response = await finish(); + const body = await response.json(); + const statements = meter.stopLog(); + expect(response.status, JSON.stringify(body)).toBe(200); + expect(body.profileBindings.map((row: { targetId: string }) => row.targetId).sort()).toEqual([f.agentId, peers[0].id].sort()); + expect(body.profileEntries).toHaveLength(50); + for (const table of ["company_memberships", "principal_permission_grants", "tool_catalog_entries"]) { + expect(statements.filter(entry => entry.sql.includes(`from "${table}"`)).length, table).toBeLessThan(30); + } + // Company-wide install expansion still reads the company roster. It must + // not add one agent lookup per target in each referenced account. + expect(statements.filter(entry => entry.sql.includes('from "agents"')).length).toBeLessThan(80); + // A fresh request must still check all referenced accounts with current grants. + await server.db.update(principalPermissionGrants).set({ scope: { connectionIds: [connection.id] } }).where(and( + eq(principalPermissionGrants.companyId, f.companyId), eq(principalPermissionGrants.principalId, userId), + eq(principalPermissionGrants.permissionKey, "tools:manage_connections"), + )); + const denied = await finish(); + expect(denied.status).toBe(403); + expect(await server.db.select().from(toolProfileBindings).where(eq(toolProfileBindings.profileId, profile.id))).toHaveLength(2); + } finally { meter.uninstall(); } + }); + it("checks effective-profile connection access once for hundreds of tools on the same account", async () => { const f = await fixture(); const connection = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: "Large catalog", transport: "mcp_remote", authKind: "none", config: { url: "https://1.1.1.1/mcp" } }); diff --git a/server/src/__tests__/workspace-provider-failure.test.ts b/server/src/__tests__/workspace-provider-failure.test.ts index a314de8eaa1..913a4a8646d 100644 --- a/server/src/__tests__/workspace-provider-failure.test.ts +++ b/server/src/__tests__/workspace-provider-failure.test.ts @@ -17,6 +17,7 @@ import { import { HttpError } from "../errors.js"; import { findPluginWorkerUnavailableError, PluginWorkerUnavailableError } from "../services/plugin-worker-unavailable-error.js"; import { + findRetryableWorkspaceStorageSetupCode, findWorkspaceProviderFailure, readWorkspaceProviderFailure, workspaceProviderCallFailure, @@ -94,7 +95,7 @@ describe("workspace provider call failures", () => { }); it("gives every reason a fixed message and a retry decision", () => { - const transient = new Set(["storage_pending", "runtime_unavailable", "remote_incomplete", "context_changed", "deadline_exceeded"]); + const transient = new Set(["storage_pending", "runtime_unavailable", "runtime_updating", "remote_incomplete", "context_changed", "deadline_exceeded"]); for (const reason of WORKSPACE_OPERATION_FAILURE_REASONS) { const failure = workspaceProviderCallFailure(new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, message: "private provider text", data: { schema: "paperclip/workspace-operation-error/v1", reason } })); @@ -196,4 +197,25 @@ describe("workspace provider call failures", () => { expect(notice.body).toContain("no agent work started"); expect(notice.body).not.toMatch(/retried automatically|tries again automatically/); }); + + it("waits for an updating runtime in its own setup lane and names it when that wait ends", async () => { + const failure = workspaceProviderCallFailure(await providerRejection( + new PluginWorkspaceOperationError("runtime_updating", "private fence holder text"))); + expect(failure.summary()).toEqual({ kind: "provider", reason: "runtime_updating", retryable: true }); + expect(failure.message).toBe("The selected runtime is updating; retry the same workspace after the update"); + expect(failure.message).not.toContain("private"); + expect(findRetryableWorkspaceStorageSetupCode(new Error("setup failed", { cause: failure }))).toBe("workspace_runtime_updating"); + + const saved = readWorkspaceProviderFailure({ workspaceProviderFailure: failure.summary() }); + const notice = buildStrandedRecoveryEscalationNotice({ + seed: buildNoRunningExecutionNoticeSeed({ status: "in_progress", workspaceProviderFailure: saved }), + recoveryActionId: id(16), + recoveryOwner: null, + sourceRun: { id: id(17), status: "failed", errorCode: "workspace_runtime_updating", + errorSummary: workspaceProviderFailureMessage(saved) }, + }); + expect(JSON.stringify(notice.presentation)).toContain("Agent computer was still updating"); + expect(notice.body).toContain("no agent work started"); + expect(notice.body).not.toMatch(/retried automatically|tries again automatically/); + }); }); diff --git a/server/src/modules/run-dispatch/domain/wake-context.ts b/server/src/modules/run-dispatch/domain/wake-context.ts index 4e45d97e4b6..685aa30bfc1 100644 --- a/server/src/modules/run-dispatch/domain/wake-context.ts +++ b/server/src/modules/run-dispatch/domain/wake-context.ts @@ -24,9 +24,11 @@ export const AI_CONNECTION_POOL_WAIT_RETRY_REASON = "ai_connection_pool_wait"; export const AI_CONNECTION_BUSY_RETRY_REASON = "ai_connection_busy"; export const RUNNER_REVISION_WAIT_RETRY_REASON = "runner_revision_wait"; export const STORAGE_UNAVAILABLE_WAIT_RETRY_REASON = "storage_unavailable_wait"; +/** Waits for an agent computer that refused new workspaces while it updates. */ +export const RUNTIME_UPDATE_WAIT_RETRY_REASON = "runtime_update_wait"; export const AGENT_DIRECTORY_BUSY_RETRY_REASON = "agent_directory_busy"; export const PREPARATION_WAIT_RETRY_REASONS: ReadonlySet = new Set([ - RUNNER_REVISION_WAIT_RETRY_REASON, STORAGE_UNAVAILABLE_WAIT_RETRY_REASON, + RUNNER_REVISION_WAIT_RETRY_REASON, STORAGE_UNAVAILABLE_WAIT_RETRY_REASON, RUNTIME_UPDATE_WAIT_RETRY_REASON, ]); export function isPreparationWaitRetryReason(reason: string | null | undefined): boolean { return typeof reason === "string" && PREPARATION_WAIT_RETRY_REASONS.has(reason); diff --git a/server/src/modules/run-dispatch/index.ts b/server/src/modules/run-dispatch/index.ts index 6d7678b2cd0..111afa3244b 100644 --- a/server/src/modules/run-dispatch/index.ts +++ b/server/src/modules/run-dispatch/index.ts @@ -16,6 +16,7 @@ export { AI_CONNECTION_POOL_WAIT_RETRY_REASON, RUNNER_REVISION_WAIT_RETRY_REASON, STORAGE_UNAVAILABLE_WAIT_RETRY_REASON, + RUNTIME_UPDATE_WAIT_RETRY_REASON, AGENT_DIRECTORY_BUSY_RETRY_REASON, PREPARATION_WAIT_RETRY_REASONS, isPreparationWaitRetryReason, diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index 3fb1d435835..68d43ab5e60 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -147,7 +147,7 @@ function toRunSnapshot(row: ReleaseRun): RunSnapshot { function carriedRetryAccounting(row: ReleaseRun): Record | null { const accounting = executionRetryAccounting(row); return accounting.failureRetries > 0 || accounting.maxTurnContinuations > 0 || (accounting.interruptedPreparations ?? 0) > 0 - || (accounting.storageWaits ?? 0) > 0 || (accounting.agentDirectoryWaits ?? 0) > 0 + || (accounting.storageWaits ?? 0) > 0 || (accounting.agentDirectoryWaits ?? 0) > 0 || (accounting.runtimeUpdateWaits ?? 0) > 0 || (accounting.serverRestarts ?? 0) > 0 ? { ...accounting } : null; } diff --git a/server/src/routes/connection-management-authz.ts b/server/src/routes/connection-management-authz.ts index 014455b87d8..fa577271b54 100644 --- a/server/src/routes/connection-management-authz.ts +++ b/server/src/routes/connection-management-authz.ts @@ -1,12 +1,13 @@ import { isUuidLike, type ConnectionRequiredUserAction } from "@paperclipai/shared"; import type { Request, RequestHandler } from "express"; -import { and, eq, or, sql } from "drizzle-orm"; +import { and, eq, inArray, or, sql } from "drizzle-orm"; import { type Db, toolConnections, toolApplications, toolProfiles, toolProfileEntries, toolProfileBindings, toolMcpGateways, toolMcpGatewayTokens, chatEndpoints, chatConversations, connectionGrants, connectionGrantDelegations, agents, issues, toolConnectionInstalls, heartbeatRuns, toolPolicies, toolRuntimeSlots, toolCatalogEntries, chatSlackManagerGrants, adapterAuthSessions, companySecrets, companies, companyMemberships } from "@paperclipai/db"; import { badRequest, forbidden, notFound, HttpError } from "../errors.js"; import { assertAuthenticated, assertCompanyAccess, hasCompanyAccess, getActorInfo } from "./authz.js"; import { connectionManagementService, responsibleConnectionUser, type ConnectionManagementContext } from "../services/connection-management.js"; +import { withFreshAuthorizationReads } from "../services/authorization-read-scope.js"; import type { ConnectionManagementAction, ConnectionManagementResource } from "../services/connection-management-policy.js"; const contexts = new WeakMap(); @@ -78,7 +79,7 @@ export function connectionManagementGuard(db: Db, purpose: "tool" | "chat" | "ai const management = connectionManagementService(db); return (action: ConnectionManagementAction, operation: string, options: { personal?: boolean; slackManagerGrant?: boolean } = {}): RequestHandler => async (req, _res, next) => { const rawBody = req.body ?? {}; - const authorizeRequest = async (afterHumanAction?: boolean): Promise => { + const authorizeRequest = async (afterHumanAction?: boolean): Promise => withFreshAuthorizationReads(async () => { const authorize: typeof management.authorize = (actor, requestedAction, resolved, checkOptions) => management.authorize(actor, requestedAction, resolved, { ...checkOptions, afterHumanAction }); assertAuthenticated(req); @@ -316,6 +317,22 @@ export function connectionManagementGuard(db: Db, purpose: "tool" | "chat" | "ai const companyAgents = await db.select({ id: agents.id }).from(agents).where(eq(agents.companyId, companyId)); companyAgents.forEach(agent => targets.add(agent.id)); } + // Saved profiles often repeat one account across many catalog entries. + // Resolve their references together; bindCompany below still checks each row. + const catalogIds = [...new Set(selectors.flatMap(selected => [ + ...(selected.catalogEntryId ? [uuid(selected.catalogEntryId)] : []), + ...(Array.isArray(selected.catalogEntryIds) ? selected.catalogEntryIds.map(uuid) : []), + ]))]; + if (catalogIds.length) { + const entries = await db.select({ id: toolCatalogEntries.id, companyId: toolCatalogEntries.companyId, + connectionId: toolCatalogEntries.connectionId, applicationId: toolCatalogEntries.applicationId, + }).from(toolCatalogEntries).where(inArray(toolCatalogEntries.id, catalogIds)); + const byId = new Map(entries.map(entry => [entry.id, entry])); + for (const id of catalogIds) { + const entry = byId.get(id.toLowerCase()); + lookupCache.set(`catalog:${id}`, Promise.resolve(entry ? [entry] : [])); + } + } for (let index = 0; index < selectors.length; index++) { const selected = selectors[index]; const profileOperation = operation.includes("profile"); @@ -394,7 +411,12 @@ export function connectionManagementGuard(db: Db, purpose: "tool" | "chat" | "ai const authorizeReferenced = async (afterHumanAction?: boolean) => { for (const referenced of uniqueResources.values()) { const resolved = { ...referenced, companyId: resource.companyId }; - const checkOptions = { targetAgentIds: [...targets], mutation: req.method !== "GET", afterHumanAction }; + const checkOptions = { targetAgentIds: [...targets], mutation: req.method !== "GET", afterHumanAction, + // The root authorization already expanded this profile, including + // its linked gateways and sibling accounts. Keep the profile in + // the permission scope without expanding it again for each account. + expandedProfile: Boolean(resource.profileId) && resolved.profileId === resource.profileId && resolved.gatewayId === resource.gatewayId, + }; await authorize(req.actor, action, resolved, checkOptions); if (changesGatewayBindings || changesAudience) await authorize(req.actor, "connections:profiles", resolved, checkOptions); if (action === "connections:profiles" && resolved.connectionId && req.method !== "GET" && (req.actor.type === "agent" || !resolved.selfServiceAgentInstalls)) { @@ -413,7 +435,7 @@ export function connectionManagementGuard(db: Db, purpose: "tool" | "chat" | "ai contexts.set(req, current); }; return context; - }; + }); try { contexts.set(req, await authorizeRequest()); next(); diff --git a/server/src/services/__tests__/run-failure-report-sandbox-resume.test.ts b/server/src/services/__tests__/run-failure-report-sandbox-resume.test.ts index 7109d66c990..977784b2b57 100644 --- a/server/src/services/__tests__/run-failure-report-sandbox-resume.test.ts +++ b/server/src/services/__tests__/run-failure-report-sandbox-resume.test.ts @@ -15,7 +15,7 @@ vi.mock("../../sentry.js", () => ({ import { environmentResumeErrorData, JsonRpcCallError, PLUGIN_RPC_ERROR_CODES, PluginWorkspaceOperationError, workspaceOperationErrorData } from "@paperclipai/plugin-sdk"; import { reportRunFailure } from "../run-failure-report.js"; import { REUSABLE_SANDBOX_RESUME_FAILED_CODE, ReusableSandboxResumeError } from "../reusable-sandbox-resume-error.js"; -import { WORKSPACE_STORAGE_INCOMPLETE_CODE, WORKSPACE_STORAGE_PENDING_CODE, workspaceProviderCallFailure } from "../workspace-provider-failure.js"; +import { WORKSPACE_RUNTIME_UPDATING_CODE, WORKSPACE_STORAGE_INCOMPLETE_CODE, WORKSPACE_STORAGE_PENDING_CODE, workspaceProviderCallFailure } from "../workspace-provider-failure.js"; const testDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL; const embeddedPostgresSupport = testDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); @@ -229,4 +229,20 @@ describeEmbeddedPostgres("reportRunFailure setup retry decisions", () => { expect(mockCaptureRunFailure.mock.calls[0]![0]).toMatchObject({ errorCode: run.errorCode, runStatus: "failed" }); expect(JSON.stringify(mockCaptureRunFailure.mock.calls[0]![0])).not.toContain("private provider text"); }); + + it("keeps an updating runtime local while its wait is scheduled and reports it once the wait ends", async () => { + const error = workspaceProviderCallFailure(new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, + message: "private provider text", data: workspaceOperationErrorData(new PluginWorkspaceOperationError("runtime_updating")) })); + const run = storageIncompleteRun({ errorCode: WORKSPACE_RUNTIME_UPDATING_CODE, + error: "The selected runtime is updating; retry the same workspace after the update", + resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + workspaceProviderFailure: { kind: "provider", reason: "runtime_updating", retryable: true } } }); + await reportRunFailure(db, run, { phase: "setup", error, workspaceStorageRetry: "pending" }); + await reportRunFailure(db, run, { phase: "setup", error, workspaceStorageRetry: "scheduled" }); + expect(mockCaptureRunFailure).not.toHaveBeenCalled(); + await reportRunFailure(db, run, { phase: "setup", error, workspaceStorageRetry: "not_scheduled" }); + expect(mockCaptureRunFailure).toHaveBeenCalledOnce(); + expect(mockCaptureRunFailure.mock.calls[0]![0]).toMatchObject({ errorCode: WORKSPACE_RUNTIME_UPDATING_CODE, runStatus: "failed" }); + expect(JSON.stringify(mockCaptureRunFailure.mock.calls[0]![0])).not.toContain("private provider text"); + }); }); diff --git a/server/src/services/agent-task-run-telemetry.ts b/server/src/services/agent-task-run-telemetry.ts index d8870664e39..11e5d58fce5 100644 --- a/server/src/services/agent-task-run-telemetry.ts +++ b/server/src/services/agent-task-run-telemetry.ts @@ -44,6 +44,7 @@ const PLATFORM_FAILURE_CODES = new Set([ "plugin_worker_unavailable", "workspace_storage_pending", "workspace_storage_incomplete", + "workspace_runtime_updating", "native_workspace_sync_out_retry_exhausted", "queued_run_claim_rejected", ]); diff --git a/server/src/services/authorization-read-scope.ts b/server/src/services/authorization-read-scope.ts index 49dc5323161..8bf6834f18c 100644 --- a/server/src/services/authorization-read-scope.ts +++ b/server/src/services/authorization-read-scope.ts @@ -3,10 +3,28 @@ import type { RequestHandler, Response } from "express"; export const AUTHORIZATION_READ_MAX_AGE_MS = 2_000; -type ReadScope = { open: boolean; entries: Map; readAt: number }> }; +type ReadScope = { open: boolean; check?: boolean; entries: Map; readAt: number }> }; const reads = new AsyncLocalStorage(); +/** One authorization pass, never the mutation or a later reauthorization. */ +export function withFreshAuthorizationReads(check: () => Promise): Promise { + const scope: ReadScope = { open: true, check: true, entries: new Map() }; + return reads.run(scope, async () => { + try { return await check(); } + finally { scope.open = false; scope.entries.clear(); } + }); +} + +export function readOncePerAuthorizationCheck(key: string, read: () => Promise): Promise { + return authorizationCheckScopeActive() ? readOncePerRequest(key, read) : read(); +} + +export function authorizationCheckScopeActive(): boolean { + const scope = reads.getStore(); + return scope?.check === true && scope.open; +} + function closeWhenResponseStarts(res: Response, close: () => void) { const { write, flushHeaders, writeHead } = res; res.write = function (this: Response, ...args: Parameters) { diff --git a/server/src/services/authorization.ts b/server/src/services/authorization.ts index 5ab5ed5255a..e20a5a049de 100644 --- a/server/src/services/authorization.ts +++ b/server/src/services/authorization.ts @@ -1,5 +1,5 @@ import { dashboardConversationCondition, dashboardConversationReadable } from "./responsibility-privacy.js"; -import { readOncePerRequest } from "./authorization-read-scope.js"; +import { readOncePerAuthorizationCheck, readOncePerRequest } from "./authorization-read-scope.js"; import { and, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agentInteractionDenial, type AgentInteractionDenial, type AgentInteractionOperation } from "./agent-interaction-policy.js"; @@ -1061,7 +1061,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA principalId: string, permissionKey: PermissionKey, ) { - return db + return readOncePerAuthorizationCheck(`grant:${companyId}:${principalType}:${principalId}:${permissionKey}`, () => db .select() .from(principalPermissionGrants) .where( @@ -1072,7 +1072,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA eq(principalPermissionGrants.permissionKey, permissionKey), ), ) - .then((rows) => rows[0] ?? null); + .then((rows) => rows[0] ?? null)); } async function decidePrincipalGrant(input: { diff --git a/server/src/services/connection-management.ts b/server/src/services/connection-management.ts index 035f8d7a13c..a2bc32501f1 100644 --- a/server/src/services/connection-management.ts +++ b/server/src/services/connection-management.ts @@ -1,4 +1,5 @@ import { assertAgentInteraction } from "./agent-interaction-policy.js"; +import { authorizationCheckScopeActive } from "./authorization-read-scope.js"; import { and, eq, inArray, or } from "drizzle-orm"; import { isUuidLike } from "@paperclipai/shared"; import { agents, agentApiKeys, heartbeatRuns, runIdentityContexts, issues, projects, toolApplications, toolCatalogEntries, toolConnections, toolConnectionInstalls, toolProfiles, toolProfileEntries, toolProfileBindings, toolMcpGateways, aiConnectionPools, connectionGrants, routines, type Db } from "@paperclipai/db"; @@ -269,7 +270,7 @@ export function connectionManagementService(db: Db) { expandedTargets, referencedConnections, currentGatewayResource, savedConnection }; } - async function evaluateTarget(prepared: PreparedAuthorization, targetAgentId: string | undefined): Promise { + async function evaluateTarget(prepared: PreparedAuthorization, targetAgentId: string | undefined, companyTargets?: ReadonlySet): Promise { const { actor, action, resource, responsibleUserId } = prepared; const resolved = { ...resource, ...(targetAgentId ? { targetAgentId } : {}) }; const decision = await authorization.decide({ actor, action, resource: resolved, scope: { ...resolved } }); @@ -284,7 +285,8 @@ export function connectionManagementService(db: Db) { if (!resourceTrust.allowed) throw forbidden(resourceTrust.explanation); } if (targetAgentId) { - const [target] = await db.select({ id: agents.id }).from(agents).where(and(eq(agents.id, targetAgentId), eq(agents.companyId, resource.companyId))); + const target = companyTargets ? companyTargets.has(targetAgentId) + : (await db.select({ id: agents.id }).from(agents).where(and(eq(agents.id, targetAgentId), eq(agents.companyId, resource.companyId))))[0]; if (!target) throw forbidden("Target agent is outside this company"); if (targetAgentId === resource.targetAgentId && (prepared.options.mutation ?? action !== "connections:read")) { await assertAgentToolAssignmentInteractions(db, actor.type === "agent" ? actor.agentId : null, resource.companyId, [targetAgentId]); @@ -306,9 +308,15 @@ export function connectionManagementService(db: Db) { const { actor, action, resource, options, responsibleUserId, workContext, capturedRun, expandedTargets, referencedConnections, currentGatewayResource } = prepared; const targets = [...new Set([...expandedTargets, ...(resource.targetAgentId ? [resource.targetAgentId] : [])])]; + // Preserve the ordinary lookup for noncanonical UUID spellings. Decisions + // remain per target, including scoped grants and agent interaction checks. + const companyTargets = authorizationCheckScopeActive() && targets.length && targets.every(id => isUuidLike(id) && id === id.toLowerCase()) + ? new Set((await db.select({ id: agents.id }).from(agents) + .where(and(eq(agents.companyId, resource.companyId), inArray(agents.id, targets)))).map(row => row.id)) + : undefined; let decision: AuthorizationDecision | undefined; for (const targetAgentId of targets.length ? targets : [undefined]) { - decision = await evaluateTarget(prepared, targetAgentId); + decision = await evaluateTarget(prepared, targetAgentId, companyTargets); } if (action === "connections:profiles" && resource.requestedInstallCompanyIds && !resource.selfServiceAgentInstalls) { await authorize(actor, "connections:configure", resource, options); diff --git a/server/src/services/connectors/slack/setup/manager-grants.test.ts b/server/src/services/connectors/slack/setup/manager-grants.test.ts new file mode 100644 index 00000000000..36edbdf450c --- /dev/null +++ b/server/src/services/connectors/slack/setup/manager-grants.test.ts @@ -0,0 +1,100 @@ +import { generateKeyPairSync } from "node:crypto"; +import { afterEach, describe, expect, it } from "vitest"; +import { createSlackManagerGrants } from "./manager-grants.js"; +import type { SlackRegistrationStore } from "./registration.js"; + +const ENV_KEYS = [ + "PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", + "PAPERCLIP_MANAGED_CONFIG", + "PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED", + "PAPERCLIP_CLOUD_CONNECTOR_BASE_URL", + "PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT", + "PAPERCLIP_CLOUD_CONNECTOR_INSTANCE_ID", + "PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY", + "PAPERCLIP_CLOUD_CONNECTOR_SEAL_PRIVATE_KEY", +] as const; + +const savedEnv: Partial> = {}; + +function setEnv(values: Partial>) { + for (const key of ENV_KEYS) { + if (!(key in savedEnv)) savedEnv[key] = process.env[key]; + const next = values[key]; + if (next === undefined) delete process.env[key]; + else process.env[key] = next; + } +} + +function rawPrivateKey(type: "ed25519" | "x25519") { + const { privateKey } = type === "ed25519" ? generateKeyPairSync("ed25519") : generateKeyPairSync("x25519"); + return Buffer.from(privateKey.export({ format: "jwk" }).d as string, "base64url").toString("base64url"); +} + +function minimalStore(): SlackRegistrationStore { + return { + db: {} as SlackRegistrationStore["db"], + options: { + publicOrigin: () => "https://paperclip.paperclip.app", + webhookOrigin: () => "https://paperclip.paperclip.app", + withLock: async (_id: string, fn: (lease: { assertOwned: () => Promise }) => Promise) => fn({ assertOwned: async () => {} }), + }, + endpoint: async () => { throw new Error("unused"); }, + origin: (value: string) => new URL(value).origin, + api: async () => { throw new Error("unused"); }, + } as unknown as SlackRegistrationStore; +} + +afterEach(() => { + for (const key of ENV_KEYS) { + if (key in savedEnv) { + if (savedEnv[key] === undefined) delete process.env[key]; + else process.env[key] = savedEnv[key]; + delete savedEnv[key]; + } + } +}); + +describe("createSlackManagerGrants defaultMethod on Cloud vs self-hosted", () => { + it("selects managed setup on pre-pool Cloud stacks where isCloudManagedInstance is true without runtime identity", () => { + setEnv({ + PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token-fixture", + PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED: "true", + PAPERCLIP_CLOUD_CONNECTOR_BASE_URL: "https://my.paperclip.app", + PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT: "production", + PAPERCLIP_CLOUD_CONNECTOR_INSTANCE_ID: "stack-paperclip", + PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY: rawPrivateKey("ed25519"), + PAPERCLIP_CLOUD_CONNECTOR_SEAL_PRIVATE_KEY: rawPrivateKey("x25519"), + }); + const grants = createSlackManagerGrants(minimalStore()); + expect(grants.defaultMethod()).toBe("managed"); + }); + + it("stays automatic on self-hosted instances even when managed env flag is set", () => { + setEnv({ + PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: undefined, + PAPERCLIP_MANAGED_CONFIG: undefined, + PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED: "true", + PAPERCLIP_CLOUD_CONNECTOR_BASE_URL: "https://my.paperclip.app", + PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT: "production", + PAPERCLIP_CLOUD_CONNECTOR_INSTANCE_ID: "self-hosted-1", + PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY: rawPrivateKey("ed25519"), + PAPERCLIP_CLOUD_CONNECTOR_SEAL_PRIVATE_KEY: rawPrivateKey("x25519"), + }); + const grants = createSlackManagerGrants(minimalStore()); + expect(grants.defaultMethod()).toBe("automatic"); + }); + + it("stays automatic on Cloud stacks when PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED is not true", () => { + setEnv({ + PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token-fixture", + PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED: "false", + PAPERCLIP_CLOUD_CONNECTOR_BASE_URL: "https://my.paperclip.app", + PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT: "production", + PAPERCLIP_CLOUD_CONNECTOR_INSTANCE_ID: "stack-paperclip", + PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY: rawPrivateKey("ed25519"), + PAPERCLIP_CLOUD_CONNECTOR_SEAL_PRIVATE_KEY: rawPrivateKey("x25519"), + }); + const grants = createSlackManagerGrants(minimalStore()); + expect(grants.defaultMethod()).toBe("automatic"); + }); +}); diff --git a/server/src/services/connectors/slack/setup/manager-grants.ts b/server/src/services/connectors/slack/setup/manager-grants.ts index 3d902d9928e..030ad4ce155 100644 --- a/server/src/services/connectors/slack/setup/manager-grants.ts +++ b/server/src/services/connectors/slack/setup/manager-grants.ts @@ -3,6 +3,7 @@ import { and, eq, gt, like, sql } from "drizzle-orm"; import { chatEndpoints, chatSlackManagerGrants, chatSlackRegistrations, companySecrets, toolOauthStates } from "@paperclipai/db"; import { SLACK_MANAGER_SCOPES, type SlackSetupOptions as SetupChoices } from "@paperclipai/shared"; import { conflict, forbidden } from "../../../../errors.js"; +import { isCloudManagedInstance } from "../../../cloud-instance.js"; import { getCloudRuntimeIdentity } from "../../../cloud-runtime-identity.js"; import { createPaperclipCloudConnector, paperclipCloudConnectorConfigFromEnv, type SealedConnectorCredentials } from "../../../paperclip-cloud-connector.js"; import { instanceSettingsService } from "../../../instance-settings.js"; @@ -19,12 +20,13 @@ export function createSlackManagerGrants(store: SlackRegistrationStore) { type Database = Parameters[0]; function broker(): SlackManagerClient | null { if (options.managed) return options.managed.enabled ? options.managed.broker : null; - if (!getCloudRuntimeIdentity()) { + const isCloud = Boolean(getCloudRuntimeIdentity()) || isCloudManagedInstance(); + if (!isCloud) { const development = developmentSlackManager(() => origin(options.publicOrigin())); if (development) return development; } // Open-source instances never contact a hosted service to discover this path. - if (!getCloudRuntimeIdentity() || process.env.PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED !== "true") return null; + if (!isCloud || process.env.PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED !== "true") return null; const config = paperclipCloudConnectorConfigFromEnv(); return config ? createPaperclipCloudConnector({ config }) : null; } diff --git a/server/src/services/execution-recovery-attempt.test.ts b/server/src/services/execution-recovery-attempt.test.ts index 128cccbe3a9..c2de87a09b7 100644 --- a/server/src/services/execution-recovery-attempt.test.ts +++ b/server/src/services/execution-recovery-attempt.test.ts @@ -2,7 +2,9 @@ import { describe, expect, it } from "vitest"; import { accountingForScheduledRetry, AGENT_DIRECTORY_WAIT_RETRY_REASON, executionFailureRetryCount, executionRetryAttemptCount, INTERRUPTED_PREPARATION_RETRY_MAX_ATTEMPTS, INTERRUPTED_PREPARATION_RETRY_REASON } from "./execution-recovery-attempt.js"; import { AGENT_DIRECTORY_BUSY_MAX_DEFERRALS } from "./heartbeat/agent-directory-busy.js"; import { RUNNER_REVISION_WAIT_RETRY_REASON } from "./runner-revision-mismatch.js"; -import { RUNNER_REVISION_WAIT_RETRY_REASON as DISPATCH_RUNNER_REVISION_WAIT_RETRY_REASON } from "../modules/run-dispatch/index.js"; +import { isPreparationWaitRetryReason, RUNNER_REVISION_WAIT_RETRY_REASON as DISPATCH_RUNNER_REVISION_WAIT_RETRY_REASON, + RUNTIME_UPDATE_WAIT_RETRY_REASON as DISPATCH_RUNTIME_UPDATE_WAIT_RETRY_REASON } from "../modules/run-dispatch/index.js"; +import { RUNTIME_UPDATE_WAIT_RETRY_REASON } from "./workspace-provider-failure.js"; describe("failure attempts across resource waits", () => { it("preserves prior failures through subscription waits without trusting unrelated context", () => { @@ -30,7 +32,7 @@ describe("failure attempts across resource waits", () => { }); describe("persisted independent accounting", () => { - it.each(["max_turns_continuation", "issue_disposition_repair", "workspace_busy", "ai_connection_busy", "ai_connection_pool_wait", "runner_revision_wait", "storage_unavailable_wait"])("%s cannot erase prior infrastructure debits or spend more", scheduledRetryReason => { + it.each(["max_turns_continuation", "issue_disposition_repair", "workspace_busy", "ai_connection_busy", "ai_connection_pool_wait", "runner_revision_wait", "storage_unavailable_wait", "runtime_update_wait"])("%s cannot erase prior infrastructure debits or spend more", scheduledRetryReason => { expect(executionFailureRetryCount({ scheduledRetryReason, scheduledRetryAttempt: 20, contextSnapshot: { executionRetryAccounting: { version: 1, failureRetries: 2, maxTurnContinuations: 1 } }, })).toBe(2); @@ -123,6 +125,21 @@ describe("storage outage waits", () => { }); }); +describe("runtime update waits", () => { + it("keep their count through an intervening workspace wait", () => { + const afterUpdateWait = { scheduledRetryReason: "runtime_update_wait", scheduledRetryAttempt: 29, + contextSnapshot: { executionRetryAccounting: { version: 1, failureRetries: 1, maxTurnContinuations: 0 } } }; + const ledger = accountingForScheduledRetry(afterUpdateWait, "workspace_busy", 1); + expect(ledger).toMatchObject({ runtimeUpdateWaits: 29, failureRetries: 1 }); + const afterWorkspaceWait = { scheduledRetryReason: "workspace_busy", scheduledRetryAttempt: 1, + contextSnapshot: { executionRetryAccounting: ledger } }; + // The update-wait limit does not restart after another lane's retry. + expect(executionRetryAttemptCount(afterWorkspaceWait, "runtime_update_wait")).toBe(29); + expect(accountingForScheduledRetry(afterWorkspaceWait, "runtime_update_wait", 30)).toMatchObject({ runtimeUpdateWaits: 30, failureRetries: 1 }); + expect(executionFailureRetryCount(afterWorkspaceWait)).toBe(1); + }); +}); + describe("agent directory waits", () => { it("keep their count through alternating workspace waits and stop at the bound", () => { let run: { scheduledRetryReason: string; scheduledRetryAttempt: number; contextSnapshot: Record } = { @@ -143,3 +160,15 @@ describe("agent directory waits", () => { expect(executionFailureRetryCount(run)).toBe(1); }); }); + +describe("updating-runtime waits", () => { + it("use the same retry reason as run dispatch and never spend the failure retry budget", () => { + expect(RUNTIME_UPDATE_WAIT_RETRY_REASON).toBe(DISPATCH_RUNTIME_UPDATE_WAIT_RETRY_REASON); + expect(isPreparationWaitRetryReason(RUNTIME_UPDATE_WAIT_RETRY_REASON)).toBe(true); + const waited = { scheduledRetryReason: "runtime_update_wait", scheduledRetryAttempt: 29, + contextSnapshot: { executionRetryAccounting: { version: 1, failureRetries: 1, maxTurnContinuations: 0 } } }; + expect(executionRetryAttemptCount(waited, "runtime_update_wait")).toBe(29); + expect(accountingForScheduledRetry(waited, "runtime_update_wait", 30)).toMatchObject({ failureRetries: 1 }); + expect(executionFailureRetryCount(waited)).toBe(1); + }); +}); diff --git a/server/src/services/execution-recovery-attempt.ts b/server/src/services/execution-recovery-attempt.ts index f7d3499b24a..885eee70dda 100644 --- a/server/src/services/execution-recovery-attempt.ts +++ b/server/src/services/execution-recovery-attempt.ts @@ -1,6 +1,7 @@ import { RUNNER_REVISION_WAIT_RETRY_REASON } from "./runner-revision-mismatch.js"; import { STORAGE_UNAVAILABLE_WAIT_RETRY_REASON } from "../storage/storage-unavailable.js"; import { ENVIRONMENT_PROVIDER_WAIT_RETRY_REASON } from "./environment-provider-wait.js"; +import { RUNTIME_UPDATE_WAIT_RETRY_REASON } from "./workspace-provider-failure.js"; import { PROVIDER_ATTEMPT_CREDIT_GENERATION_LIMIT } from "./native-runtime/provider-attempt-outcome.js"; import { NATIVE_RESUME_REFUSED_CONTINUATION_CODE } from "./native-runtime/native-resume-refused-continuation.js"; import { AGENT_DIRECTORY_BUSY_RETRY_REASON } from "../modules/run-dispatch/index.js"; @@ -33,7 +34,7 @@ export const SERVER_RESTART_RETRY_WINDOW_MS = 60 * 60_000; const UNCHARGED_RETRY_LANES: ReadonlySet = new Set([ "workspace_busy", "ai_connection_busy", "ai_connection_pool_wait", AGENT_DIRECTORY_WAIT_RETRY_REASON, RUNNER_REVISION_WAIT_RETRY_REASON, INTERRUPTED_PREPARATION_RETRY_REASON, STORAGE_UNAVAILABLE_WAIT_RETRY_REASON, SERVER_RESTART_RETRY_REASON, - ENVIRONMENT_PROVIDER_WAIT_RETRY_REASON, NATIVE_RESUME_REFUSED_CONTINUATION_CODE, + ENVIRONMENT_PROVIDER_WAIT_RETRY_REASON, NATIVE_RESUME_REFUSED_CONTINUATION_CODE, RUNTIME_UPDATE_WAIT_RETRY_REASON, ]); type RetryRun = { @@ -57,6 +58,8 @@ export interface ExecutionRetryAccounting { storageWaits?: number; /** Agent-directory waits in this chain, kept across intervening resource waits. Omitted while zero. */ agentDirectoryWaits?: number; + /** Updating-runtime waits in this chain, kept across intervening resource waits. Omitted while zero. */ + runtimeUpdateWaits?: number; /** Server-restart continuations in the current window. Omitted while zero. */ serverRestarts?: number; /** Start of the current server-restart window (ISO time). Saved with serverRestarts. */ @@ -77,6 +80,7 @@ function savedAccounting(run: RetryRun): ExecutionRetryAccounting | null { const interruptedPreparations = count(saved.interruptedPreparations) ?? 0; const storageWaits = count(saved.storageWaits) ?? 0; const agentDirectoryWaits = count(saved.agentDirectoryWaits) ?? 0; + const runtimeUpdateWaits = count(saved.runtimeUpdateWaits) ?? 0; const serverRestarts = count(saved.serverRestarts) ?? 0; const windowStartedAt = typeof saved.serverRestartWindowStartedAt === "string" && Number.isFinite(Date.parse(saved.serverRestartWindowStartedAt)) ? saved.serverRestartWindowStartedAt : null; @@ -84,6 +88,7 @@ function savedAccounting(run: RetryRun): ExecutionRetryAccounting | null { ...(interruptedPreparations > 0 ? { interruptedPreparations } : {}), ...(storageWaits > 0 ? { storageWaits } : {}), ...(agentDirectoryWaits > 0 ? { agentDirectoryWaits } : {}), + ...(runtimeUpdateWaits > 0 ? { runtimeUpdateWaits } : {}), ...(serverRestarts > 0 && windowStartedAt ? { serverRestarts, serverRestartWindowStartedAt: windowStartedAt } : {}) }; } @@ -111,6 +116,8 @@ export function executionRetryAccounting(run: RetryRun): ExecutionRetryAccountin reason === STORAGE_UNAVAILABLE_WAIT_RETRY_REASON ? count(run.scheduledRetryAttempt) ?? 0 : 0); const agentDirectoryWaits = Math.max(saved?.agentDirectoryWaits ?? 0, reason === AGENT_DIRECTORY_WAIT_RETRY_REASON ? count(run.scheduledRetryAttempt) ?? 0 : 0); + const runtimeUpdateWaits = Math.max(saved?.runtimeUpdateWaits ?? 0, + reason === RUNTIME_UPDATE_WAIT_RETRY_REASON ? count(run.scheduledRetryAttempt) ?? 0 : 0); return { version: 1, failureRetries: Math.max(saved?.failureRetries ?? 0, saved && nonFailureLane ? 0 : historicalFailureCount(run)), @@ -119,6 +126,7 @@ export function executionRetryAccounting(run: RetryRun): ExecutionRetryAccountin ...(interruptedPreparations > 0 ? { interruptedPreparations } : {}), ...(storageWaits > 0 ? { storageWaits } : {}), ...(agentDirectoryWaits > 0 ? { agentDirectoryWaits } : {}), + ...(runtimeUpdateWaits > 0 ? { runtimeUpdateWaits } : {}), ...(saved?.serverRestarts ? { serverRestarts: saved.serverRestarts, serverRestartWindowStartedAt: saved.serverRestartWindowStartedAt } : {}), }; @@ -146,6 +154,7 @@ export function executionRetryAttemptCount(run: RetryRun, reason: string): numbe if (reason === INTERRUPTED_PREPARATION_RETRY_REASON) return executionRetryAccounting(run).interruptedPreparations ?? 0; if (reason === STORAGE_UNAVAILABLE_WAIT_RETRY_REASON) return executionRetryAccounting(run).storageWaits ?? 0; if (reason === AGENT_DIRECTORY_WAIT_RETRY_REASON) return executionRetryAccounting(run).agentDirectoryWaits ?? 0; + if (reason === RUNTIME_UPDATE_WAIT_RETRY_REASON) return executionRetryAccounting(run).runtimeUpdateWaits ?? 0; if (UNCHARGED_RETRY_LANES.has(reason)) { return run.scheduledRetryReason === reason ? count(run.scheduledRetryAttempt) ?? 0 : 0; } @@ -165,6 +174,7 @@ export function accountingForScheduledRetry(run: RetryRun, reason: string, attem else if (reason === INTERRUPTED_PREPARATION_RETRY_REASON) accounting.interruptedPreparations = attempt; else if (reason === STORAGE_UNAVAILABLE_WAIT_RETRY_REASON) accounting.storageWaits = attempt; else if (reason === AGENT_DIRECTORY_WAIT_RETRY_REASON) accounting.agentDirectoryWaits = attempt; + else if (reason === RUNTIME_UPDATE_WAIT_RETRY_REASON) accounting.runtimeUpdateWaits = attempt; else if (!UNCHARGED_RETRY_LANES.has(reason)) accounting.failureRetries = attempt; return accounting; } diff --git a/server/src/services/failed-preparation-retry.ts b/server/src/services/failed-preparation-retry.ts index bdb59400d58..a07130867cf 100644 --- a/server/src/services/failed-preparation-retry.ts +++ b/server/src/services/failed-preparation-retry.ts @@ -10,7 +10,7 @@ import { REUSABLE_SANDBOX_RESUME_FAILED_CODE } from "./reusable-sandbox-resume-e import { REVIEWED_CHAT_BINDING_NOT_READY } from "./reviewed-chat-binding-diagnostics.js"; import { RUNNER_REVISION_MISMATCH_CODE } from "./runner-revision-mismatch.js"; import { WORKSPACE_GIT_SCAN_ERROR_CODES } from "./workspace-git-operation-scheduler.js"; -import { WORKSPACE_STORAGE_INCOMPLETE_CODE, WORKSPACE_STORAGE_PENDING_CODE } from "./workspace-provider-failure.js"; +import { WORKSPACE_RUNTIME_UPDATING_CODE, WORKSPACE_STORAGE_INCOMPLETE_CODE, WORKSPACE_STORAGE_PENDING_CODE } from "./workspace-provider-failure.js"; type HeartbeatRun = typeof heartbeatRuns.$inferSelect; @@ -21,6 +21,7 @@ export const TRANSIENT_WORKSPACE_PREPARATION_CODES: readonly string[] = [ RUNNER_REVISION_MISMATCH_CODE, ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, REPOSITORY_CATALOG_UNAVAILABLE_CODE, REVIEWED_CHAT_BINDING_NOT_READY, STORAGE_UNAVAILABLE_CODE, WORKSPACE_STORAGE_PENDING_CODE, WORKSPACE_STORAGE_INCOMPLETE_CODE, + WORKSPACE_RUNTIME_UPDATING_CODE, ]; /** Transient setup codes whose accepted-interaction wakes stay on the interaction continuation retry lane. */ diff --git a/server/src/services/heartbeat/retries.test.ts b/server/src/services/heartbeat/retries.test.ts index 10ea547bbad..acf157f1c46 100644 --- a/server/src/services/heartbeat/retries.test.ts +++ b/server/src/services/heartbeat/retries.test.ts @@ -141,6 +141,25 @@ describe("heartbeat retry module callbacks", () => { expect(database.access).not.toHaveBeenCalled(); }); + it("gives every caller the updating-runtime wait budget and reports its exhaustion", async () => { + const database = guardedDatabase(); + const deps = callbacks(); + const run = { ...unitRun(), status: "failed", errorCode: "workspace_runtime_updating", scheduledRetryReason: "runtime_update_wait", scheduledRetryAttempt: 30, + contextSnapshot: { issueId: "issue", executionRetryAccounting: { version: 1, failureRetries: 0, maxTurnContinuations: 0 } } } as Run; + const retry = await extracted.createHeartbeatRetries(database.db, deps).scheduleBoundedRetryForRun(run, { adapterType: "codex_local" } as Agent); + expect(retry).toMatchObject({ outcome: "retry_exhausted", attempt: 31, maxAttempts: 30 }); + expect(deps.appendRunEvent).toHaveBeenCalledWith(run, expect.objectContaining({ + retryExhaustion: { retryReason: "runtime_update_wait", scheduledRetryAttempt: 30, maxAttempts: 30 }, + })); + expect(extracted.failedRunRetryBudgetSpent(run)).toBe(true); + // Two transient failures before the update began do not shorten the wait. + expect(extracted.failedRunRetryBudgetSpent({ ...run, scheduledRetryAttempt: 29, contextSnapshot: { issueId: "issue", + executionRetryAccounting: { version: 1, failureRetries: 2, maxTurnContinuations: 0 } } })).toBe(false); + expect(extracted.failedRunRetryBudgetSpent({ ...run, scheduledRetryReason: "transient_failure", scheduledRetryAttempt: 2, + contextSnapshot: { issueId: "issue", executionRetryAccounting: { version: 1, failureRetries: 2, maxTurnContinuations: 0 } } })).toBe(false); + expect(database.access).not.toHaveBeenCalled(); + }); + it("ends an answered interaction's storage wait at its limit and escalates it", async () => { const database = guardedDatabase(); const deps = callbacks(); @@ -153,6 +172,18 @@ describe("heartbeat retry module callbacks", () => { expect(deps.escalatePlanApprovalResumeFailureNeedsAttention).toHaveBeenCalledWith(expect.objectContaining({ run, maxAttempts: 10 })); }); + it("ends an answered interaction's runtime update wait at its limit and escalates it", async () => { + const database = guardedDatabase(); + const deps = callbacks(); + const run = { ...unitRun(), status: "failed", errorCode: "workspace_runtime_updating", scheduledRetryReason: "runtime_update_wait", scheduledRetryAttempt: 30, + contextSnapshot: { issueId: "issue", interactionId: "interaction-1", interactionStatus: "accepted", interactionKind: "request_confirmation", + mutation: "interaction", retryReason: "runtime_update_wait", + executionRetryAccounting: { version: 1, failureRetries: 0, maxTurnContinuations: 0 } } } as Run; + const retry = await extracted.createHeartbeatRetries(database.db, deps).scheduleBoundedRetryForRun(run, { adapterType: "codex_local" } as Agent); + expect(retry).toMatchObject({ outcome: "retry_exhausted", maxAttempts: 30 }); + expect(deps.escalatePlanApprovalResumeFailureNeedsAttention).toHaveBeenCalledWith(expect.objectContaining({ run, maxAttempts: 30 })); + }); + it("leaves successor work to the committed case handoff without retry escalation", async () => { const database = guardedDatabase(); const deps = callbacks(); diff --git a/server/src/services/heartbeat/retries.ts b/server/src/services/heartbeat/retries.ts index 1250864ed21..b0318a15106 100644 --- a/server/src/services/heartbeat/retries.ts +++ b/server/src/services/heartbeat/retries.ts @@ -41,6 +41,7 @@ import { REPOSITORY_CATALOG_UNAVAILABLE_CODE } from "../repository-catalog-unava import { REVIEWED_CHAT_BINDING_NOT_READY } from "../reviewed-chat-binding-diagnostics.js"; import { RUNNER_REVISION_MISMATCH_CODE, RUNNER_REVISION_MISMATCH_RETRY, RUNNER_REVISION_WAIT_RETRY_REASON } from "../runner-revision-mismatch.js"; import { STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_RETRY, STORAGE_UNAVAILABLE_WAIT_RETRY_REASON } from "../../storage/storage-unavailable.js"; +import { WORKSPACE_RUNTIME_UPDATING_CODE, WORKSPACE_RUNTIME_UPDATING_RETRY } from "../workspace-provider-failure.js"; import { CONTROLLER_LEASE_LOST_FAILURE_CODE } from "../legacy-controller-lease.js"; import { ENVIRONMENT_PROVIDER_WAIT_KEY, ENVIRONMENT_PROVIDER_WAIT_RETRY_REASON, environmentProviderWaitFor, environmentProviderWaitRetry } from "../environment-provider-wait.js"; import { randomUUID } from "node:crypto"; @@ -201,7 +202,9 @@ export function failedRunRetryBudgetSpent(run: Parameters= RUNNER_REVISION_MISMATCH_RETRY.maxAttempts : run.errorCode === STORAGE_UNAVAILABLE_CODE ? executionRetryAttemptCount(run, STORAGE_UNAVAILABLE_WAIT_RETRY_REASON) >= STORAGE_UNAVAILABLE_RETRY.maxAttempts - : executionFailureRetryCount(run) >= BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS + : run.errorCode === WORKSPACE_RUNTIME_UPDATING_CODE + ? executionRetryAttemptCount(run, WORKSPACE_RUNTIME_UPDATING_RETRY.retryReason) >= WORKSPACE_RUNTIME_UPDATING_RETRY.maxAttempts + : executionFailureRetryCount(run) >= BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS || executionRetryAttemptCount(run, INTERRUPTED_PREPARATION_RETRY_REASON) >= INTERRUPTED_PREPARATION_RETRY_MAX_ATTEMPTS; } @@ -530,6 +533,7 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen } if (!opts?.retryReason && run.errorCode === RUNNER_REVISION_MISMATCH_CODE) opts = { ...RUNNER_REVISION_MISMATCH_RETRY, ...opts }; if (!opts?.retryReason && run.errorCode === STORAGE_UNAVAILABLE_CODE) opts = { ...STORAGE_UNAVAILABLE_RETRY, ...opts }; + if (!opts?.retryReason && run.errorCode === WORKSPACE_RUNTIME_UPDATING_CODE) opts = { ...WORKSPACE_RUNTIME_UPDATING_RETRY, ...opts }; if (!opts?.retryReason && run.errorCode === ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE && (run.scheduledRetryReason === ENVIRONMENT_PROVIDER_WAIT_RETRY_REASON || executionFailureRetryCount(run) >= BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS)) { @@ -657,7 +661,9 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen payload: exhaustion, retryExhaustion: exhaustion, }); - if (retryReason === INTERACTION_CONTINUATION_INFRA_RETRY_REASON || (retryReason === STORAGE_UNAVAILABLE_WAIT_RETRY_REASON + // An answered interaction whose preparation wait ran out gets the same handoff as an exhausted interaction retry. + if (retryReason === INTERACTION_CONTINUATION_INFRA_RETRY_REASON || ((retryReason === STORAGE_UNAVAILABLE_WAIT_RETRY_REASON + || retryReason === WORKSPACE_RUNTIME_UPDATING_RETRY.retryReason) && isResolvedInteractionContinuationWakeContext(run.contextSnapshot))) { await escalatePlanApprovalResumeFailureNeedsAttention({ run, diff --git a/server/src/services/heartbeat/run-completion.test.ts b/server/src/services/heartbeat/run-completion.test.ts index b0f061a6407..1d8b872ed18 100644 --- a/server/src/services/heartbeat/run-completion.test.ts +++ b/server/src/services/heartbeat/run-completion.test.ts @@ -36,7 +36,7 @@ import { environmentTaskErrorCodeData, JsonRpcCallError, PLUGIN_RPC_ERROR_CODES, import { RUNNER_REVISION_MISMATCH_RETRY } from "../runner-revision-mismatch.js"; import { STORAGE_CREDENTIALS_REJECTED_HELD_MESSAGE, STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, STORAGE_UNAVAILABLE_HELD_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_RETRY } from "../../storage/storage-unavailable.js"; import { withS3FailureDiagnostics } from "../../storage/s3-failure.js"; -import { workspaceProviderCallFailure } from "../workspace-provider-failure.js"; +import { WORKSPACE_RUNTIME_UPDATING_RETRY, workspaceProviderCallFailure } from "../workspace-provider-failure.js"; import { logger } from "../../middleware/logger.js"; import { unprocessable } from "../../errors.js"; import { ACCOUNTING_CONTENTION_MESSAGE, AccountingContentionError } from "../accounting-transaction.js"; @@ -1875,6 +1875,34 @@ describe.skipIf(!support.supported && !process.env.PAPERCLIP_TEST_DATABASE_URL)( } else expect(f.deps.scheduleBoundedRetryForRun).not.toHaveBeenCalled(); }); + const runtimeUpdating = () => workspaceProviderCallFailure(new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, + message: "private provider text", data: workspaceOperationErrorData(new PluginWorkspaceOperationError("runtime_updating")) })); + + it.each(["fresh", "started", "retained"] as const)("waits for an updating runtime after a %s refusal instead of the two-attempt bootstrap retry", async scenario => { + const f = await fixture({ runtimeMode: scenario === "retained" ? "native" : "legacy" }); + f.deps.scheduleBoundedRetryForRun.mockResolvedValueOnce({ outcome: "not_scheduled", reason: "Fixture scheduler boundary", issueId: null }); + await f.completion.failRunSetup(f.setup(runtimeUpdating(), scenario === "started")); + const failed = await read(f.run.id); + expect(failed).toMatchObject({ status: "failed", errorCode: scenario === "fresh" ? "workspace_runtime_updating" : "setup_failed", + error: "The selected runtime is updating; retry the same workspace after the update" }); + expect(failed.error).not.toContain("private"); + if (scenario === "fresh") { + expect(failed.resultJson).toMatchObject({ executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + workspaceProviderFailure: { kind: "provider", reason: "runtime_updating", retryable: true } }); + expect(f.deps.scheduleBoundedRetryForRun).toHaveBeenCalledWith(expect.objectContaining({ id: f.run.id }), f.agent, WORKSPACE_RUNTIME_UPDATING_RETRY); + } else expect(f.deps.scheduleBoundedRetryForRun).not.toHaveBeenCalled(); + }); + + it("waits for an updating runtime on an answered interaction instead of its two-attempt continuation retry", async () => { + const f = await fixture({ contextSnapshot: { interactionId: "interaction-1", interactionStatus: "answered", interactionKind: "ask_user_questions", + mutation: "interaction", wakeReason: "issue_commented" } }); + f.deps.scheduleBoundedRetryForRun.mockResolvedValueOnce({ outcome: "not_scheduled", reason: "Fixture scheduler boundary", issueId: null }); + await f.completion.failRunSetup(f.setup(runtimeUpdating())); + expect(await read(f.run.id)).toMatchObject({ status: "failed", errorCode: "workspace_runtime_updating" }); + expect(f.deps.scheduleBoundedRetryForRun).toHaveBeenCalledWith(expect.objectContaining({ id: f.run.id }), f.agent, WORKSPACE_RUNTIME_UPDATING_RETRY); + expect(f.deps.scheduleInteractionContinuationInfrastructureRetryIfEligible).not.toHaveBeenCalled(); + }); + it.each(["context_changed", "deadline_exceeded"] as const)("keeps a retryable %s provider answer a generic setup failure", async reason => { const f = await fixture(); await f.completion.failRunSetup(f.setup(workspaceProviderCallFailure(new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, diff --git a/server/src/services/heartbeat/run-completion.ts b/server/src/services/heartbeat/run-completion.ts index 2739bede80d..13ede6a8124 100644 --- a/server/src/services/heartbeat/run-completion.ts +++ b/server/src/services/heartbeat/run-completion.ts @@ -40,7 +40,8 @@ import { findReusableSandboxResumeError } from "../reusable-sandbox-resume-error import { findPluginWorkerUnavailableError, PLUGIN_WORKER_UNAVAILABLE_CODE } from "../plugin-worker-unavailable-error.js"; import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, findEnvironmentProviderUnavailableError } from "../environment-provider-unavailable-error.js"; import { REPOSITORY_CATALOG_UNAVAILABLE_CODE, findRepositoryCatalogUnavailableError } from "../repository-catalog-unavailable-error.js"; -import { findRetryableWorkspaceStorageSetupCode, findWorkspaceProviderFailure, WORKSPACE_STORAGE_RETRY_CODES } from "../workspace-provider-failure.js"; +import { findRetryableWorkspaceStorageSetupCode, findWorkspaceProviderFailure, WORKSPACE_RUNTIME_UPDATING_CODE, WORKSPACE_RUNTIME_UPDATING_RETRY, + WORKSPACE_STORAGE_RETRY_CODES } from "../workspace-provider-failure.js"; import { isRunnerRevisionMismatch, RUNNER_REVISION_MISMATCH_CODE, RUNNER_REVISION_MISMATCH_RETRY } from "../runner-revision-mismatch.js"; import { readPluginTaskError } from "../environment-task-runtime.js"; import { isStorageUnavailableError, STORAGE_CREDENTIALS_REJECTED_MESSAGE, STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_RETRY, storageUnavailableHeldMessage, storageUnavailableMessage } from "../../storage/storage-unavailable.js"; @@ -1736,7 +1737,8 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC const pluginWorkerUnavailableFailure = !providerDispatchStarted && run.runtimeMode === "legacy" && run.nativeSessionId === null && run.runnerInstanceId === null ? findPluginWorkerUnavailableError(outerErr) : null; // Retryable pre-dispatch workspace storage failures (`storage_pending` and - // `remote_incomplete`) retry the same workspace within the bootstrap budget. + // `remote_incomplete`) retry the same workspace within the bootstrap budget; + // an updating runtime (`runtime_updating`) waits in its own lane. const workspaceStorageRetryCode = !providerDispatchStarted && run.runtimeMode === "legacy" && run.nativeSessionId === null && run.runnerInstanceId === null ? findRetryableWorkspaceStorageSetupCode(outerErr) : null; @@ -1976,7 +1978,9 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC ? scheduleBoundedRetryForRun(livenessRun, failedAgent, RUNNER_REVISION_MISMATCH_RETRY) : livenessRun.errorCode === STORAGE_UNAVAILABLE_CODE ? scheduleBoundedRetryForRun(livenessRun, failedAgent, STORAGE_UNAVAILABLE_RETRY) - : scheduleBoundedRetryForRun(livenessRun, failedAgent) + : livenessRun.errorCode === WORKSPACE_RUNTIME_UPDATING_CODE + ? scheduleBoundedRetryForRun(livenessRun, failedAgent, WORKSPACE_RUNTIME_UPDATING_RETRY) + : scheduleBoundedRetryForRun(livenessRun, failedAgent) : scheduleNativePreDispatchRetry(livenessRun, failedAgent).then(nativeRetry => nativeRetry ?? scheduleInteractionContinuationInfrastructureRetryIfEligible(livenessRun, failedAgent)) ).catch((retryError) => { diff --git a/server/src/services/legacy-execution-recovery.ts b/server/src/services/legacy-execution-recovery.ts index 7d3980ab94d..e06c38919ee 100644 --- a/server/src/services/legacy-execution-recovery.ts +++ b/server/src/services/legacy-execution-recovery.ts @@ -10,7 +10,7 @@ import { isPreDispatchExecutionWaitVerified } from "./pre-dispatch-execution-wai import { REMOTE_WORKSPACE_PREPARATION_TIMEOUT_CODE, REMOTE_WORKSPACE_RESTORE_FAILED_CODE } from "./remote-workspace-transport.js"; import { REUSABLE_SANDBOX_RESUME_FAILED_CODE } from "./reusable-sandbox-resume-error.js"; import { PLUGIN_WORKER_UNAVAILABLE_CODE } from "./plugin-worker-unavailable-error.js"; -import { WORKSPACE_STORAGE_INCOMPLETE_CODE, WORKSPACE_STORAGE_PENDING_CODE } from "./workspace-provider-failure.js"; +import { WORKSPACE_RUNTIME_UPDATING_CODE, WORKSPACE_STORAGE_INCOMPLETE_CODE, WORKSPACE_STORAGE_PENDING_CODE } from "./workspace-provider-failure.js"; import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE } from "./environment-provider-unavailable-error.js"; import { REPOSITORY_CATALOG_UNAVAILABLE_CODE } from "./repository-catalog-unavailable-error.js"; import { RUNNER_REVISION_MISMATCH_CODE } from "./runner-revision-mismatch.js"; @@ -91,6 +91,7 @@ export function legacyExecutionNeedsReconciliation( || run.errorCode === REMOTE_WORKSPACE_PREPARATION_TIMEOUT_CODE || run.errorCode === REUSABLE_SANDBOX_RESUME_FAILED_CODE || run.errorCode === REMOTE_WORKSPACE_RESTORE_FAILED_CODE || run.errorCode === PLUGIN_WORKER_UNAVAILABLE_CODE || run.errorCode === WORKSPACE_STORAGE_PENDING_CODE || run.errorCode === WORKSPACE_STORAGE_INCOMPLETE_CODE + || run.errorCode === WORKSPACE_RUNTIME_UPDATING_CODE || run.errorCode === RUNNER_REVISION_MISMATCH_CODE || run.errorCode === ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE || run.errorCode === REPOSITORY_CATALOG_UNAVAILABLE_CODE) && evidence?.kind === "bootstrap" && evidence.providerWorkStarted === false) return false; diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 7359fa46f75..a02a151b952 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -201,7 +201,7 @@ import { } from "./origins.js"; import { withRecoveryContext } from "./status-only-context.js"; import { getExecutionBlocker } from "../execution-blocker.js"; -import { readWorkspaceProviderFailure, WORKSPACE_STORAGE_INCOMPLETE_CODE, WORKSPACE_STORAGE_PENDING_CODE } from "../workspace-provider-failure.js"; +import { readWorkspaceProviderFailure, WORKSPACE_RUNTIME_UPDATING_CODE, WORKSPACE_STORAGE_INCOMPLETE_CODE, WORKSPACE_STORAGE_PENDING_CODE } from "../workspace-provider-failure.js"; import { currentRunFailureText } from "../native-runtime/native-exact-resume-failure.js"; import { isAutomaticRecoverySuppressedByPauseHold } from "./pause-hold-guard.js"; import { rehomeStrandedLegacyWorkspaceTasks } from "./legacy-workspace-rehome.js"; @@ -661,6 +661,7 @@ const NON_RETRYABLE_CONTINUATION_ERROR_CODES = new Set([ PLUGIN_WORKER_UNAVAILABLE_CODE, WORKSPACE_STORAGE_PENDING_CODE, WORKSPACE_STORAGE_INCOMPLETE_CODE, + WORKSPACE_RUNTIME_UPDATING_CODE, ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, RUNNER_REVISION_MISMATCH_CODE, "low_trust_isolation_unavailable", diff --git a/server/src/services/recovery/stranded-notice.ts b/server/src/services/recovery/stranded-notice.ts index 9de2029ccd7..0cce199deb9 100644 --- a/server/src/services/recovery/stranded-notice.ts +++ b/server/src/services/recovery/stranded-notice.ts @@ -84,6 +84,7 @@ const WORKSPACE_SCAN_NOTICES: Record([WORKSPACE_BUSY_RETRY_REASON, AI_CONNECTION_BUSY_RETRY_REASON, AI_CONNECTION_POOL_WAIT_RETRY_REASON, RUNNER_REVISION_WAIT_RETRY_REASON, STORAGE_UNAVAILABLE_WAIT_RETRY_REASON, - AGENT_DIRECTORY_WAIT_RETRY_REASON]); + AGENT_DIRECTORY_WAIT_RETRY_REASON, RUNTIME_UPDATE_WAIT_RETRY_REASON]); // A due same-run resume dispatches within seconds; past this, offer Retry. const NATIVE_RESUME_DISPATCH_GRACE_MS = 2 * 60_000; diff --git a/server/src/services/tool-access/catalog/aggregator-accounts.ts b/server/src/services/tool-access/catalog/aggregator-accounts.ts index 732591d122b..d802c041463 100644 --- a/server/src/services/tool-access/catalog/aggregator-accounts.ts +++ b/server/src/services/tool-access/catalog/aggregator-accounts.ts @@ -6,7 +6,7 @@ import { AGGREGATOR_NAMES, isAppAggregator, type AggregatorAppsResponse, type Ar import { resolveAggregatorApp, type AppCatalogAggregator } from "@paperclipai/shared/aggregator-app-catalog"; import { AggregatorDiscoveryUnavailableError, discoverArcadeApps, discoverExecutorApps, type DiscoveredApp } from "../../aggregator-app-discovery.js"; import { COMPOSIO_APP_TOOLKITS, findComposioCatalogApp } from "@paperclipai/shared/aggregator-app-catalog"; -import type { ComposioAppAccount, ComposioAppAccountInput, ComposioAppSetupInput, ComposioAppSetupResult, ComposioAppSnapshot, ComposioAppsResponse } from "@paperclipai/shared"; +import { COMPOSIO_SIGN_IN_LINK_MISSING, type ComposioAppAccount, type ComposioAppAccountInput, type ComposioAppSetupInput, type ComposioAppSetupResult, type ComposioAppSnapshot, type ComposioAppsResponse } from "@paperclipai/shared"; import { composioAddAccountLink, composioAppAccounts, composioAppSetupResult } from "../../composio-app-setup.js"; import { createHash, randomUUID } from "node:crypto"; import { and, asc, desc, eq, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm"; @@ -454,7 +454,11 @@ export function createAggregatorAccounts(db: Db, { options, secrets, audit, cred result = composioAppSetupResult(await opened.manage([{ name: toolkit, action: "list" }]), toolkit); if (input.action === "start" && result.status !== "connected") { result = composioAppSetupResult(await opened.manage([{ name: toolkit, action: "add" }]), toolkit); - if (result.status === "not_connected") throw unprocessable("Composio did not return a sign-in link for this app. Manage it in Composio to check its setup requirements."); + if (result.status === "not_connected") { + throw unprocessable("Composio did not return a sign-in link for this app. Manage it in Composio to check its setup requirements.", { + code: COMPOSIO_SIGN_IN_LINK_MISSING, + }); + } } } catch (error) { requested("failed"); diff --git a/server/src/services/workspace-provider-failure.ts b/server/src/services/workspace-provider-failure.ts index 5f6531e2efb..4810ef2479c 100644 --- a/server/src/services/workspace-provider-failure.ts +++ b/server/src/services/workspace-provider-failure.ts @@ -35,6 +35,8 @@ const REASONS: Record([ WORKSPACE_STORAGE_PENDING_CODE, WORKSPACE_STORAGE_INCOMPLETE_CODE, + WORKSPACE_RUNTIME_UPDATING_CODE, ]); const RETRYABLE_PROVIDER_REASON_TO_SETUP_CODE: Partial> = { storage_pending: WORKSPACE_STORAGE_PENDING_CODE, remote_incomplete: WORKSPACE_STORAGE_INCOMPLETE_CODE, + runtime_updating: WORKSPACE_RUNTIME_UPDATING_CODE, }; /** Classify a retryable pre-dispatch workspace provider reason to its transient setup code. */ diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index bd5d6641b07..52b16ea8e4b 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -30,7 +30,7 @@ "packages/plugins/sdk/src/ui/runtime.ts": "998428e9701eba3b762d3417236d32c2d0d5763d", "packages/plugins/sdk/src/ui/types.ts": "5a5644acf6554d2e5e1d000bfd03b97d57001eb2", "packages/plugins/sdk/src/worker-rpc-host.ts": "1fe5ce2c81362af765db249a4c804dfd04688683", - "packages/plugins/sdk/src/workspace-operation-error.ts": "2cd247d002d83b163239229e631bca4e519e5075", + "packages/plugins/sdk/src/workspace-operation-error.ts": "6bee7252ff52d755e0207c72219c1964bbc63796", "packages/plugins/sdk/src/workspace-provider.ts": "38e945b807f22150710c11b136af0a28aab2cb7c", "packages/plugins/sdk/tsconfig.json": "d62ebdff94bc4b75dabf1fcad187e1e7a90fc794", "packages/shared/package.json": "0d417d9a3db4fd099b1fe2e0c0a3fa52eee243cf", @@ -221,7 +221,7 @@ "packages/shared/src/cloud-inference.ts": "e91bb2e8d732a9935bbfc36a693de4b910184937", "packages/shared/src/company-import-transfer.test.ts": "213169db79a3f4b6788f4107d6a7b49cd0beb6b9", "packages/shared/src/company-import-transfer.ts": "376482a8c28feba53b1e4973db0ba2e158b65b41", - "packages/shared/src/composio-app-setup.ts": "75f544f5647f227214b8a9d0f61d0196bcbbab55", + "packages/shared/src/composio-app-setup.ts": "dfefc5aded0e4a437d929c355e6ce968f4d10004", "packages/shared/src/composio-search-catalog.json": "483d391b1dbd68f46848dffa83f2e735375835c1", "packages/shared/src/config-schema.test.ts": "5810f2c152e612326bc377aa47f23f623b206ec8", "packages/shared/src/config-schema.ts": "f9c8d41cb09fbc51c3e7a038089b54376cc9150c", @@ -290,7 +290,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "6cb45924ebf5671b63ad4c5011b6b6a6929597c4", + "packages/shared/src/index.ts": "12c7f22a6b31768d27ebe225f5f1ff4f2b89ec91", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -454,7 +454,7 @@ "packages/shared/src/types/feedback.ts": "c5eb31545c7f67c04ad9afd9db45a6b4774bcb35", "packages/shared/src/types/finance.ts": "5c2208c7950020f1005aa0dd86a1680c54dd4354", "packages/shared/src/types/folder.ts": "451856a6720f91525b846d91ec25f7eff110dba5", - "packages/shared/src/types/github-app-setup.ts": "15789f107e578910ca5459364c937e13809a7b0b", + "packages/shared/src/types/github-app-setup.ts": "d36e0b87233d662998c49d2a2d0709bb59bd97e8", "packages/shared/src/types/goal.ts": "29100192bcc3e0c4c4904e59b5d84874952e67a2", "packages/shared/src/types/heartbeat.ts": "68fed072e37ad155b22e3ddf03b6af60411aba24", "packages/shared/src/types/inbox-agent-policy.ts": "cb9d41d9681e80b834889268ad96015a39df92f6", diff --git a/ui/src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx b/ui/src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx index 2a210747810..f26886054ca 100644 --- a/ui/src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx +++ b/ui/src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx @@ -361,12 +361,15 @@ describe("Needs You keeps its toolbar between visits", () => { await vi.waitFor(() => expect(assignee().value).toBe("me")); await choose("Filter decisions by assignee", "Dotta"); await vi.waitFor(() => expect(cards()).toEqual(["dottas"])); + const folderDescription = () => container.querySelector("[data-inbox-folders] p")?.textContent ?? null; + expect(folderDescription()).toBeNull(); await choose("Filter decisions by agent", "Chief of Staff"); await choose("Filter decisions by project", "Website"); const waitingTab = [...container.querySelectorAll('[aria-label="Inbox views"] button')].find((button) => button.textContent?.startsWith("Waiting"))!; await act(async () => waitingTab.click()); await flush(); await vi.waitFor(() => expect(cards()).toEqual(["waiting-1"])); + expect(folderDescription()).toContain("snoozed"); const needsTab = [...container.querySelectorAll('[aria-label="Inbox views"] button')].find((button) => button.textContent === "Needs you")!; await act(async () => needsTab.click()); await flush(); diff --git a/ui/src/components/coordinator/CoordinatorNeedsYou.tsx b/ui/src/components/coordinator/CoordinatorNeedsYou.tsx index d95ea82fabf..3264fa2249c 100644 --- a/ui/src/components/coordinator/CoordinatorNeedsYou.tsx +++ b/ui/src/components/coordinator/CoordinatorNeedsYou.tsx @@ -50,11 +50,11 @@ import { CoordinatorNeedsYouSidePanel, needsYouReviewTab, needsYouReviewTabId, n import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; import { cn } from "@/lib/utils"; -const inboxFolders = [ - { value: "needs", label: "Needs you", description: "Review open requests and decide what happens next." }, +const inboxFolders: ReadonlyArray<{ value: "needs" | "waiting" | "history"; label: string; description?: string }> = [ + { value: "needs", label: "Needs you" }, { value: "waiting", label: "Waiting", description: "See what you’ve snoozed and which tasks are waiting for an automatic retry." }, { value: "history", label: "History", description: "Look back at past decisions and see what happened to failed runs." }, -] as const; +]; /** Rule 7: a card that cannot answer inline links to the exact control, named by its verb. */ function openLabel(item: AttentionItem) { @@ -437,7 +437,7 @@ export function CoordinatorNeedsYou() { return ; })} - {activeFolder &&

{activeFolder.description}

} + {activeFolder?.description &&

{activeFolder.description}

} ; const receipts = feed.data?.receipts ?? []; if (historyOpen) return
diff --git a/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx b/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx index 7a30b0a4ba7..20a4c3dc8d4 100644 --- a/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx +++ b/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx @@ -9,7 +9,7 @@ import { queryKeys } from "@/lib/queryKeys"; import { ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS, nativeTaskModelCatalogOptions } from "@/lib/native-model-catalog"; import { cn } from "@/lib/utils"; import { useMobileEntityPickerViewportStyle } from "@/hooks/useMobileEntityPickerViewportStyle"; -import { getLastComposerEffort, rememberComposerEffort } from "@/lib/recent-composer-effort"; +import { confirmTaskEffortModel, getLastComposerEffort, readRecentTaskRunSettings, rememberComposerEffort, rememberTaskRunSettings } from "@/lib/recent-composer-effort"; import { getCompanyRecentAssigneeSelectionIds, trackRecentAssigneeSelection } from "@/lib/recent-assignees"; import { orderItemsBySelectedAndRecent } from "@/lib/recent-selections"; import type { InlineEntityOption } from "@/components/InlineEntitySelector"; @@ -30,6 +30,7 @@ interface Props { agents: ReadonlyMap; overrides?: IssueAssigneeAdapterOverrides | null; settings: ComposerRunSettings | null; + rememberTaskSettings?: boolean; onSettingsChange: (settings: ComposerRunSettings | null) => void; onAssigneeChange: (value: string) => void; /** Conversations keep their agent identity; only model/effort is editable here. */ @@ -93,7 +94,7 @@ function AnimatedBody({ children }: { children: ReactNode }) { export function ComposerRunSettingsPicker({ companyId, assigneeValue, currentAssigneeValue, options, agents, overrides, - settings, onSettingsChange, onAssigneeChange, allowAssigneeChange = true, disabled = false, mobile: mobileProp, triggerRef, modelOptionsOverride, renderAssigneeIdentity, + settings, rememberTaskSettings = false, onSettingsChange, onAssigneeChange, allowAssigneeChange = true, disabled = false, mobile: mobileProp, triggerRef, modelOptionsOverride, renderAssigneeIdentity, initialOpen = false, initialView = "settings", initialModelSearch = "", initialAssigneeSearch = "", }: Props) { const [open, setOpen] = useState(initialOpen); @@ -128,6 +129,14 @@ export function ComposerRunSettingsPicker({ const poolId = binding?.mode === "router" ? binding.connectionId : undefined; const nativeCatalog = nativeTaskModelCatalogOptions(agent); const acpxAgent = agent?.adapterType === "paperclip_runner" && provider === "acpx" && typeof agent.adapterConfig.acpxAgent === "string" ? agent.adapterConfig.acpxAgent : undefined; + const preferenceScope = rememberTaskSettings && agent && modelSupported + ? JSON.stringify([companyId, agentId, agent.adapterType, provider, acpxAgent, poolId]) + : null; + const hasTaskOverrides = Boolean(rememberTaskSettings && overrides); + const remembered = useMemo( + () => preferenceScope && !hasTaskOverrides ? readRecentTaskRunSettings(preferenceScope) : undefined, + [preferenceScope, hasTaskOverrides, settings], + ); const nativeCatalogScope = JSON.stringify(nativeCatalog ?? null); const requestNativeModels = Boolean(nativeCatalog && open && view !== "agents" && !modelOptionsOverride); const { data: fetchedModels = [], isPending: modelsPending, refetch: refreshModels } = useQuery({ @@ -151,24 +160,43 @@ export function ComposerRunSettingsPicker({ const base = assigneeValue === currentAssigneeValue ? readComposerRunSettings(overrides, agent?.adapterType) : DEFAULT_COMPOSER_RUN_SETTINGS; - const selected = settings ?? base; + const rememberedModel = remembered?.model ?? null; + const selected = settings ?? { ...base, model: rememberedModel ?? base.model }; const configuredModel = composerDefaultModel(agent); const model = selected.model ?? configuredModel; const modelName = models.find((item) => item.id === model)?.label ?? model ?? ""; - const choices = composerEfforts(agent, model, models.map((item) => item.id)); + const catalogIds = models.map((item) => item.id); + const effortValidatedForModel = remembered?.effort && remembered.effortModel === model; + const knownEffortModels = effortValidatedForModel + ? [...catalogIds, model] + : catalogIds; + const choices = composerEfforts(agent, model, knownEffortModels); const effort = selected.effort && choices.includes(selected.effort) ? selected.effort : null; const effortIndex = effort ? choices.indexOf(effort) + 1 : 0; const effortLabel = effort ? EFFORT_LABELS[effort] ?? effort : "Default"; const fastAvailable = composerFastAvailable(agent, model); - const effortChoicesKey = choices.join(","); + const preferredEffort = hasTaskOverrides ? undefined : remembered ? remembered.effort : getLastComposerEffort(companyId); + const restoredEffort = preferredEffort && choices.includes(preferredEffort) ? preferredEffort : null; + // A delayed result may fill in effort for the draft settings we supplied. + // Replacing those settings with a user edit or recovered draft cancels it. + const pendingEffort = useRef<{ scope: string; settings: ComposerRunSettings } | null>(null); useEffect(() => { - // Explicit drafts and task overrides take precedence over remembered effort. - if (settings !== null || base.effort || !modelSupported) return; - const remembered = getLastComposerEffort(companyId); - if (remembered && effortChoicesKey.split(",").includes(remembered)) { - onSettingsChange({ ...base, effort: remembered }); + if (!modelSupported || hasTaskOverrides) return; + if (settings) { + const pending = pendingEffort.current; + if (!restoredEffort || pending?.settings !== settings || pending.scope !== preferenceScope) return; + } else if (base.effort || (!rememberedModel && !restoredEffort)) { + return; } - }, [companyId, agentId, model, modelSupported, settings, base.model, base.effort, base.fast, effortChoicesKey, onSettingsChange]); + if (preferenceScope && remembered && restoredEffort) { + confirmTaskEffortModel(preferenceScope, remembered, model); + } + const next = { model: selected.model, effort: restoredEffort, fast: selected.fast }; + pendingEffort.current = preferenceScope && catalogPending && preferredEffort && !restoredEffort + ? { scope: preferenceScope, settings: next } + : null; + onSettingsChange(next); + }, [settings, modelSupported, hasTaskOverrides, base.effort, rememberedModel, restoredEffort, catalogPending, preferredEffort, preferenceScope, remembered, model, selected.model, selected.fast, onSettingsChange]); const changed = Boolean(selected.model || selected.effort || selected.fast); const assigneeOptions = useMemo(() => { if (!open || view !== "agents") return []; @@ -222,16 +250,28 @@ export function ComposerRunSettingsPicker({ setView("settings"); setAssigneeSearch(""); }; + const saveSelection = (next: ComposerRunSettings, effortModel: string, effortPreference = next.effort) => { + if (preferenceScope) rememberTaskRunSettings(preferenceScope, next.model, effortPreference, effortModel); + onSettingsChange(next); + }; const chooseModel = (value: string | null) => { - const nextChoices = composerEfforts(agent, value ?? configuredModel, models.map((item) => item.id)); - const preferred = selected.effort ?? getLastComposerEffort(companyId); - onSettingsChange({ model: value, effort: preferred && nextChoices.includes(preferred) ? preferred : null, fast: false }); + const effortModel = value ?? configuredModel; + const nextChoices = composerEfforts(agent, effortModel, knownEffortModels); + const preferred = selected.effort ?? preferredEffort; + const next = { model: value, effort: preferred && nextChoices.includes(preferred) ? preferred : null, fast: false }; + if (preferenceScope && catalogPending && preferred && !nextChoices.length) { + const validatedEffortModel = choices.includes(preferred) ? model : remembered?.effortModel ?? ""; + pendingEffort.current = { scope: preferenceScope, settings: next }; + saveSelection(next, validatedEffortModel, preferred); + } else { + saveSelection(next, effortModel); + } setView("settings"); setModelSearch(""); }; const reset = () => { rememberComposerEffort(companyId, null); - onSettingsChange(DEFAULT_COMPOSER_RUN_SETTINGS); + saveSelection(DEFAULT_COMPOSER_RUN_SETTINGS, configuredModel); }; const closeButton = mobile ? : null; const Trigger = mobile ? DialogTrigger : PopoverTrigger; @@ -280,7 +320,7 @@ export function ComposerRunSettingsPicker({ onChange={(event) => { const nextEffort = Number(event.target.value) === 0 ? null : choices[Number(event.target.value) - 1]!; rememberComposerEffort(companyId, nextEffort); - onSettingsChange({ ...selected, effort: nextEffort }); + saveSelection({ ...selected, effort: nextEffort }, model); }} className="composer-run-effort-range mt-3 w-full" style={{ "--fill": `${effortIndex / choices.length * 100}%` } as CSSProperties} /> : null} diff --git a/ui/src/components/task-chat/TaskChatComposer.test.tsx b/ui/src/components/task-chat/TaskChatComposer.test.tsx index 651c54f6d3f..3b79a3ff507 100644 --- a/ui/src/components/task-chat/TaskChatComposer.test.tsx +++ b/ui/src/components/task-chat/TaskChatComposer.test.tsx @@ -14,7 +14,7 @@ import { parseSwarmCommand, planSubmission, swarmRunSettingsRefusal } from "./co import { ComposerAddMenu } from "./ComposerAddMenu"; import { QuestionForm } from "./QuestionForm"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import type { Agent, HeartbeatRun, IssueWorkMode } from "@paperclipai/shared"; +import type { Agent, HeartbeatRun, IssueAssigneeAdapterOverrides, IssueWorkMode } from "@paperclipai/shared"; import { agentsApi } from "@/api/agents"; import { instanceSettingsApi } from "@/api/instanceSettings"; import { CoordinatorPresentation } from "@/components/coordinator/CoordinatorPresentation"; @@ -32,6 +32,8 @@ import { ApiError } from "../../api/api-error"; import { queryKeys } from "../../lib/queryKeys"; import { useAccountBoundMutation } from "../../hooks/useAccountBoundMutation"; import { waitForStoppedRuns } from "../../lib/wait-for-stopped-runs"; +import { getLastComposerEffort } from "../../lib/recent-composer-effort"; +import type { ComposerRunSettings } from "./composer-run-settings"; // The session lookup never answers on its own; tests set the account directly. vi.mock("../../api/auth", async (importOriginal) => { @@ -2916,6 +2918,159 @@ describe("TaskChatComposer", () => { } }); + it("restores the last model and effort in a fresh task composer for the same agent", async () => { + vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} }); + const availableModels = [ + { id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6" }, + { id: "claude-sonnet-4-5", label: "Claude Sonnet 4.5" }, + ]; + const catalog = vi.spyOn(agentsApi, "adapterModels").mockResolvedValue(availableModels); + let client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const agent = { id: "task-agent", name: "Mira", adapterType: "claude_local", adapterConfig: { model: "claude-sonnet-4-5" } } as unknown as Agent; + const otherAgent = { ...agent, id: "other-agent", name: "Tess" }; + const onSubmit = vi.fn().mockResolvedValue(undefined); + const onAdd = vi.fn().mockResolvedValue(undefined); + function Draft({ assignee = agent, initialSettings = null, overrides }: { + assignee?: Agent; + initialSettings?: ComposerRunSettings | null; + overrides?: IssueAssigneeAdapterOverrides; + }) { + const [settings, setSettings] = useState(initialSettings); + const value = `agent:${assignee.id}`; + return ; + } + const paint = (key: string, props?: ComponentProps) => + render(); + const paintConversation = () => + render( + + ); + const click = async (selector: string) => + act(async () => document.querySelector(selector)!.click()); + const chooseModel = async (label: string) => { + await click('[aria-label="Select model and effort"]'); + await click('[aria-label="Choose exact model"]'); + const option = [...document.querySelectorAll('button[role="option"]')] + .find((item) => item.textContent?.startsWith(label))!; + await act(async () => option.click()); + }; + const resetCatalog = () => { + render(<>); + client.clear(); + client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + }; + const waitForEffort = () => vi.waitFor(async () => { + await flushAsync(); + expect(container.querySelector('[aria-label="Select model and effort"]')?.textContent).toContain("High"); + }); + try { + paint("first"); + await flushAsync(); + await chooseModel("Claude Sonnet 4.6"); + const range = document.querySelector('input[aria-label="Effort"]')!; + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(range, "3"); + range.dispatchEvent(new Event("change", { bubbles: true })); + range.dispatchEvent(new Event("input", { bubbles: true })); + }); + + expect(getLastComposerEffort("task-company")).toBe("high"); + resetCatalog(); + paintConversation(); + await waitForEffort(); + expect(container.querySelector('[data-testid="task-chat-composer-model-label"]')?.textContent).toBe("Claude Sonnet 4.5"); + typeText("Continue the conversation"); + await act(async () => sendButton().click()); + expect(onAdd).toHaveBeenLastCalledWith("Continue the conversation", undefined, undefined, undefined, + expect.any(String), { model: null, effort: "high", fast: false }); + + paint("other", { assignee: otherAgent }); + await waitForEffort(); + expect(container.querySelector('[data-testid="task-chat-composer-model-label"]')?.textContent).toBe("Claude Sonnet 4.5"); + await act(async () => sendButton().click()); + expect(onSubmit).toHaveBeenLastCalledWith("Start a task", "standard", { model: null, effort: "high", fast: false }); + + resetCatalog(); + let finishDiscovery!: (models: typeof availableModels) => void; + catalog.mockImplementation(() => new Promise((resolve) => { finishDiscovery = resolve; })); + paint("second"); + expect(container.querySelector('[data-testid="task-chat-composer-model-label"]')?.textContent).toBe("claude-sonnet-4-6"); + await act(async () => sendButton().click()); + expect(onSubmit).toHaveBeenLastCalledWith("Start a task", "standard", { model: "claude-sonnet-4-6", effort: "high", fast: false }); + + paint("inherited", { overrides: { adapterConfig: { model: "claude-sonnet-4-5" } } }); + expect(container.querySelector('[data-testid="task-chat-composer-model-label"]')?.textContent).toBe("claude-sonnet-4-5"); + await act(async () => sendButton().click()); + expect(onSubmit).toHaveBeenLastCalledWith("Start a task", "standard", null); + + const explicit = { model: "claude-sonnet-4-5", effort: "low", fast: false }; + paint("recovered", { initialSettings: explicit }); + await act(async () => sendButton().click()); + expect(onSubmit).toHaveBeenLastCalledWith("Start a task", "standard", explicit); + + paint("pending-model-choice"); + await chooseModel("Use agent default"); + expect(document.querySelector('[data-testid="selected-effort"]')).toBeNull(); + await act(async () => finishDiscovery(availableModels)); + await vi.waitFor(async () => { + await flushAsync(); + expect(document.querySelector('[data-testid="selected-effort"]')?.textContent).toBe("High"); + }); + + resetCatalog(); + catalog.mockImplementation(() => new Promise(() => {})); + paint("reload-before-discovery"); + await act(async () => sendButton().click()); + expect(onSubmit).toHaveBeenLastCalledWith("Start a task", "standard", { model: null, effort: "high", fast: false }); + + resetCatalog(); + catalog.mockResolvedValue(availableModels); + paint("after-pending-model-choice"); + await waitForEffort(); + await act(async () => sendButton().click()); + expect(onSubmit).toHaveBeenLastCalledWith("Start a task", "standard", { model: null, effort: "high", fast: false }); + + await chooseModel("Claude Sonnet 4.6"); + + resetCatalog(); + catalog.mockResolvedValue(availableModels.slice(1)); + paint("limited-catalog"); + await flushAsync(); + expect(container.querySelector('[data-testid="task-chat-composer-model-label"]')?.textContent).toBe("claude-sonnet-4-6"); + await act(async () => sendButton().click()); + expect(onSubmit).toHaveBeenLastCalledWith("Start a task", "standard", { model: "claude-sonnet-4-6", effort: "high", fast: false }); + + paint("reset"); + await click('[aria-label="Select model and effort"]'); + await click('[aria-label="Reset to agent default"]'); + expect(getLastComposerEffort("task-company")).toBeNull(); + paint("after-reset"); + await act(async () => sendButton().click()); + expect(onSubmit).toHaveBeenLastCalledWith("Start a task", "standard", null); + + catalog.mockResolvedValue(availableModels); + paintConversation(); + await flushAsync(); + typeText("Continue with defaults"); + await act(async () => sendButton().click()); + expect(onAdd.mock.calls.at(-1)?.slice(5)).toEqual([]); + } finally { + render(<>); + client.clear(); + catalog.mockRestore(); + vi.unstubAllGlobals(); + } + }); + describe("paused task takeover", () => { it("allows only standalone /new to resume a paused conversation through the normal composer", async () => { const onAdd = vi.fn().mockResolvedValue(undefined); diff --git a/ui/src/components/task-chat/TaskChatComposer.tsx b/ui/src/components/task-chat/TaskChatComposer.tsx index 58d1bbdc433..9177b9a6626 100644 --- a/ui/src/components/task-chat/TaskChatComposer.tsx +++ b/ui/src/components/task-chat/TaskChatComposer.tsx @@ -1641,6 +1641,7 @@ export function TaskChatComposer({ agents={modelAgents} overrides={assigneeAdapterOverrides} settings={runSettings} + rememberTaskSettings={Boolean(creation)} onSettingsChange={setRunSettings} onAssigneeChange={updatePendingAssignee} allowAssigneeChange={showAssignee && !conversationMode} diff --git a/ui/src/lib/recent-composer-effort.ts b/ui/src/lib/recent-composer-effort.ts index ce45aeb58d6..8d45c05cc61 100644 --- a/ui/src/lib/recent-composer-effort.ts +++ b/ui/src/lib/recent-composer-effort.ts @@ -1,21 +1,51 @@ const STORAGE_KEY = "paperclip:composer-effort"; -/** Undefined means no preference; null is the user's explicit Default choice. */ -export function getLastComposerEffort(companyId: string): string | null | undefined { +type RememberedTaskRunSettings = { model: string | null; effort: string | null; effortModel: string }; + +function readPreference(key: string): unknown { try { - const raw = localStorage.getItem(`${STORAGE_KEY}:${companyId}`); - if (raw === null) return undefined; - const value: unknown = JSON.parse(raw); - return value === null || typeof value === "string" ? value : undefined; + const raw = localStorage.getItem(key); + return raw === null ? undefined : JSON.parse(raw); } catch { return undefined; } } -export function rememberComposerEffort(companyId: string, effort: string | null): void { +function writePreference(key: string, value: RememberedTaskRunSettings | string | null): void { try { - localStorage.setItem(`${STORAGE_KEY}:${companyId}`, JSON.stringify(effort)); + localStorage.setItem(key, JSON.stringify(value)); } catch { // The current run setting still works without persistent storage. } } + +/** Undefined means no preference; null is the user's explicit Default choice. */ +export function getLastComposerEffort(companyId: string): string | null | undefined { + const value = readPreference(`${STORAGE_KEY}:${companyId}`); + return value === null || typeof value === "string" ? value : undefined; +} + +export function rememberComposerEffort(companyId: string, effort: string | null): void { + writePreference(`${STORAGE_KEY}:${companyId}`, effort); +} + +export function readRecentTaskRunSettings(scope: string): RememberedTaskRunSettings | undefined { + const value = readPreference(`paperclip:task-run-settings:${scope}`) as Partial | null; + if (value && (value.model === null || typeof value.model === "string") + && (value.effort === null || typeof value.effort === "string") && typeof value.effortModel === "string") { + return { model: value.model, effort: value.effort, effortModel: value.effortModel }; + } +} + +export function rememberTaskRunSettings(scope: string, model: string | null, effort: string | null, effortModel: string): void { + writePreference(`paperclip:task-run-settings:${scope}`, { model, effort, effortModel }); +} + +export function confirmTaskEffortModel(scope: string, remembered: RememberedTaskRunSettings, effortModel: string): void { + if (remembered.effortModel === effortModel) return; + const current = readRecentTaskRunSettings(scope); + // Discovery can finish after another composer has saved a newer choice. + if (current?.model === remembered.model && current.effort === remembered.effort && current.effortModel === remembered.effortModel) { + rememberTaskRunSettings(scope, current.model, current.effort, effortModel); + } +} diff --git a/ui/src/lib/recent-selections.test.ts b/ui/src/lib/recent-selections.test.ts index 5e9ddd6c4fa..d614ed3604c 100644 --- a/ui/src/lib/recent-selections.test.ts +++ b/ui/src/lib/recent-selections.test.ts @@ -7,7 +7,7 @@ import { trackRecentAssigneeUser, } from "./recent-assignees"; import { getLastProjectId, getRecentProjectIds, trackRecentProject } from "./recent-projects"; -import { getLastComposerEffort, rememberComposerEffort } from "./recent-composer-effort"; +import { confirmTaskEffortModel, getLastComposerEffort, readRecentTaskRunSettings, rememberComposerEffort, rememberTaskRunSettings } from "./recent-composer-effort"; import { orderItemsBySelectedAndRecent } from "./recent-selections"; describe("recent selection ordering", () => { @@ -92,6 +92,32 @@ describe("recent selection ordering", () => { expect(getLastComposerEffort("company-1")).toBeUndefined(); }); + it("reads scoped model and effort choices and ignores incomplete or corrupt records", () => { + const scope = "company-1:agent-1"; + const key = `paperclip:task-run-settings:${scope}`; + rememberTaskRunSettings(scope, "model-a", "high", "model-a"); + expect(readRecentTaskRunSettings(scope)).toEqual({ model: "model-a", effort: "high", effortModel: "model-a" }); + expect(readRecentTaskRunSettings("company-1:agent-2")).toBeUndefined(); + rememberTaskRunSettings(scope, null, null, "model-a"); + expect(readRecentTaskRunSettings(scope)).toEqual({ model: null, effort: null, effortModel: "model-a" }); + localStorage.setItem(key, '{"model":"model-a","effort":"high"}'); + expect(readRecentTaskRunSettings(scope)).toBeUndefined(); + localStorage.setItem(key, "broken json"); + expect(readRecentTaskRunSettings(scope)).toBeUndefined(); + }); + + it("records late effort validation without replacing a newer choice", () => { + const scope = "company-1:agent-1"; + rememberTaskRunSettings(scope, "new-model", "high", "previous-model"); + const pending = readRecentTaskRunSettings(scope)!; + confirmTaskEffortModel(scope, pending, "new-model"); + expect(readRecentTaskRunSettings(scope)).toEqual({ model: "new-model", effort: "high", effortModel: "new-model" }); + + rememberTaskRunSettings(scope, "new-model", null, "new-model"); + confirmTaskEffortModel(scope, pending, "new-model"); + expect(readRecentTaskRunSettings(scope)?.effort).toBeNull(); + }); + it("tracks recent user and agent assignee selections with prefixed ids", () => { trackRecentAssignee("agent-1"); trackRecentAssigneeUser("user-1"); diff --git a/ui/src/pages/apps/ComposioAppSetup.test.tsx b/ui/src/pages/apps/ComposioAppSetup.test.tsx new file mode 100644 index 00000000000..bdf3f13b62c --- /dev/null +++ b/ui/src/pages/apps/ComposioAppSetup.test.tsx @@ -0,0 +1,105 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { COMPOSIO_SIGN_IN_LINK_MISSING, type ToolConnection } from "@paperclipai/shared"; +import { describe, expect, it, vi } from "vitest"; +import { ComposioAppSetup } from "./ComposioAppSetup"; + +const { setup } = vi.hoisted(() => ({ setup: vi.fn() })); +vi.mock("@/api/tools", () => ({ toolsApi: { setupComposioApp: setup } })); +vi.mock("@/api/companies-query", () => ({ useAccountIdentity: () => ({ userId: "user", settled: true }) })); +vi.mock("@/context/ToastContext", () => ({ useToast: () => ({ pushToast: vi.fn() }) })); +vi.mock("@/lib/router", () => ({ + Link: ({ to, children }: { to: string; children: React.ReactNode }) => {children}, +})); + +async function clickButton(container: HTMLElement, label: string) { + const button = [...container.querySelectorAll("button")].find(button => button.textContent === label); + if (!button) throw new Error(`Could not find the "${label}" button`); + await act(async () => button.click()); +} + +async function submit(toolkit: string, inspect: (container: HTMLElement) => void | Promise) { + const container = document.createElement("div"); + const root = createRoot(container); + const queries = new QueryClient(); + try { + await act(async () => root.render( + + + , + )); + await clickButton(container, "Continue"); + expect(setup).toHaveBeenLastCalledWith("saved", toolkit, { action: "start" }); + await inspect(container); + } finally { + act(() => root.unmount()); + queries.clear(); + } +} + +describe("Composio app setup recovery", () => { + const missingLink = { + status: 422, + body: { error: "Composio did not return a sign-in link for this app.", details: { code: COMPOSIO_SIGN_IN_LINK_MISSING } }, + }; + + it("opens the existing MCP setup with Buffer's official endpoint when Composio has no link", async () => { + setup.mockRejectedValueOnce(missingLink); + await submit("buffer", container => { + expect(container.querySelector('[role="alert"]')?.textContent).toContain("custom OAuth app"); + const link = new URL(container.querySelector("a")!.href); + expect(link.pathname).toBe("/apps/byo"); + expect(link.searchParams.get("name")).toBe("Buffer"); + expect(link.searchParams.get("link")).toBe("https://mcp.buffer.com/mcp"); + }); + }); + + it("keeps a valid Buffer sign-in link in the Composio flow", async () => { + const authorizationUrl = "https://connect.composio.dev/link/buffer-example"; + setup.mockResolvedValueOnce({ status: "authorization_required", authorizationUrl }); + await submit("buffer", container => { + expect(container.querySelector('[role="alert"]')).toBeNull(); + expect(container.querySelector("a")?.href).toBe(authorizationUrl); + }); + }); + + it("removes the previous sign-in link when Composio cannot issue a replacement", async () => { + const authorizationUrl = "https://connect.composio.dev/link/old-buffer"; + setup.mockResolvedValueOnce({ status: "authorization_required", authorizationUrl }) + .mockRejectedValueOnce(missingLink); + await submit("buffer", async container => { + expect(container.querySelector("a")?.href).toBe(authorizationUrl); + await clickButton(container, "Get a new link"); + expect(setup).toHaveBeenLastCalledWith("saved", "buffer", { action: "start" }); + expect(container.querySelector('[role="status"]')).toBeNull(); + expect([...container.querySelectorAll("a")].map(link => link.textContent)) + .toEqual(["Connect directly to Buffer"]); + expect([...container.querySelectorAll("button")].map(button => button.textContent)).toContain("Continue"); + }); + }); + + it("keeps the current sign-in link when the completion check fails", async () => { + const authorizationUrl = "https://connect.composio.dev/link/buffer-example"; + setup.mockResolvedValueOnce({ status: "authorization_required", authorizationUrl }) + .mockRejectedValueOnce({ + status: 409, + body: { error: "Finish connecting this app in Composio, then check again" }, + }); + await submit("buffer", async container => { + await clickButton(container, "I’ve connected it"); + expect(setup).toHaveBeenLastCalledWith("saved", "buffer", { action: "complete" }); + expect(container.querySelector('[role="alert"]')).not.toBeNull(); + expect(container.querySelector("a")?.href).toBe(authorizationUrl); + }); + }); + + it("links to Composio management for other apps when there is no sign-in link", async () => { + setup.mockRejectedValueOnce(missingLink); + await submit("gmail", container => { + expect(container.querySelector("a")?.href).toBe("https://dashboard.composio.dev/~/org/connect/apps"); + }); + }); +}); diff --git a/ui/src/pages/apps/ComposioAppSetup.tsx b/ui/src/pages/apps/ComposioAppSetup.tsx index d9ea4d7b50e..5ea8c8b28f8 100644 --- a/ui/src/pages/apps/ComposioAppSetup.tsx +++ b/ui/src/pages/apps/ComposioAppSetup.tsx @@ -1,14 +1,16 @@ import { useState } from "react"; import { useQueryClient } from "@tanstack/react-query"; import { ExternalLink } from "lucide-react"; -import type { ComposioAppSetupInput, ComposioAppSetupResult, ToolConnection } from "@paperclipai/shared"; +import { COMPOSIO_SIGN_IN_LINK_MISSING, type ComposioAppSetupInput, type ComposioAppSetupResult, type ToolConnection } from "@paperclipai/shared"; import { toolsApi } from "@/api/tools"; import { useAccountIdentity } from "@/api/companies-query"; import { queryKeys } from "@/lib/queryKeys"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { useToast } from "@/context/ToastContext"; -import { describeError } from "@/api/errors"; +import { describeError, errorCodes } from "@/api/errors"; +import { COMPOSIO_APP_MANAGEMENT_URL } from "@/lib/aggregator-app-setup"; +import { Link } from "@/lib/router"; import { cn } from "@/lib/utils"; import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; @@ -24,14 +26,16 @@ export function ComposioAppSetup({ name, toolkit, connections, onClose, onBack, const connectionId = selectedConnectionId ?? connections[0]?.id ?? "__new__"; const [result, setResult] = useState(null); const [busy, setBusy] = useState(false); - const [error, setError] = useState(null); + const [error, setError] = useState<{ message: string; missingSignInLink: boolean } | null>(null); const connection = connections.find(candidate => candidate.id === connectionId); + const offerDirectBuffer = error?.missingSignInLink && toolkit === "buffer"; async function submit(input: ComposioAppSetupInput) { if (busy || !connection || !settled) return; setConnectionId(connection.id); setBusy(true); setError(null); + if (input.action === "start") setResult(null); try { const next = await toolsApi.setupComposioApp(connection.id, toolkit, input); setResult(next); @@ -42,7 +46,7 @@ export function ComposioAppSetup({ name, toolkit, connections, onClose, onBack, onClose(); } } catch (cause) { - setError(describeError(cause).body); + setError({ message: describeError(cause).body, missingSignInLink: errorCodes(cause).includes(COMPOSIO_SIGN_IN_LINK_MISSING) }); } finally { setBusy(false); } } @@ -56,7 +60,16 @@ export function ComposioAppSetup({ name, toolkit, connections, onClose, onBack, - {error ?

{error}

: null} + {error ?
+

{offerDirectBuffer + ? "Buffer requires a custom OAuth app in Composio. To connect directly, create a key in Buffer Settings → API, then choose Key or token in Paperclip." + : error.message}

+ {offerDirectBuffer ? : error.missingSignInLink ? : null} +
: null} {result ?

Finish connecting {name} in Composio, then return here.

: null} {result?.authorizationUrl ?