mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
d9ce549dd22bf484599ba2d84871efad5bd8fac3
1083
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
eb35831f05 |
Add first-class SpreadJam and Okara remote MCP connectors (#23859)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Apps catalog ships first-class connectors for external services so teams can connect tools with verified endpoints, brand icons, permission reviews, and guided sign-in > - SpreadJam and Okara both publish official hosted remote MCP servers with OAuth discovery and dynamic client registration, so users currently fall back to unverified custom MCP entries without brand assets, scope defaults, or reviewed risk policies > - Adding catalog definitions with conservative risk classification, drift quarantine, and Ask-first defaults lets users discover both apps in the gallery and connect safely without unreviewed write/destructive actions auto-enabling > - This pull request adds first-class remote MCP connectors for SpreadJam (`https://api.spreadjam.com/mcp`) and Okara (`https://okara.ai/api/mcp`) with official brand SVGs, reviewed permission entries, reviewed tool risk + drift policies, Ask-first defaults for write/destructive actions, unit + fresh-OAuth server tests, and refreshed SDK public inputs > - The benefit is a guided connection flow with official branding, safer default OAuth scopes for Okara, optional project pinning and API-key support for SpreadJam, Ask-first approval on write/destructive tools, drift quarantine on catalog refresh, and automatic BYO URL recognition ## Linked Issues or Issue Description **Subsystem affected** Cross-cutting (packages/shared, server, ui, doc/connections) **Problem or motivation** Users connecting SpreadJam (`https://api.spreadjam.com/mcp`) or Okara (`https://okara.ai/api/mcp`) must configure them as unverified custom MCP servers. They get no official brand icon, no catalog entry, no curated permission review, no Okara default scope restriction (`mcp:read`, `mcp:write`), no SpreadJam `X-Jam-Project` or workspace API key setup guidance, and no reviewed risk classification or drift quarantine. **Proposed solution** Add both SpreadJam and Okara as first-class Track A remote MCP connectors in the Paperclip Apps catalog: - Register `spreadjam` with DCR OAuth (`dcr`) and workspace API key (`customer`, `Authorization: Bearer sk_...`) methods, optional `projectId` header pinning (`X-Jam-Project`), default agent instructions, verified `reviewedTools` (against `https://api.spreadjam.com/openapi.json`) with `quarantineNewEntries: true`, and official SVG branding. - Register `okara` with DCR OAuth (`dcr`) requesting `mcp:read` and `mcp:write` by default (omitting `mcp:publish` and `mcp:spend`), conservative `okaraRisk` classification with `quarantineNewEntries: true` in `connectorToolPolicy`, and official light and dark SVG branding. - Require Ask-first approval by default for `write` and `destructive` actions on fresh SpreadJam and Okara connections via `recommendedDefaultsForApp`, keeping read tools immediately usable. - Register permission reviews, manifest entries, generated catalog output, shared/server tests, and `source-sdk-public-inputs.json`. **Alternatives considered** Leaving both servers as custom BYO MCP connections was considered. Custom connections work after #23846, but they cannot provide curated brand assets, verified gallery placement, Okara's read/draft scope guardrails, reviewed tool risk + Ask-first defaults, or SpreadJam's `X-Jam-Project` pinning and API-key flow. **Roadmap alignment** Extends the existing declarative Track A remote MCP Apps catalog (`packages/shared/src/app-definitions/`) and connector risk policy registry (`server/src/services/connectors/`). Does not duplicate or alter planned core architecture in `ROADMAP.md`. **Additional context** Follows up on #23846, which improved custom remote MCP discovery and recovery. ## What Changed - Added SpreadJam connector override and generated definition (`scripts/app-definition-overrides/spreadjam.json`, `packages/shared/src/app-definitions/spreadjam.json`) for `https://api.spreadjam.com/mcp` with `mcp-oauth` (`dcr`), `mcp-api-key` (`customer`, Bearer `sk_...`), optional `X-Jam-Project` tenant header pinning, `spreadjam-default-v1` agent instructions, and `reviewedTools` (42 verified `GET` reads, 26 verified delete/publish/PR/credit-spending/billing-allocation destructive ops, `unlisted: "write"`, `quarantineNewEntries: true`). - Added Okara connector override and generated definition (`scripts/app-definition-overrides/okara.json`, `packages/shared/src/app-definitions/okara.json`) for `https://okara.ai/api/mcp` with `mcp-oauth` (`dcr`) and default `scopesHint: ["mcp:read", "mcp:write"]` (`Read and draft` capability profile, withholding `mcp:publish` and `mcp:spend`). - Added `server/src/services/connectors/okara/risk.ts` and registered `okara` in `server/src/services/connectors/tool-policy.ts` with `quarantineNewEntries: true` and fail-closed risk classification (only explicit `readOnlyHint: true` without destructive/write hints or verbs classifies as `read`; publish/spend/delete/launch verbs classify as `destructive`; unlisted/unannotated fail closed to `write`). - Updated `recommendedDefaultsForApp` in `packages/shared/src/app-definitions.ts` so new SpreadJam and Okara connections default to `askFirstRiskLevels: ["write", "destructive"]` while leaving read tools immediately usable. - Added verbatim official brand SVGs (`ui/public/brands/apps/spreadjam.svg`, `ui/public/brands/apps/okara.svg`, `ui/public/brands/apps/okara-dark.svg`) and registered both identities in `ui/public/brands/apps/manifest.json` without colliding with `jam-dev`'s existing `"jam"` alias. - Added reviewed method entries for `spreadjam/mcp-oauth`, `spreadjam/mcp-api-key`, and `okara/mcp-oauth` in `doc/connections/tool-method-permission-reviews.json`. - Added `"okara"` and `"spreadjam"` to `CONNECTABLE_APP_SLUGS` in `packages/shared/src/app-definitions.ts` and regenerated `packages/shared/src/app-definitions.generated.ts`. - Added unit and embedded-Postgres integration tests in `packages/shared/src/app-definitions.test.ts` and `server/src/__tests__/connector-tool-policy.test.ts` covering definitions, risk classification, fresh OAuth Ask-first policy creation, and drift quarantine on catalog refresh. - Refreshed `tests/runner-e2e/source-sdk-public-inputs.json` to match the updated shared exports. ## Verification - Brand, asset, and override validation: - `node scripts/check-app-brand-assets.mjs` (pass: 117 brand identities validated) - `node --test scripts/app-definition-overrides.test.mjs scripts/app-brand-validation.test.mjs` (pass: 16/16) - Build, typecheck, and Vitest suites: - `pnpm --filter @paperclipai/shared build && pnpm --filter @paperclipai/shared typecheck` (pass) - `pnpm --filter @paperclipai/server typecheck` (pass) - `pnpm --filter @paperclipai/ui typecheck` (pass) - `pnpm exec vitest run packages/shared/src/app-definitions.test.ts server/src/services/tool-access/oauth/client-settings.test.ts server/src/__tests__/connector-tool-policy.test.ts ui/src/pages/apps/AppsConnect.test.tsx` (pass: 4 files, 97/97 tests) - `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD) --check` (pass: `changed: false`) - Live non-registering preflight against local Paperclip dev server: - `GET /api/companies/:id/tools/apps/spreadjam/preflight` → `endpointReachable: true` (`401 application/json`), `oauth.metadataFound: true`, `oauth.registrationAdvertised: true` - `GET /api/companies/:id/tools/apps/okara/preflight` → `endpointReachable: true` (`401 application/json`), `oauth.metadataFound: true`, `oauth.registrationAdvertised: true`, `oauth.clientIdMetadataDocumentSupported: true` - Local browser verification against isolated dev server: - Verified both tiles render in the Apps gallery with official SVG logos (dark and light theme contrast verified for Okara's light/dark icons). - Verified `/apps/connect?source=spreadjam` shows no unverified badge, default agent instructions, OAuth + API key methods, and optional `Pin to project ID` field. - Verified `/apps/connect?source=okara` shows no unverified badge and clean one-click OAuth flow. - Verified BYO URL recognition (`/apps/byo?link=...`) detects and suggests guided setup for both `https://api.spreadjam.com/mcp` and `https://okara.ai/api/mcp`. ### Production Validation Matrix | Check | SpreadJam | Okara | | --- | --- | --- | | Public docs & live OAuth metadata discovery | Passed | Passed | | Non-registering Paperclip preflight endpoint | Passed | Passed | | Deterministic unit, server OAuth policy, typecheck, and brand asset checks | Passed | Passed | | Local UI gallery, connect flow, light/dark logos, and BYO recognition | Passed | Passed | | Live account-bound OAuth sign-in / tool call execution | Not run (no live user credentials provided) | Not run (no live user credentials provided) | ## Risks - Low risk: additive declarative catalog definitions, static brand SVGs, connector risk policy, tests, and generated metadata only; no database schema, migration, or generic OAuth runtime changes. - Live account-bound OAuth consent, token exchange, and post-connect MCP tool invocation were not executed in this verification pass because no live SpreadJam or Okara account credentials were used. - SpreadJam OAuth and workspace API keys inherit the signed-in user's workspace role; new connections mitigate accidental side effects by starting write and destructive actions on Ask first and quarantining newly added tools on catalog refresh. ## Model Used - Google Antigravity (`gemini-3-pro`, extended thinking, tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
266eccc524 |
fix(connections): improve custom remote MCP OAuth draft setup, auto-detection, and recovery UX (#23846)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - People connect external tools to agents through custom remote MCP servers in `/apps/byo` and manage them on `/apps/:id/permissions` > - Unauthenticated custom MCP OAuth drafts failed catalog reads with `oauth_refresh_missing`, displayed as `Paused`, and left operators on a dead-end `Retry` error screen with no sign-in, auth-method switch, or remove controls > - The `/apps/byo` setup flow also lacked upfront read-only auth detection, display-name editing, custom draft resume, and detached-tab OAuth completion polling > - Custom remote MCP servers must work smoothly out of the box without dead ends or manual trial-and-error > - This pull request fixes backend OAuth draft/catalog truthfulness, adds a read-only custom MCP auto-detection probe, adds dedicated draft setup and error recovery on `AppDetail`, and improves `/apps/byo` auto-detection, resume, and OAuth waiting UX > - The benefit is that operators can connect and recover any standards-compliant remote MCP server cleanly without hitting false expired-credential dead ends ## Linked Issues or Issue Description **What happened?** Opening an unauthenticated custom remote MCP OAuth draft at `/apps/:id/permissions` triggered a live remote catalog refresh that threw `422 oauth_refresh_missing` (`"OAuth credentials have expired and need to be reconnected."`), overwrote stored health to `failed`, displayed status `Paused`, and replaced the Permissions tab with a looping `Retry` box. Operators had no way to start sign-in, change the sign-in method, see OAuth callback failure details, or remove the connection. In `/apps/byo`, pasting a URL did not detect auth upfront, did not allow editing the display name, failed to resume custom MCP drafts via `?resume=<id>`, duplicated the `Unverified server` badge, and stopped polling when opening sign-in in a new tab. **Expected behavior** Unauthenticated OAuth drafts should remain readable without failing catalog reads or reporting expired credentials, show `Setup incomplete` with clear `Sign in`, `Change sign-in method`, `Remove`, and `Connection details` controls, surface OAuth callback errors inline, and keep recovery actions visible when catalog loading fails. `/apps/byo` should detect auth upfront in a read-only probe, allow naming the connection, resume custom MCP drafts cleanly, and detect OAuth completion even when sign-in opens in a new tab. **Steps to reproduce** 1. Create a custom remote MCP OAuth draft via `/apps/byo` or `POST /api/companies/:companyId/tools/apps/connect` without completing browser OAuth consent. 2. Open `/<prefix>/apps/<connectionId>/permissions`. 3. Observe `Paused` and `"Couldn't load tools for this app / OAuth credentials have expired and need to be reconnected. [Retry]"` with no sign-in or recovery controls. **Paperclip version or commit** `master` (`fd8ad7d5b8`) **Deployment mode** Local dev (pnpm dev) ## What Changed - **Backend OAuth draft & catalog truthfulness** - Export `isConnectionAwaitingFirstSignIn` in `server/src/services/tool-access/connections/first-sign-in.ts` and skip remote `refreshCatalog()` in `server/src/services/tool-access/catalog/reader.ts` when an unauthenticated OAuth draft has an empty catalog. - Distinguish never-authorized OAuth connections/grants (`422 oauth_challenge`: `"This app needs you to sign in."`) from genuinely expired tokens missing a refresh token (`422 oauth_refresh_missing`) in `server/src/services/tool-access/oauth/grant-refresh.ts` and `server/src/services/tool-access/oauth/connection-refresh.ts`. - Annotate `firstSignInPending` on `getConnection` in `server/src/services/tool-access.ts` to match `listConnections`. - **Read-only custom MCP auto-detection probe** - Add `probeGenericMcpSchema` and `GenericMcpProbeResult` in `packages/shared`, capture optional `resource_name` in `server/src/services/tool-access/oauth/discovery.ts`, implement read-only `createGenericMcpProbe` in `server/src/services/tool-access/connections/probe-mcp.ts`, expose `POST /api/companies/:companyId/tools/apps/probe-mcp` in `server/src/routes/tool-access.ts`, and add `toolsApi.probeGenericMcp` in `ui/src/api/tools.ts`. - Refresh `tests/runner-e2e/source-sdk-public-inputs.json` for the shared schema and type additions. - **App detail setup, recovery, and management UI** - Show `Setup incomplete` for draft connections in `ui/src/pages/apps/AppDetail.tsx` and `ui/src/pages/apps/Connections.tsx`. - Add `FinishSetupCard` in `AppDetail.tsx` with `Sign in` (shared, personal, and agent policies), `Change sign-in method`, inline OAuth return error recovery (`?oauth=failed|denied`), live completion polling, `Remove`, and `Connection details`. - Scope catalog fetch errors to the Actions area so `IdentitiesSection`, `ReconnectCard`, and custom MCP management (`AdvancedPanel`) stay accessible. - **BYO setup, resume, and OAuth waiting UX** - Run background read-only probing on `/apps/byo` Step 2 in `ConnectionSetupFlow.tsx` and `GenericMcpConnectStep.tsx`, add an editable Display name input, use `Server URL · Connect` for the BYO stepper, and support resuming/reconnecting custom MCP drafts via `?resume=<id>&editAuth=1`. - Remove the duplicate `Unverified server` badge and stuck disabled `Opening …` button on `OAuthConnectStateScreen`, use non-workspace copy for custom MCP servers, and keep polling connection activation after clicking `Open sign-in in a new tab`. ## Verification - Ran server and UI regression tests (183/183 passing): - `pnpm vitest run server/src/__tests__/generic-mcp-connection.test.ts server/src/__tests__/tool-access-cancelled-first-sign-in.integration.test.ts ui/src/pages/apps/AppDetail.test.tsx ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx ui/src/pages/apps/generic-mcp-connect.test.ts` - Ran package typechecks and UI checks: - `pnpm --filter @paperclipai/shared typecheck` - `pnpm --filter @paperclipai/server typecheck` - `pnpm --filter @paperclipai/ui typecheck` - `node scripts/check-query-error-rendering.mjs` (0 findings) - `pnpm run check:token-gates` (0 violations in changed files) - Verified end-to-end locally in an isolated worktree dev server against live remote OAuth MCP endpoints for draft setup, `Change sign-in method` resume, upfront read-only auto-detection, and OAuth waiting screen. ## Risks - Low risk: existing active and expired OAuth connections keep `oauth_refresh_missing` behavior unchanged (covered by explicit regression tests). - The new `/probe-mcp` route uses the same company/management authorization guards, SSRF/private-network checks, self-loop protection, and OAuth endpoint policy as `/apps/connect`, performs zero database writes, and makes zero DCR `POST` requests. - `packages/shared` exports changed, so `tests/runner-e2e/source-sdk-public-inputs.json` was regenerated for CI. ## Model Used - Google Antigravity (`gemini-3-pro`, extended thinking, tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
3befcd245b |
feat(connections): add LinkedIn REST connector (v1 personal posting) (#23388)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - App connectors let agents call external APIs under company/user
grants, risk classification, and audit governance
> - LinkedIn does not publish an official remote MCP server, and its
public API separates self-serve personal posting (`Share on LinkedIn`)
from vetted commercial Company Page management (`Community Management
API`)
> - Users want a governed native LinkedIn connector without waiting
weeks for commercial review or relying on ToS-violating scrapers
> - This pull request adds a reviewed native LinkedIn REST adapter
(`server/src/services/connectors/linkedin/`) registered in
`rest-registry.ts`, extracts a shared governed REST transport
(`server/src/services/connectors/rest-transport.ts`) used by LinkedIn,
Vercel, and Supabase, and wires managed Paperclip Cloud OAuth
(`linkedin.share`) plus customer-owned OAuth fallback
> - The benefit is governed personal LinkedIn publishing
(`linkedin_get_profile`, `linkedin_create_post`, `linkedin_delete_post`)
with S4 destructive classification, shared transport security
guarantees, and clean expansion room for v2 Company Page support
## Linked Issues or Issue Description
**Subsystem affected**
Cross-cutting (multiple of the above)
**Problem or motivation**
Paperclip has no native LinkedIn connector. LinkedIn does not publish an
official remote MCP server, and standard self-serve OAuth requires a
pre-registered LinkedIn Developer App with exact callback URIs and
explicit governance for public broadcasts.
**Proposed solution**
Add a reviewed native LinkedIn REST adapter
(`server/src/services/connectors/linkedin/`) in `rest-registry.ts`
supporting v1 self-serve OIDC Sign In + Share on LinkedIn (`openid`,
`profile`, `email`, `w_member_social`), backed by a shared governed REST
transport (`server/src/services/connectors/rest-transport.ts`) shared
across LinkedIn, Vercel, and Supabase, paired with the `linkedin.share`
managed OAuth profile in `paperclip-cloud` and a customer-owned OAuth
fallback.
**Alternatives considered**
- Remote MCP: ruled out because LinkedIn has no official MCP server.
- Waiting for Community Management API review before v1: deferred to v2
so personal posting ships now without blocking on commercial app review.
## What Changed
- Extracted shared governed REST transport
(`server/src/services/connectors/rest-transport.ts` and
`rest-transport.test.ts`) owning pre-`Headers` Bearer validation, token
redaction in strings and object keys, origin/prefix pinning, `redirect:
"error"`, deadline racing with forged-504 rejection, input/output byte
caps with reader cancellation, and unified write uncertain-outcome
(`408`/`5xx`/unparseable 2xx) handling; converged LinkedIn, Vercel, and
Supabase adapters onto it.
- Added reviewed LinkedIn REST adapter
(`server/src/services/connectors/linkedin/catalog.ts`, `index.ts`,
`index.test.ts`) using `LinkedIn-Version: 202611` and registered it in
`server/src/services/connectors/rest-registry.ts`:
- `linkedin_get_profile` (`read`, also powers `probe()` via `GET
/v2/userinfo`)
- `linkedin_create_post` (`destructive`, S4; derives `author` URN from
authenticated grant via `POST /rest/posts`)
- `linkedin_delete_post` (`destructive`, S4; validates post URN via
`DELETE /rest/posts/{encoded_urn}`)
- Added `packages/shared/src/linkedin-connectors.ts` (`linkedin.share`
profile & scopes) and exported from `packages/shared/src/index.ts`.
- Wired `linkedin` / `linkedin.share` into
`server/src/services/paperclip-cloud-connector.ts`,
`server/src/services/tool-access/oauth/client-settings.ts` (with
exhaustive `managedConnectorIssuer` mapping), and
`server/src/services/tool-access/oauth/authorization-start.ts`.
- Added official sanitized LinkedIn SVG
(`ui/public/brands/apps/linkedin.svg`) and registered it in
`ui/public/brands/apps/manifest.json`.
- Added reviewed catalog override
(`scripts/app-definition-overrides/linkedin.json`), regenerated
`packages/shared/src/app-definitions/linkedin.json` and
`app-definitions.generated.ts`, added `"linkedin"` to
`CONNECTABLE_APP_SLUGS`, and added permission reviews in
`doc/connections/tool-method-permission-reviews.json`.
- Added `doc/connections/LINKEDIN.md` and indexed it in
`doc/connections/README.md`.
- Merged `master` and resynced
`tests/runner-e2e/source-sdk-public-inputs.json`.
## Verification
- `node scripts/check-app-brand-assets.mjs` — passed (115 brand
identities validated)
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` — passed (`changed: false`)
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — passed
- `pnpm exec vitest run
server/src/services/connectors/rest-transport.test.ts
server/src/services/connectors/linkedin/index.test.ts
server/src/services/connectors/vercel/index.test.ts
server/src/services/connectors/supabase/index.test.ts
server/src/services/tool-access/oauth/client-settings.test.ts
server/src/services/paperclip-cloud-connector.test.ts
server/src/__tests__/connector-tool-policy.test.ts
packages/shared/src/app-definitions.test.ts` — passed (8 files, 248/248
tests)
- `pnpm exec vitest run ui/src/lib/app-brand-assets.test.ts --project
@paperclipai/ui` — passed (7/7)
- `pnpm verify --explain` — exit 2 (global CI input
`doc/connections/tool-method-permission-reviews.json` changed; full CI
`ci / verify` and `ci / e2e` running on current head `cc7e3a8184`)
- **Live-provider proof (human-gated — pending):** Registering
Paperclip's LinkedIn Developer App + AWS Secrets Manager credentials on
`paperclip-cloud` (companion PR) and completing an interactive OAuth
sign-in on a real LinkedIn account are required before live-account
acceptance.
## Risks
- LinkedIn posts are public external broadcasts (S4); both
`linkedin_create_post` and `linkedin_delete_post` are classified
`destructive`, and `author` is always derived from the authenticated
grant rather than caller input.
- Standard self-serve LinkedIn tokens expire every 60 days without a
refresh token; UI copy and docs state this explicitly.
- Extracting `rest-transport.ts` touches Vercel and Supabase adapters
alongside LinkedIn; all three adapters' unit suites (80 tests combined)
plus dedicated `rest-transport.test.ts` pass and preserve existing
status/error codes while extending unified write
`408`/`5xx`/unparseable-2xx uncertain-outcome protection.
- Deploy the companion `paperclip-cloud` PR (`feat/linkedin-connector`)
and configure LinkedIn client credentials before enabling `managed`
sign-in on Cloud stacks.
## Model Used
- Google Gemini (Antigravity agentic coding assistant, tool use and code
execution enabled)
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
|
||
|
|
1f817b495c |
fix(ui): hide monitor waiting notices during active runs (#23822)
## Thinking Path > - Paperclip manages work performed by AI agents. > - Task monitors schedule later checks. > - A saved schedule can remain present during a new run. > - The UI calls that state a wait even while the agent works. > - This change gives the current run priority over monitor notices. > - Users see the monitor again after the run ends. ## Linked Issues or Issue Description Refs #19519, which added the active-run wait message. This change removes that message during execution. Searches found no open duplicate, and the roadmap has no overlapping item. The small SSH fixture repair below addresses a CI regression introduced on master by #14309. **What happened?** A task showed a running agent and a monitor waiting notice at the same time. The notice said the agent was waiting or saving work, based only on the presence of a run. **Expected behavior** Show the current run without monitor waiting notices. Keep the saved schedule. Restore both monitor surfaces after execution ends, if the monitor remains scheduled. **Steps to reproduce** 1. Schedule a task monitor. 2. Start a run on the same task before its next check. 3. Inspect the task banner and composer while the run works. 4. End the run and confirm the retained monitor appears again. **Paperclip version or commit** Reproduced against master at |
||
|
|
205482b2c2 |
fix(telemetry): emit missing server telemetry across native, onboarding, and routine paths (#23297)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip emits first-party product telemetry from server lifecycle transitions so operators and Cloud analytics can measure real agent runs, completions, onboarding, and routines > - A full audit of every `track*` helper in `packages/shared/src/telemetry/events.ts` found several server code paths that perform real product transitions directly in the database without emitting their existing telemetry events: native/reconciliation terminal run failure writers (`agent.task_run`), agent-accepted `native_completion_review` closures (`agent.task_completed`), `active-run-watchdog` overwriting a null `lastHeartbeatAt` (suppressing `agent.first_heartbeat`), `onboarding-seed` creating the first agent and mission goal (`agent.created`, `goal.created`), routine suggestions creating a routine (`routine.created`), and standing check reports recording a routine run (`routine.run`) > - Because those paths bypass the REST routes or `emitTerminalAgentTaskRun` (which skips rows already written to `"failed"`), deployments under-report failed native runs, agent-reviewed completions, onboarding hires, and routine activity > - This pull request wires up the existing telemetry helpers at each missing server-side transition after transaction commit using a shared terminal-failure emitter, passes an explicit root database handle for post-commit operator-containment telemetry, skips non-terminal `retryable_failure` writes while emitting non-blocking telemetry on `retryable_failure -> terminal_failure` / `committed` transitions (including superseded retry retirement), keeps `agent-task-run-telemetry.ts` free of circular imports from `run-failure-report.ts`, updates `packages/shared/src/telemetry/README.md`, and adds embedded-Postgres regression tests covering every restored path > - The benefit is complete, deduplicated, non-blocking server-side telemetry across native runtime, onboarding, and routine flows without changing any telemetry contract schema ## Linked Issues or Issue Description Refs #22963 **What happened?** Several server-side lifecycle paths transitioned database rows directly without emitting their existing first-party telemetry events: 1. `native-session-executor.ts`, `native-restart-recovery.ts`, `native-superseded-retry.ts`, `execution-control-reconciliation.ts`, and `native-failed-run-owner-release.ts` wrote `heartbeat_runs.status = 'failed'` or transitioned `retryable_failure -> terminal_failure` directly (so `heartbeat.ts`'s `emitTerminalAgentTaskRun` later saw `previousStatus === updated.status` and skipped `agent.task_run`). 2. `issue-thread-interactions.ts` allowed an agent reviewer to accept a `native_completion_review` confirmation card and move an `in_review` task to `done` without emitting `agent.task_completed`. 3. `active-run-watchdog/adapters/postgres.ts` set `agents.lastHeartbeatAt = new Date()` unconditionally when folding a silent run instead of using `settledHeartbeat(now)`, suppressing `agent.first_heartbeat` for never-heartbeated agents. 4. `onboarding-seed.ts` created a company's first agent and mission goal without emitting `agent.created` or `goal.created`. 5. `routine-suggestions.ts` created routines from task suggestions without emitting `routine.created`, and `routine-standing-checks.ts` inserted completed `routine_runs` without emitting `routine.run`. **Expected behavior** Each of those committed transitions emits its existing first-party telemetry event once after commit, non-blocking, with accurate company and person scope (`withTelemetryActor` / `withTelemetryCompany`), using an explicit live root DB handle after outer transaction commit, skipping pending native retries (`retryable_failure`), and emitting no duplicates on replay or rollback. **Steps to reproduce** 1. Trigger any of the paths above in embedded Postgres (as exercised in `server/src/__tests__/missing-server-telemetry-emissions.test.ts`). 2. Observe that the database state transitions as expected, while the corresponding telemetry event is missing, dropped on a finished transaction, prematurely emitted on a retryable native failure, or blocking finalization while pending. **Paperclip version or commit** Merged cleanly with `master` at `054b4e1395b7f246e2c18d222b701595daf5522b` (PR head `b4e70c295b78de4bdcec1788e342c421cce1e138`). ## What Changed - `server/src/services/agent-task-run-telemetry.ts` & `server/src/services/run-failure-report.ts`: keep `isRunFailureStatus`, `isPendingNativeRetry`, and `isNewTerminalRunFailure` as pure leaf helpers in `agent-task-run-telemetry.ts` (re-exported by `run-failure-report.ts`) and colocate `emitTerminalRunFailure(db, run, options)` in `run-failure-report.ts` so `agent-task-run-telemetry.ts` never imports `run-failure-report.ts` (avoiding a circular dependency into `status-decision-committer.ts` that broke `vi.mock("../agent-task-run-telemetry.js")` in `native-task-completed-telemetry.test.ts`). Tighten `isNewTerminalRunFailure` so writes into `failed/retryable_failure` return `false` while writes leaving `retryable_failure` into a terminal failure return `true`, guard `emitAgentTaskRun` against `isPendingNativeRetry`, and select `nativePhase` in `emitAgentTaskRunById`. - `server/src/routes/issues.ts`, `server/src/services/execution-recovery-resolution.ts`, and `server/src/services/native-runtime/native-failed-run-owner-release.ts`: require an explicit root `telemetryDb: Db` whenever `controllerContainment` is set (discriminated union type plus runtime guard, removing the `input.telemetryDb ?? input.db` and `release.telemetryDb ?? db` fallbacks) so `afterTransactionCommit` always runs `emitTerminalRunFailure` against the root pool instead of a finished outer transaction, gated on `isNewTerminalRunFailure(run, settledRun)`. - `server/src/services/native-runtime/native-run-finalizer.ts` and `server/src/services/native-runtime/native-run-projection.ts`: emit non-blocking `void emitAgentTaskRun(...)` + `void reportRunFailure(...)` on the `isNewTerminalRunFailure` branch when a native run transitions from `failed/retryable_failure` to `failed/committed`, ensuring telemetry DB lookups never block finalization, projection, review responses, or chat settlement. - `server/src/services/native-runtime/native-superseded-retry.ts`, `server/src/services/native-runtime/native-finalization-reconciler.ts`, and `server/src/services/native-runtime/native-restart-recovery.ts`: return the retired `heartbeatRuns` row from `retireSupersededNativeRetry` so both `claimNativeSessionResumptions` and `claimNativeRestartRecoveries` emit `agent.task_run` and `reportRunFailure` once after commit when retiring a superseded `retryable_failure` run to `terminal_failure`. - `server/src/services/native-runtime/native-session-executor.ts`: select `runtimeMode` and `nativePhase` before the failure write, gate on `isNewTerminalRunFailure(runBeforeWrite, updatedRun)`, and emit via `emitTerminalRunFailure(input.db, terminalRunToReport, { failureReport: { nativeCloseFailure: error } })`. - `server/src/services/native-runtime/native-restart-recovery.ts`: return `updatedRun` from `endNamespaceUnverifiedRun` and call `emitTerminalRunFailure` after commit in both `claimNativeRestartRecoveries` and `boundAwaitingEvidence` (making `boundAwaitingEvidence` consistent with inline unverified-run termination for both telemetry and Sentry failure reporting). - `server/src/services/execution-control-reconciliation.ts`: gate terminal failure detection on `isNewTerminalRunFailure(run, updatedRun)` and emit via `emitTerminalRunFailure(db, terminalRunToReport)`. - `server/src/modules/active-run-watchdog/adapters/postgres.ts`: use `settledHeartbeat(now)` instead of `new Date()` when folding a silent run so a never-heartbeated agent keeps `lastHeartbeatAt = null` until its first real heartbeat. - `server/src/services/issue-thread-interactions.ts`: call `void emitAgentTaskCompleted(committedDb, completedTask)` in the post-commit `publish` hook when an agent reviewer accepts a `native_completion_review` confirmation card and closes the task to `done`. - `server/src/services/onboarding-seed.ts`: emit `trackAgentCreated` (after hire commit) and `trackGoalCreated` (via `afterTransactionCommit`) with `withTelemetryActor` when onboarding seed creates a new first agent or mission goal. - `server/src/services/routine-suggestions.ts`: emit `trackRoutineCreated` with `withTelemetryActor` after both the routine and its trigger are created. - `server/src/services/routine-standing-checks.ts`: emit `trackRoutineRun` (`source: STANDING_CHECK_TRIGGER_KIND` = `"heartbeat"`, `status: "completed"`) with `withTelemetryCompany` after committing a standing-check report. Emitting the raw value follows `packages/shared/src/telemetry/README.md`; the receiving layer and `posthog-direct/enum-fallbacks.generated.ts` normalize unknown `routine.run.source` values to `"other"` until `"heartbeat"` is promoted in the telemetry schema. - `packages/shared/src/telemetry/README.md` & `tests/runner-e2e/source-sdk-public-inputs.json`: document the restored `agent.task_run` and `agent.task_completed` emission paths per `rules/data-paths.mdc`. - `server/src/__tests__/missing-server-telemetry-emissions.test.ts`: add embedded-Postgres TDD regression tests covering every restored path, including `isNewTerminalRunFailure`, the real board containment route (`POST /api/issues/:id/recovery-actions/resolve`) for both `running` and `retryable_failure` runs, `native-session-executor` retryable vs terminal settlement, `native-restart-recovery` inline and `boundAwaitingEvidence` termination, non-blocking `finalizeNativeRun` / `projectCommittedRun` while `emitAgentTaskRun` is pending, superseded-retry retirement telemetry in both `claimNativeRestartRecoveries` and `claimNativeSessionResumptions`, and strict `telemetryDb` enforcement on `validateExecutionReconciliation`. ## Telemetry Contract Exception (`rules/data-paths.mdc`) - **Unchanged generated contract exception:** `packages/shared/src/telemetry/generated/paperclip-telemetry.ts` has no diff in this PR because all six emitted events (`agent.task_run`, `agent.task_completed`, `agent.created`, `goal.created`, `routine.created`, `routine.run`) and all of their dimensions, types, and optionality already exist unchanged in the generated contract. No new event names, dimensions, or enum values were added to the telemetry contract. - **Documentation & privacy review preserved:** `packages/shared/src/telemetry/README.md` is updated in this PR to document the restored emission paths, and privacy review remains requested per `rules/data-paths.mdc` because this PR adds callers to existing helpers in `packages/shared/src/telemetry/events.ts`. ## Verification - **RED (initial review-finding regression proof before fix on `9f10d34af2`):** `pnpm --filter @paperclipai/server exec vitest run src/__tests__/missing-server-telemetry-emissions.test.ts -t "classifies pending native retries|board containment route|retryable native session failures"` — **3/3 failed**. - **RED (targeted P1/CI/review fix pass before `b4e70c295b`):** - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-task-completed-telemetry.test.ts` — **3/3 failed** (reproducing CI shard 16 failure caused by the `agent-task-run-telemetry.ts -> run-failure-report.ts` circular import into `status-decision-committer.ts`). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/missing-server-telemetry-emissions.test.ts -t "without awaiting emitAgentTaskRun|retiring a superseded native retry|requires an explicit root telemetryDb"` — **3/3 failed** (reproducing blocking `await emitAgentTaskRun`, missing `agent.task_run` on superseded retry retirement, and silent `telemetryDb` fallback to `input.db`). - **GREEN (on final head `b4e70c295b78de4bdcec1788e342c421cce1e138`):** - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/missing-server-telemetry-emissions.test.ts` — **1/1 file, 12/12 tests passed**. - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-task-completed-telemetry.test.ts src/__tests__/heartbeat-status-preserving-telemetry.test.ts src/__tests__/agent-task-run-telemetry.test.ts` — **3/3 files, 59/59 tests passed** (3 + 1 + 55). - **Test budget:** `node scripts/check-test-budget.mjs --files server/src/__tests__/missing-server-telemetry-emissions.test.ts` — **PASS** (113 nightly suites validated, 1 test file checked). - **Verify scope & local gap:** Local `tsc --noEmit` was skipped to avoid exceeding the container's shared 9.7 GiB cgroup memory limit; GitHub PR CI supplied full typecheck, build, serialized server suites (`ci / verify`), and E2E (`ci / e2e`) verification for head `b4e70c295b78de4bdcec1788e342c421cce1e138`. - **GitHub CI on `b4e70c295b78de4bdcec1788e342c421cce1e138`:** - `ci / verify` — **PASS** (https://github.com/paperclipai/paperclip/actions/runs/47455114528/job/145468380453; includes Typecheck + Release Registry, Build, policy, Runner support/package/native server suites, and all 20 server test shards). - `ci / e2e` — **PASS** (https://github.com/paperclipai/paperclip/actions/runs/47455114528/job/145468199932; all 16 E2E shards). - All 87 status checks completed with zero failures and zero pending checks. - **Automated reviews on `b4e70c295b78de4bdcec1788e342c421cce1e138`:** Greptile **5/5** (`SUCCESS`, unchanged-contract exception recorded), Ponytail **5/5** (`Verdict: ship`), Feynman **4/5** (zero functional defects; structural rationale recorded below and in threads, 17/17 review threads resolved). - **Structural decisions (`rules/pull-request-review.mdc` & `rules/test-budget.mdc`):** - `server/src/services/native-runtime/native-finalization-reconciler.ts` grew from 1,000 lines on `master` to 1,006 lines (+6 net lines) to keep the `retiredSupersededRun` capture, error-clear, and post-commit `void emitTerminalRunFailure` call locally visible inside `claimNativeSessionResumptions` rather than bundling an unrelated reconciler refactor into this telemetry fix. - `server/src/__tests__/missing-server-telemetry-emissions.test.ts` (1,447 lines) keeps all 12 embedded-Postgres telemetry regressions in one shared `beforeAll` suite (grouped by domain `describe` blocks) to avoid multiplying disposable Postgres startup cost across CI shards per `rules/test-budget.mdc`. ## Risks - Low risk. No telemetry schemas, event names, or dimension contracts changed; all new emissions run after transaction commit as best-effort/fire-and-forget and catch errors so telemetry can never block or fail product flows. - `native-restart-recovery.ts`'s `boundAwaitingEvidence` and `retireSupersededNativeRetry` callers now invoke terminal failure telemetry/reporting after commit, matching inline unverified-run termination. - Deployments will see more accurate counts for failed `agent.task_run`, agent-reviewed `agent.task_completed`, `agent.created` / `goal.created` during onboarding, and `routine.created` / `routine.run`, which is the intended fix. - Requesting privacy review per `rules/data-paths.mdc` because this PR adds callers to existing helpers in `packages/shared/src/telemetry/events.ts`. ## Model Used - Google Antigravity (Gemini 4 Neon, High reasoning, tool use and code execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups (explicit unchanged-contract exception recorded per `rules/data-paths.mdc`) - [x] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
6a5dfc0288 |
feat(recents): store sidebar Recents on the server so every client shares one list (#23706)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The sidebar Recents list shows the tasks from a person's own recent activity > - Each browser kept Recents in `localStorage`. A laptop, a phone, and a second browser each showed a different list > - People expect one list for their account, the same on every client > - This pull request moves Recents to the server. The server keeps one list for each person in each company. The UI shows that list and gets live updates when another client changes it > - The benefit is that every client shows the same Recents in the same order, and a change on one client shows on the others at once ## Linked Issues or Issue Description **Is your feature request related to a problem? Please describe.** Recents is kept in the browser. When I open a task on my laptop, the task does not show in Recents on my phone or in another browser. **Describe the solution you'd like** Keep Recents on the server, so that every client that I sign in to shows the same list. **Additional context** Eligibility (which rows show) does not change. The navigation summaries still decide it (see #23675). ## What Changed - `packages/db`: new `user_recent_tasks` table (company, user, issue, `recorded_at`), unique on company + user + issue. Migration `0515` creates only a new table, so it is `online_compatible`. - `packages/shared`: `RecentTaskRecord`, `RecentTaskList`, `RECENT_TASKS_MAX_ENTRIES` (200), and the `recordRecentTaskSchema` and `importRecentTasksSchema` validators. - `server`: new `recentTaskService` and routes: - `GET /api/companies/:companyId/recent-tasks/me`: the list, newest first. - `POST /api/companies/:companyId/recent-tasks/me` `{ issueId, touch }`: `touch: true` moves the task to the top (server time). `touch: false` adds a missing task below the history and does not move an existing task. - `POST /api/companies/:companyId/recent-tasks/me/import`: imports the list that a browser kept. The later time wins. - `DELETE /api/companies/:companyId/recent-tasks/me/:issueId`. - The server keeps the newest 200 rows for each person. Each change is in the activity log as `recent_tasks.*` with `entityType: "company"` and `details.userId`. The entry does not name the task. Viewers can change their own Recents, like workspace preferences. - Record, import, and list use the normal task read decision. A private or unreadable task gets the same 404 as a missing task. The import skips it, and the list does not return it. - `server/src/realtime/live-events-ws.ts`: sends `recent_tasks.*` events only to the owner's connections, without details. - OpenAPI entries for the four routes. - `ui/src/lib/recent-tasks.ts`: the module is now a client mirror of the server list, not `localStorage`. Optimistic records and removals stay applied until a server list that was requested after the server saved them arrives. This prevents a stale list from hiding a new visit. - `ui/src/hooks/useRecentTasks.ts`: fetches the server list (`queryKeys.recentTasks`). On the first load it imports the old browser list one time and then deletes the browser copy. It does not delete ineligible rows anymore. It hides them, and it requests a new summary batch when new activity occurs on a hidden task. The `awaitingRead` flow is removed because nothing deletes the row while the read is in flight. - `LiveUpdatesProvider`: a `recent_tasks.*` event refreshes Recents. Other company views do not refresh. - A failed save is tried again one time. If it fails again, the client loads the server list again, so an unsaved change does not look saved. - The import reads only the newest browser storage version. - `SidebarRecentTasks`: the "Archive" action removes the task from the server list. - `doc/PRODUCT.md`: describes the shared list. ## Verification - `cd server && npx vitest run src/__tests__/recent-tasks-routes.test.ts` (embedded Postgres): 5 passed. The tests cover: two clients of the same person see the same order; touch and passive seed; personal and company scope (teammate, other company, agent, viewer, suspended member); removal plus activity log plus live events; import, and the 200-row limit. - `cd server && npx vitest run src/__tests__/openapi-routes.test.ts`: 59 passed. - `cd server && npx vitest run src/__tests__/recent-tasks-routes.test.ts src/__tests__/live-events-toast.test.ts`: 21 passed. This includes private-task checks and owner-only socket delivery. - `cd ui && npx vitest run src/lib/recent-tasks.test.ts src/hooks/useRecentTasks.test.tsx src/context/LiveUpdatesProvider.test.ts`: all passed. New tests cover: the same list on a second client, legacy import (success and failure), the record-and-list race, server-time adoption, and live-event scoping. - `packages/db`: `migration-compatibility.ts` classifies `0515` as `online_compatible`. - `packages/shared` typecheck: no errors. `ui` typecheck: no errors in changed files (errors exist only in the ungenerated Storybook feature-map indexes). - `server`: a typecheck of the route, service, and test graph passes. The full `server` typecheck was killed by the local memory limit (exit 137). CI covers it. - `pnpm verify` returned exit 2 (the migration needs broad CI coverage). Required CI supplies that coverage. ## Risks - Medium. This adds a table and changes where Recents is kept. - Each task open now sends one more request and writes one activity row (the same as `issue.read_marked`). The live socket sends the event only to the owner's connections. - Rows that are not eligible stay in the server list (hidden) until they fall out of the newest 200. Before, the client deleted them. - The import reads `paperclip.recentTasks.v3`, `v2`, and the oldest key one time for each browser. If the import fails, the browser copy stays and the next load tries again. - An old tab from the previous release still writes to `localStorage`. The next load of a new tab imports those entries. The later time wins, so this does not reorder newer server entries. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use (shell, file edit, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [ ] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [ ] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
f530a7b167 |
Keep pause status inline and ease the agent character into sleep (#23662)
## Thinking Path
> - Paperclip helps people manage AI agents at work.
> - The agent overview shows the agent name and runtime status.
> - A pause or resume adds a status row and moves the name.
> - The name should stay in place while the agent changes state.
> - This change places the status beside the name and crown.
## Linked Issues or Issue Description
**Subsystem affected**
Agent detail header.
**Current behavior**
Pause and resume add a line of detail below the harness. The title moves
when that line appears.
**Proposed behavior**
Keep the title steady. Show progress beside the crown and keep the
paused state visible until the user resumes the agent.
## What Changed
- Resize and fade the pill with a fixed left edge. Respect reduced
motion.
- Blend the header character into its sleeping pose over 160 ms when the
agent reaches **Paused**. Keep its assigned colors and show the
onboarding sleep marks. Wake the character when resuming begins.
- Show the new pose immediately when the user requests reduced motion.
- Preserve lifecycle error details and retry controls.
- Add a development preview that lets reviewers try both transitions
without changing an agent.
## Verification
- Open an agent overview in development with `?preview=pause`. Select
**Preview pause**, wait for **Paused**, then select **Preview resume**.
- Chromium confirmed the full cycle and the 240 ms resize duration.
- Chromium confirmed that the character uses the same palette when
sleeping and awake.
- All 36 focused tests passed in four Vitest files on commit
|
||
|
|
bc526683c2 |
fix(github-chat): fix initial repository import and verify UX states (#23760)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - The GitHub Code Review Bot setup wizard registers a GitHub App,
discovers its installation repositories, imports initial repository
selections, and verifies access before activation.
> - When a user or agent saves review configuration on a draft before
installing the GitHub App, the wizard skipped initial repository import
because it required `saved.revision === 0`, leaving enabled GitHub
repositories disabled in Paperclip and showing a misleading "Enable at
least one repository from the App installation." error.
> - The wizard also closed initial repository import prematurely when
GitHub returned zero repositories, failed to refresh repositories on
retry, treated removed installations (HTTP 404) as generic 422 failures
and transient repository-sync errors as empty installations, omitted the
direct GitHub App installation link on verification errors, and kept
showing "Checking GitHub access…" while idle on a failed check.
> - This pull request decouples initial repository import from review
configuration revision, recovers verifying endpoints stuck with a
pending initial import, maps removed installations and transient
repository sync errors to structured verification check codes with
validated GitHub URLs, and updates the setup verify screen to show clear
error states, accurate paired links/labels, and active retry feedback.
> - The benefit is that pre-configured GitHub review bots connect
cleanly when the App is installed, and operators get accurate error
diagnostics, direct GitHub installation and Access settings links, and
clear retry feedback when setup checks fail.
## Linked Issues or Issue Description
**What happened?**
During GitHub Code Review Bot setup
(`/apps/chat/connect?provider=github&purpose=chat&resume=...`), the
verify step failed with "Enable at least one repository from the App
installation." even when one repository was already enabled on the
GitHub App installation. The verify screen also kept displaying
"Checking GitHub access…" when idle, did not link to the GitHub App
installation URL, and did not clearly explain whether the problem was on
GitHub or in Paperclip Access settings.
**Expected behavior**
Installing the GitHub App with one or more repositories enabled should
import and enable those repositories during initial setup even if custom
review configuration was saved earlier, while preserving that saved
configuration. When verification genuinely fails for missing
repositories, missing permissions, removed/suspended installations, or
transient GitHub repository sync errors, the screen should stop polling,
replace the checking indicator with a clear error card, pair each GitHub
link with an accurate label, link to Paperclip Access settings, and show
active checking feedback only while a retry or refetch is running.
**Steps to reproduce**
1. Create a GitHub Code Review Bot draft and save custom review
configuration (`PUT /api/chat-endpoints/:id/github/configuration`),
incrementing configuration revision to `1`.
2. Register and install the GitHub App on GitHub with one repository
selected, verify webhook delivery, and link a GitHub identity.
3. Resume
`/apps/chat/connect?provider=github&purpose=chat&resume=<endpointId>`.
4. Observe that `POST /api/chat-endpoints/:id/github/setup` leaves the
repository disabled, marks `initialRepositoriesImported: true` while
leaving `initialRepositoryImportPending: true`, and returns `state:
"verify"` with "Enable at least one repository from the App
installation." and no GitHub installation link.
**Paperclip version or commit**
Reproduced on `master` at commit `e2e2265085`.
**Deployment mode**
Self-hosted server
**Agent adapter(s) involved**
Not adapter-specific (core bug)
## What Changed
- Extract initial GitHub repository import eligibility/transition logic
into `server/src/services/chat-github-initial-import.ts` and decouple
initial repository import in `server/src/services/chat-github-wizard.ts`
from `saved.revision === 0` so pre-saved review configuration no longer
blocks enabling repositories granted during initial App installation,
while keeping `saved.revision === 0` strictly for default review
configuration writes.
- Recover verifying endpoints left in the prior half-state
(`initialRepositoriesImported: true` with
`initialRepositoryImportPending: true` and `repositorySelectionSaved`
unset) without re-enabling repositories after an explicit user save
(`repositorySelectionSaved: true`).
- Keep `initialRepositoryImportPending` open when GitHub returns zero
repositories during initial import
(`server/src/services/chat-github-wizard.ts` and
`server/src/services/chat-channels/resource-reconciliation.ts`), refresh
repository inventory on wizard retry when no enabled available
repository exists, and track transient repository-sync errors so failed
`/installation/repositories` refreshes skip initial import and emit
`repositories_sync_failed` instead of misreporting
`no_installation_repositories`.
- Map HTTP 404 on `/app/installations/:id` in
`server/src/services/chat-github-management.ts` to
`installation_missing` + `managementUrl` (keeping 401/403/5xx and
transient failures separate), and enforce `!permissionsOk` precedence
(`permissions_required`) over cached repository state.
- Preserve `setup.github.managementUrl` and sibling setup fields via
atomic `jsonb_set` in
`server/src/services/chat-channels/github/app-setup.ts`.
- Centralize strict GitHub URL validation
(`safeGitHubInstallationManagementUrl`, `safeGitHubAppInstallUrl`,
`safeGitHubAppUrl`) and structured `GitHubVerificationCheckCode` values
(including `repositories_sync_failed`) in
`packages/shared/src/types/github-app-setup.ts` and
`packages/shared/src/index.ts`, with OpenAPI schema updates in
`server/src/routes/openapi.ts` and UI API types in
`ui/src/api/githubChat.ts`.
- Extract `deriveGitHubVerifyView`, `shouldPollGitHubVerify`, and
`<GitHubVerifyStatus />` into
`ui/src/pages/apps/chat/GitHubVerifyStatus.tsx` and simplify
`ui/src/pages/apps/chat/GitHubChatSetup.tsx` so verification failures
stop 5-second background polling, pair every external GitHub link with
an accurate label (including `installation_missing` fallback to
`managementUrl`), show active checking feedback only while
retrying/refetching, and link to Paperclip Access and Connection
settings.
- Add unit, integration, and UI tests in
`server/src/services/chat-github-initial-import.test.ts`,
`server/src/services/chat-github-management.test.ts`,
`server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts`,
`ui/src/pages/apps/chat/GitHubVerifyStatus.test.ts`, and
`ui/src/pages/apps/chat/GitHubChatSetup.test.tsx`.
- Update `tests/runner-e2e/source-sdk-public-inputs.json` for the shared
type and helper exports.
## Verification
Tested on Linux through revision `9a5a949098`:
- Red-green TDD proofs:
- Pre-saved review configuration and stuck verifying endpoint recovery
(`server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts`):
confirmed both failed before the wizard fix (`Received: "verify"`,
`Expected: "connected"`) and passed after.
- Removed installation HTTP 404 (`installation_missing` +
`managementUrl`) and `!permissionsOk` precedence
(`server/src/services/chat-github-management.test.ts` + integration
test): confirmed red before fix, green after.
- Transient `/installation/repositories` 503 failure with empty cache
and valid permissions (`repositories_sync_failed`, followed by
successful retry -> `connected`) and UI `installation_missing` fallback
label (`ui/src/pages/apps/chat/GitHubVerifyStatus.test.ts`,
`GitHubChatSetup.test.tsx`,
`github-setup-and-access.integration.test.ts`): confirmed red before
fix, green after.
- Server unit & OpenAPI tests on `9a5a949098`:
- `pnpm --filter @paperclipai/server exec vitest run
src/services/chat-github-management.test.ts
src/services/chat-github-initial-import.test.ts` (47/47 passed: 39
management + 8 initial-import).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/openapi-routes.test.ts` (59/59 passed).
- Server integration tests (`c1f234335f`; full suite running in CI on
merged head `9a5a949098`):
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/chat-channels/github-setup-and-access.integration.test.ts
-t "recovers from an empty initial GitHub repository inventory|keeps
explicitly disabled repositories disabled|imports GitHub App
installation repositories even when review configuration was
pre-saved|recovers a verifying endpoint whose
initialRepositoriesImported|returns installation_missing with
managementUrl when the GitHub installation is removed|surfaces a
retryable repositories_sync_failed check"` (6/6 passed).
- UI tests & typecheck on `9a5a949098`:
- `pnpm --filter @paperclipai/ui exec vitest run
src/pages/apps/chat/GitHubChatSetup.test.tsx
src/pages/apps/chat/GitHubVerifyStatus.test.ts
src/pages/apps/chat/chat-ui-contract.test.ts` (27/27 passed) and
`ui/src/lib/analytics/replay-masking.test.tsx` (236/236 passed).
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/ui
typecheck` (passed).
- `node scripts/check-token-gates.mjs` — zero violations in touched
files.
- Release registry check on `9a5a949098`:
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
|
||
|
|
bf49fce70f |
chore(lockfile): refresh pnpm lockfiles (#23802)
## Thinking Path > - Paperclip uses a dependency lock for reproducible builds. > - Dependency changes on master need matching lock entries. > - Paid eval reports also pin a reviewed offline correction. > - Reports must install before paid model work starts. > - This automated PR keeps the lock and report proof together. ## Linked Issues or Issue Description **What happened?** Dependency manifests on master changed after the last committed lock refresh. **Expected behavior** Frozen installs must match those manifests. Eval reports must retain matching offline lock proof. **Steps to reproduce** Run a frozen install before and after this lock refresh. ## What Changed - Refresh the dependency lock from the manifests on master. - Refresh the sandbox provider lockfiles from their manifests on master. - Include the matching offline report correction and hashes. - Resync the SDK public source proof's lock pins from the refreshed lock. ## Verification - Pinned pnpm resolution completed with lifecycle scripts disabled. - The report proof refresh accepted the reviewed committed baseline. - The workflow rejected changes outside the lock and report proof files. ## Risks The lockfile bot merges this PR without CI or review when it verifies every added version on npm and all versions outside the harness allowlist are at least 3 days old. Otherwise the PR waits for a maintainer, and the daily refresh tries again. The bot merges only the exact commit this workflow generated from manifests already reviewed on master. Unknown report lock baselines remain blocked. This update changes no permissions or paid enable gates. ## Model Used None — generated by pnpm and the deterministic report-lock updater. ## Checklist - [x] Thinking path and problem description included - [x] Generated lock and matching report proof included - [x] Release-age gate decides between bot merge and maintainer review Co-authored-by: lockfile-bot <lockfile-bot@users.noreply.github.com> |
||
|
|
ab79cb9cdd |
fix(heartbeat): wait for an updating runtime before workspace setup fails (#23779)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Before a run starts its agent, Paperclip prepares the task workspace through a workspace provider plugin > - A hosted agent computer can apply an update. While it updates, it finishes its running tasks and refuses new workspaces > - The provider can only report this refusal as a generic `remote_incomplete` failure. Setup retries that failure two times in about 90 seconds (#23764), but an update can wait for running tasks for an hour > - So each new task on that computer fails setup, reports an error, and stops, although it only had to wait > - This pull request adds the closed provider reason `runtime_updating` and a separate wait lane for it. Setup holds the run and retries the same workspace every 2 minutes for up to 1 hour. The wait does not use the failure retry budget, and Paperclip does not report the run as a failure while the wait continues > - The benefit is that new tasks wait for an updating agent computer and then start, instead of failing ## Linked Issues or Issue Description Refs #23764, #23362 **What happened?** A hosted agent computer refused every new workspace preparation while it applied an update and finished its long running tasks. The provider reported each refusal as `remote_incomplete`. Setup failed each new run. Every retry of the same workspace failed the same way, and each failure was reported to error tracking. On one staging stack this happened 34 times in two hours, for two agents. **Expected behavior** A provider can say that the selected runtime is updating. Setup then holds the run and retries the same workspace after the update. The retry does not spend the failure budget. Paperclip reports the failure only if the wait ends without success. **Steps to reproduce** 1. Start a legacy run whose workspace preparation calls a workspace provider plugin. 2. Have the provider reject preparation because its runtime is updating. Before this change, the only fitting reason is `remote_incomplete`. 3. Setup records `workspace_storage_incomplete` and retries two times (30 s and 60 s). Then the task stops and the failure is reported, while the runtime is still updating. **Paperclip version or commit** `master` at `30334c1f03`. **Deployment mode** Hosted (Paperclip Cloud agent computers). A self-hosted workspace provider can use the same reason. ## What Changed - `packages/plugins/sdk/src/workspace-operation-error.ts`: add the closed reason `runtime_updating` ("the selected runtime is applying an update and refuses new workspaces until it finishes"). - `server/src/services/workspace-provider-failure.ts`: give `runtime_updating` a fixed, retryable message. Map it to the new setup code `workspace_runtime_updating`. Add `WORKSPACE_RUNTIME_UPDATING_RETRY` (reason `runtime_update_wait`, 30 attempts, 2 minutes apart). Add the code to `WORKSPACE_STORAGE_RETRY_CODES`, so the existing deferred error report also covers it. - `server/src/services/heartbeat/run-completion.ts` and `heartbeat/retries.ts`: schedule a failed pre-dispatch `workspace_runtime_updating` run with the wait lane, and use the lane's budget in `failedRunRetryBudgetSpent`. This is the same pattern as `runner_revision_mismatch`. - `server/src/services/execution-recovery-attempt.ts`, `modules/run-dispatch/domain/wake-context.ts`, `task-interruption-presentation.ts`: `runtime_update_wait` is an uncharged preparation wait. An answered interaction keeps its continuation through the wait, and the task shows a wait, not a failure. - `failed-preparation-retry.ts`, `legacy-execution-recovery.ts`, `recovery/service.ts`, `agent-task-run-telemetry.ts`: treat `workspace_runtime_updating` like the other transient workspace preparation codes. - `recovery/stranded-notice.ts`: add a notice for a wait that ended without success ("Agent computer was still updating"). ## Verification - Red before the change (test files only, source reverted): 9 new tests fail in `workspace-provider-failure.test.ts`, `execution-recovery-attempt.test.ts`, `heartbeat/retries.test.ts`, `heartbeat/run-completion.test.ts` and `run-failure-report-sandbox-resume.test.ts`. - `pnpm verify` did not run: its workspace link repair failed for `plugin-orchestration-smoke-example`, before test selection. The SDK change also affects many packages, so CI supplies the broad coverage. - Green after the change: the same 5 files pass (267 tests). Related files also pass: `task-interruption-automatic-path`, `task-interruption-query`, `wake-context`, `stranded-notice-remote-workspace-environment`, `task-interruption-presentation` (181 tests); `agent-task-run-telemetry`, `legacy-continuation-authority`, `heartbeat-retry-scheduling` (179 tests); plugin SDK `workspace-operation-error`, `workspace-provider` (20 tests). - `pnpm --dir server typecheck` and `pnpm --filter @paperclipai/plugin-sdk typecheck`: pass (server typecheck run with `PAPERCLIP_TYPECHECK_LOW_MEMORY=1` because of a local memory limit). - CI supplies the full suite. - Review follow-up (`cf73701742`, `d7540263bd`): update waits keep their count in `executionRetryAccounting` (`runtimeUpdateWaits`) across other retry lanes. An answered interaction whose update wait runs out is escalated like an exhausted storage wait. The pinned SDK input registry is refreshed. The two new tests failed before the fix and pass after it. `execution-recovery-attempt`, `heartbeat/retries`, `workspace-provider-failure` and `run-failure-report-sandbox-resume` pass (83 tests). `heartbeat/run-completion` and `modules/wake-queue` pass (577 tests). `tests/runner-e2e/source-sdk-public-inputs` passes (13 tests). `pnpm --dir server typecheck` passes. ## Risks - Low risk. No schema, migration, API route or wire protocol shape change. The reason set is closed and validated on both sides. An older Core that receives `runtime_updating` treats it as an unknown provider failure, as before. - A provider must not send `runtime_updating` before the new SDK is available to it. The SDK constructor rejects an unknown reason, so a provider update has to follow this change. - The wait is a bounded scheduled retry after a real refusal, not idle polling: at most 30 retries in one hour per waiting run. Each retry is one workspace preparation call. When the wait ends without success, the run is reported and the task shows a named notice with a Retry action. - Only legacy runs that fail before provider dispatch use the lane. Started and native runs keep `setup_failed`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use (code search, file edits, shell, local test execution, GitHub CLI). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
14f23fef03 |
fix(plugins): offer direct Buffer setup when Composio has no sign-in link (#23782)
## Thinking Path > - Paperclip helps people manage AI agents for work. > - Plugins lets people connect tools to their agents. > - Some tool connections use the Composio gateway. > - Buffer requires a custom OAuth app in the Composio project that serves the session. > - When that gateway returns no sign-in link, Plugins can help the user open Buffer's own MCP setup. > - This pull request opens the existing connection form with the Buffer name and endpoint filled in. ## Linked Issues or Issue Description **What happened?** Plugins showed a generic error when Composio returned no Buffer sign-in link. **Expected behavior** The user can open the direct Buffer setup from the error. For other apps, the user can open Composio's app settings. **Steps to reproduce** In Plugins, select Buffer and choose a saved Composio gateway without a configured Buffer OAuth app. Select Continue. **Additional context** [Buffer's MCP setup](https://developers.buffer.com/guides/integrations/other-ai-tools.html) accepts a Buffer API key. [Composio's Buffer setup](https://composio.dev/toolkits/buffer) requires a custom OAuth app. [Composio auth configs belong to one project](https://docs.composio.dev/kb/guide/dashboard-auth-configs-navigation). Related prior work: Refs #19408. ## What Changed - Return a machine-readable code when Composio returns no sign-in link. - Offer the direct Buffer MCP form with its official address. Offer a link to Composio app settings for other toolkits. - Clear the old sign-in link when the user requests a new one. Keep the link if the completion check fails. - Document the setup options. Refresh the shared SDK test input pins. ## Verification - Reproduced the missing-link API response with an embedded database and a Composio response fixture. The new test failed on the old server. - Passed 13 focused tests across the Composio route, Plugins setup dialog, and the MCP URL prefill flow. The replacement-link test reproduced the stale link before the fix. A second test checks that the sign-in link stays available after a failed completion check. - Sent an unauthenticated MCP initialize request to Buffer's documented endpoint and confirmed that it requires authentication. A real Buffer consent or API-key test needs a Buffer account with access. ## Risks - Low risk. The new action opens the existing MCP setup page. The user chooses the credentials and access before Paperclip creates the connection. - A valid Composio sign-in link still takes the user through Composio. ## Model Used - OpenAI GPT-6 (Codex), with repository, test, and GitHub tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
039e4c0a57 |
fix(native): stop paperclip_block from reassigning tasks and audit assignee changes (#23780)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native Paperclip Runner agents report blockers with `paperclip_block`, which includes a descriptive `blocker.owner` field (`kind` and `name`). > - PR #22962 made `paperclip_block` reassign `issue.assigneeAgentId` whenever `blocker.owner` named another company agent, including when the task was only waiting on a durable dependency (`durable_dependency_blocker_bound`). > - That collided directly with Paperclip's own execution prompt (which instructs agents waiting on a child or prerequisite task to call `set_dependencies` and then `paperclip_block` naming the dependency's agent), silently transferred task ownership with no return path, could cross multi-user AI credential boundaries, and omitted the assignee change from the `issue.updated` activity record. > - This pull request stops `paperclip_block` from reassigning tasks at all, preserves the original assignee on dependency-gated blocks, guides agents toward explicit delegation/reassignment tools (`create_task` + `set_dependencies`, `reassign_task`, `handoff_case`) at report time when no dependency exists, and records assignee field changes in native `issue.updated` activity details. > - The benefit is that waiting on a dependency resumes the original owner cleanly, ownership transfers stay explicit and auditable, and native assignee changes (such as configured review stages) appear in task activity receipts. ## Linked Issues or Issue Description Refs #22962, #21265, #22140, #22438. **What happened?** When an agent linked a prerequisite task via `set_dependencies` and followed the execution prompt by calling `paperclip_block` with the prerequisite's agent as `blocker.owner`, `status-arbiter.ts` emitted `handoffAgentId` and `status-decision-committer.ts` permanently overwrote `issue.assigneeAgentId` to that other agent. The same silent reassignment also occurred on non-dependency `current_track` and `task_wide` blocks naming another agent. Because `status-decision-committer.ts` did not record `previousAssigneeAgentId` / `assigneeAgentId` in `issue.updated` details, the assignee change was invisible in task history, and handing a task to an agent bound to another user's unshared AI credential caused repeated `ai_connection_credential_not_shared` wake failures. **Expected behavior** `blocker.owner` in `paperclip_block` is descriptive and never silently reassigns a task: - On dependency-gated blocks (`durable_dependency_blocker_bound`), the reporting agent remains `assigneeAgentId` and `unblockDescriptor.owner` so dependency completion wakes the original owner. - On non-dependency blocks naming another agent, report-time feedback rejects the report with actionable guidance pointing to `create_task` + `set_dependencies`, `reassign_task` (or `handoff_case`), or `blocker.owner.kind: "user"`. If such a report still reaches finalization, it stays blocked for `"board"` without changing `assigneeAgentId` or waking the other agent. - Whenever any committed native status decision changes `assigneeAgentId` or `assigneeUserId` (for example when starting a configured review stage), the `issue.updated` activity row records `previousAssigneeAgentId`, `assigneeAgentId`, `previousAssigneeUserId`, `assigneeUserId`, and `changes`. **Steps to reproduce** 1. Create two agents in one company (Agent A and Agent B), an upstream task assigned to Agent B, and a parent task assigned to Agent A. 2. Link the upstream task as a dependency of the parent task (`blocks`). 3. Have Agent A call `paperclip_block` with `blocker.owner: { kind: "agent", name: "<Agent B>" }`, then finalize Agent A's run. 4. Observe on `master` that the parent task's `assigneeAgentId` is silently overwritten from Agent A to Agent B with no assignee-change fields in the `issue.updated` activity log. ## What Changed - **`server/src/services/native-runtime/status-arbiter.ts`**: - Remove `handoffAgentId`, `blockerHandoffLocked`, and `resolveBlockerHandoff` so `paperclip_block` never reassigns tasks. - On `durable_dependency_blocker_bound`, keep `unblockDescriptor.owner` on `{ agentId: input.agentId }` whenever `blocker.ownerKind === "agent"` (including another agent or an unresolved/deprecated agent label), while preserving named human/board owners (`#22438`). - On non-dependency `task_wide` and `current_track` blocks naming another agent, bind `unblockDescriptor.owner` to `"board"` without reassigning, waking the other agent, or re-waking the reporting agent. - **`server/src/services/native-runtime/native-completion-feedback.ts`**: - Check dependency readiness (memoized per call) before validating `blocker.owner.kind === "agent"`: allow dependency-gated blocks naming the dependency's agent descriptively, and reject non-dependency blocks naming another or unknown agent with actionable guidance pointing to `create_task` + `set_dependencies`, `reassign_task` / `handoff_case`, or `blocker.owner.kind "user"`. - **`server/src/services/native-runtime/native-run-finalizer.ts` & `server/src/services/native-runtime/status-decision-committer.ts`**: - Remove blocker-owner handoff checks and `assigneeAgentId` handoff patching during finalization and commit. - Record `previousAssigneeAgentId`, `assigneeAgentId`, `previousAssigneeUserId`, `assigneeUserId`, and `changes` on native `issue.updated` activity events whenever a committed native status decision changes the task assignee. - **Cleanup**: - Remove unused `server/src/services/native-runtime/blocker-owner-handoff.ts` and `server/src/modules/external-agents/run-authorizer.ts` (and its export from `server/src/modules/external-agents/index.ts`). - **Tests**: - Update `server/src/services/native-runtime/status-arbiter.test.ts` and `server/src/__tests__/native-status-arbiter-corpus.test.ts` to cover dependency-gated owner preservation (including chat-bound tasks and unmatched agent labels) and non-dependency rejection + board fallback without reassignment. - Extend `server/src/services/native-runtime/native-execution-policy-review-stage.test.ts` to verify `issue.updated` activity details record assignee transitions for both human and agent configured review stages. ## Verification - **RED-before-fix (on base `c5a705ce92`)**: - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/status-arbiter.test.ts` -> 3 failed | 31 passed (34) (failed because `handoffAgentId` and `{ agentId: "reviewer" }` were emitted on dependency and non-dependency blocks). - **GREEN after fix**: - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/blocker-owner.test.ts src/services/native-runtime/evidence-classifier.test.ts src/services/native-runtime/status-arbiter.test.ts` -> 48 passed (48). - `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=120000 src/services/native-runtime/native-execution-policy-review-stage.test.ts` -> 16 passed (16). - `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=120000 src/__tests__/native-status-arbiter-corpus.test.ts -t "rejects a non-dependency|keeps accepting a human-owned|preserves the original assignee on a dependency-gated"` -> 5 passed (5 selected; 169 skipped). - `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=120000 src/services/native-runtime/native-agent-blocker.integration.test.ts` -> 17 passed (17). - `pnpm --filter @paperclipai/server typecheck` -> PASS across all 7 layers. - `node scripts/check-module-boundaries.mjs` -> PASS. - `node scripts/check-test-budget.mjs --base origin/master` -> PASS (113 nightly suites validated, 3 test file(s) checked). - `pnpm --filter @paperclipai/server exec vitest run ../tests/runner-e2e/chat-catalog-domains/internal-timeline-native-milestone.test.ts` -> 33 passed (33). - **CI & Reviews on final head `d7c54badca`**: - GitHub Actions PR workflow run [`47436506671`](https://github.com/paperclipai/paperclip/actions/runs/47436506671): `ci / verify` PASS, `ci / e2e` PASS, all 84 checks green/neutral (including Socket Security, Superagent Security Scan, and Snyk). - Greptile Review: `5/5` (zero open comments); Ponytail Paperclip Review: `5/5`; Feynman Nuclear Review: `5/5`. ## Risks - **Intentional behavior change from #22962**: Agents that previously relied on `paperclip_block` naming another agent without a dependency to silently reassign a task will now receive actionable report-time feedback directing them to `create_task` + `set_dependencies` or `reassign_task` (and any already-saved result reaching finalization will fall back to `"board"` without reassigning). - **Upgrade safety**: Existing `chat-control-recovery-stop.ts` read-only ancestry checks for historical `bind_blocker` wakes are preserved. Self-owned blocker continuations (#22140) and named human blocker routing (#22438) are preserved unchanged. - No database schema changes or migrations. ## Model Used - Google Gemini (Antigravity, high reasoning mode with code execution and tool use) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
ee05db9e16 |
fix(budgets): add Anthropic rate cards with family-max fallback and surface paused-agent budget notices (#23658)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Cost accounting prices Anthropic token receipts against rate cards
so budget policies can track spend and enforce hard stops
> - `anthropic-pricing.ts` only had rate cards for `claude-sonnet-5` and
`claude-opus-5-5`, so newer shipped models such as `claude-fable-5-2`
settled as `unpriced`
> - Because budget policies default to `unpriced_usage_policy =
"block"`, creating a spend cap on an agent that ran an unpriced model
immediately triggered a budget hard stop even when observed spend was
far below the limit
> - Meanwhile, the chat thread notice for a budget-paused agent had no
action link and did not state that messages sent while paused will not
receive a reply, and the budget incident card did not clearly explain
unpriced-usage stops or what "Keep paused" does
> - This pull request adds rate cards for shipped Anthropic models with
a conservative family-maximum fallback for uncataloged models, clarifies
the paused-agent chat notice and unpriced budget incident card, and adds
Storybook coverage
> - The benefit is that budget caps track current and future Anthropic
models accurately without false unpriced-usage lockouts, and operators
immediately see why an agent is not replying and where to resolve it
## Linked Issues or Issue Description
**What happened?**
When an agent ran a shipped Anthropic model missing from `RATE_CARDS`
(such as `claude-fable-5-2`), its usage receipts settled with
`costStatus: "unpriced"`. Creating a budget policy (which defaults to
`unpriced_usage_policy: "block"`) immediately fired a hard-stop incident
and paused the agent even when known spend was well below the limit. In
the task chat thread, the paused-agent banner gave no link to the
agent's budget page and did not clearly warn that new messages would not
trigger replies; on the budget incident card, the unpriced-usage stop
looked like a regular spend-limit alert and dismissing it via "Keep
paused" left the agent paused with no clear explanation.
**Expected behavior**
Shipped Anthropic models should have explicit rate cards, and
uncataloged models in a known Claude family (`fable`, `mythos`, `opus`,
`sonnet`, `haiku`) should fall back conservatively to the most expensive
rate card in that family rather than settling as unpriced. When an agent
is paused in chat, the notice should clearly state that messages will
not get a reply until the agent is resumed and provide a direct "Review
budget" link for budget pauses. Unpriced-usage budget stops should
clearly explain why work stopped and that "Keep paused" dismisses the
alert without resuming work.
**Steps to reproduce**
1. Run an agent on `claude-fable-5-2` using direct Anthropic API billing
so usage receipts settle as `unpriced`.
2. Add a monthly budget policy (e.g. $1,000) on that agent.
3. Observe an immediate hard-stop budget incident pausing the agent
despite low observed spend.
4. Return to the agent's chat thread and observe the paused banner lacks
a budget link and does not clearly state that new messages will not get
a reply.
## What Changed
- `server/src/services/anthropic-pricing.ts`: Added explicit standard
API rate cards for shipped Anthropic models (`claude-fable-5-2`, `5-1`,
`5`; `claude-mythos-5-2`, `5-1`, `5`; `claude-opus-5-5`, `5`, `4-8`,
`4-7`, `4-6`, `4-5`; `claude-sonnet-5-5`, `5`, `4-6`, `4-5`;
`claude-haiku-5-5`, `4-5`), normalized optional `[1m]` suffixes, and
added a dynamic family-maximum fallback (`FAMILY_MAX_RATE_CARDS`) so any
uncataloged model in a known Claude family conservatively uses the
highest rate in that group with explicit provenance.
- `server/src/services/anthropic-pricing.test.ts`: Added unit tests
covering `claude-fable-5-2` (including `[1m]`), `claude-sonnet-5-5`,
`claude-haiku-4-5`, family-maximum fallbacks across all five Claude
families, and preserving unknown/non-Anthropic models as unpriced.
- `ui/src/components/IssueChatThread.tsx`: Updated
`IssueAssigneePausedNotice` to state clearly that messages sent while
paused will not get a reply, distinguish budget pauses in the title, and
render a direct "Review budget" link to `${agentUrl(agent)}/budgets`.
- `ui/src/components/BudgetIncidentCard.tsx`: Clarified unpriced-usage
hard stops (`unpriced usage stop`, known spend vs. limit, and why
unpriced usage blocked work) and added a muted note beside "Keep paused"
explaining that dismissing the alert keeps the scope paused.
- `ui/src/components/PausedBudgetNotices.test.tsx`: Added focused jsdom
unit tests for `IssueAssigneePausedNotice` (budget pause link and manual
resume action) and `BudgetIncidentCard` (unpriced-usage hard-stop copy).
-
`ui/storybook/stories/budgets-costs/paused-agent-chat-notice.stories.tsx`:
Added production-component Storybook stories (`BudgetPausedInChat`,
`BudgetPausedWithUnpricedIncident`, `ManuallyPausedInChat`) with
interaction tests.
## Verification
- `pnpm vitest run server/src/services/anthropic-pricing.test.ts
ui/src/components/PausedBudgetNotices.test.tsx`: 2 test files, 30 tests
passed.
- `pnpm --filter @paperclipai/server typecheck`: passed.
- `pnpm --filter @paperclipai/ui typecheck` (including `node
../scripts/storybook-catalog.mjs`): passed.
- Verified all three new Storybook stories interactively in a browser
against local Storybook (`http://localhost:6006`) with zero runtime
errors and passing Storybook play assertions.
- `pnpm verify` exited 2 due to pre-existing untracked local files;
relying on required CI for full-repo coverage.
## Risks
- Low risk. Existing rate cards for `claude-sonnet-5` and
`claude-opus-5-5` keep their exact rates and versions. Family-maximum
fallbacks are intentionally conservative upper bounds and are labeled in
`pricingProvenance.evidence` as estimates rather than invoices.
- Existing already-settled `unpriced` cost events in databases are not
retroactively rewritten; this prevents new runs on shipped or future
Claude-family models from settling as unpriced.
## Model Used
- Google Gemini (Gemini 4 Neon Medium via Antigravity), with file
editing, terminal execution, browser verification, and web search tools.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
|
||
|
|
7838a12f5c |
fix(runner): upgrade Pi to 1.7.0 for the undici and minimatch security fixes (#23430)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The experimental Paperclip Runner runs Pi from a pinned, hash-verified distribution. > - That distribution pins Pi 1.0.0, which installs undici 8.10.2. > - undici 8.12.4 fixes six advisories, including GHSA-mqg3-3v4r-cm32 (high). > - Dependabot cannot do this upgrade. The pins feed `PI_DISTRIBUTION_PINS`, the closure pins and the ACPX `commandDigest`, so a Dependabot change fails CI (#22711, #18998). > - This pull request upgrades Pi to 1.7.0 by hand under `rules/acpx-profile-identity.mdc`. > - The benefit is a Pi runtime with the undici security fixes and an unchanged trust model. ## Linked Issues or Issue Description Supersedes #22711. Supersedes #18998. **What is the problem?** The Runner Pi distribution installs undici 8.10.2. undici 8.12.4 fixes GHSA-mqg3-3v4r-cm32, GHSA-7xg3-fphp-28hg, GHSA-5rm8-gv32-r954, GHSA-9v6h-8rgp-m69f, GHSA-3g9m-rv3r-w5w2 and GHSA-r4pc-4jcp-7pqc. **Why can Dependabot not fix it?** `.github/dependabot.yml` excludes `pi-distribution` on purpose. The lock, the closure pins and the profile digest must change together. **What is the fix?** Upgrade `@earendil-works/pi-coding-agent` from 1.0.0 to 1.7.0, which pins undici 8.12.4. ## What Changed - Pin `@earendil-works/pi-coding-agent` 1.7.0. Regenerate `package-lock.json` with the pinned Node 24.21.0 and its npm 11.19.0. The lock now has 126 packages and no os/cpu-specific packages. - Pi 1.6.0 and later do not ship `npm-shrinkwrap.json`. Pi pins `brace-expansion` 5.0.12 itself. So: - Remove `patches/brace-expansion@5.0.9.patch` and its setup and build plumbing. - Replace the shrinkwrap check in `verifyLockedPiPackageGraph`. Each dependency that Pi declares must install at exactly that version. Each `undici` and `brace-expansion` copy in the lock must be the reviewed release (`PI_DISTRIBUTION_PINS.undici` 8.12.4, `braceExpansion` 5.0.12). - Pi 1.7.0 (the newest Pi) pins minimatch 11.0.3. That version has GHSA-cf2h-pxjq-68xw (high), GHSA-hqmv-qgp3-jx75 and GHSA-c859-jr93-m5j4. Add an npm override to minimatch 11.0.8, the first fixed release. `PI_SECURITY_OVERRIDES` lets the verifier accept only this override, and only while Pi pins 11.0.3. A later Pi pin change fails closed and forces a new review. - Update the three `PI_DISTRIBUTION_CLOSURE_SHA256` pins. Then regenerate the ACPX profiles (TypeScript and Rust) with `generate:acpx-profiles`. - Keep profile version 37. The `commandDigest` changes with the upstream release, so saved Pi sessions start fresh. This follows the rule. - Update the version checks in `pi-installation.ts`, the Rust fixtures (`PI_ACPX_DIGEST`), the installation-integrity fixtures (the 1.0.0 digest is now the refused prior digest), the tests, the e2e qualification ID (`pi:0.0.33:1.7.0:openrouter`) and its suite-definition hashes, and `runner-pi-capabilities.md`. ## Verification - `node scripts/materialize-pi-distribution.mjs /tmp/out` passes on linux-x64. It uses the official pinned Node archive and verifies all 126 locked packages and the new closure pin. - Darwin closure pins: the lock has no platform-specific packages. So each darwin closure is the linux-x64 closure with that target's pinned Node executable. I checked this method first: it reproduces all three Pi 1.0.0 pins exactly from a linux-x64 build of master. - `PAPERCLIP_TEST_PI_RUNTIME_ROOT=<materialized runtime> node --test test/pi-native-package-contract.test.mjs`: 15/15 pass. The test runs real Pi 1.7.0 RPC through the owned ACP/MCP bridge (hello, interleaved tools, provider errors, thinking modes, warm recovery, pending cancel, path admission, aliased MCP tools). - `node --test` for the materialize, provision, build-inputs and attestation scripts: 39/39 pass. - Vitest: `pi-installation`, `pi-provision`, `native-execution`: 132 pass, 1 skipped. `tests/runner-e2e/pi-controls-evidence.test.ts`: 72/72 pass. - `generate-acpx-profiles.mjs --check` passes. - Static review against 1.0.0: `dist/core/tools/path-utils.js` is byte-identical, the tool `path` schemas are unchanged, and the extension events that we use still exist. Unknown tools still fail closed. - Not run locally: Rust tests (no cargo here) and paid live-model qualification. CI covers Rust. Pi stays a candidate profile. ## Risks - Saved Pi Runner sessions start fresh after deploy because the `commandDigest` changes. This is the expected result of an upstream upgrade. - Pi 1.0 → 1.7 has upstream behavior changes (for example, the Azure provider rename to `azure`, and new default models). The Paperclip Pi bindings do not use `azure-openai-responses`. - A darwin closure pin can be wrong only if npm installs different bytes on macOS for a platform-neutral graph. The macOS build checks the pin and fails closed. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution, in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
0960dd464d |
perf(chat): eliminate activity_log seq scans, chat load waterfalls, and transcript storms (#23750)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Persistent agent chat pages (`/:companyPrefix/chats/:agentRef`) are a primary surface for collaborating with an agent across many tasks and turns. > - Opening an active agent chat page was slow: multiple endpoints scanned the full `activity_log` table, the page bypassed the single-request chat bootstrap, the native transcript hook aborted and retried historical run fetches across multiple waves, and pending task questions triggered N+1 per-task interaction requests. > - These bottlenecks blocked the initial chat reveal for several seconds and saturated server and database capacity during page open. > - This pull request eliminates the `activity_log` sequential scans with index-backed predicates (no schema migrations), batches pending-question interaction hydration, defers completed saved-reply run transcripts in persistent agent chats, stabilizes per-run transcript lifecycles, and enables parallel chat resolution and chat-bootstrap adoption on agent chat pages. > - The benefit is dramatically faster agent chat page loads with far fewer HTTP requests, zero `activity_log` full-table scans on hot chat paths, and no schema migrations. ## Linked Issues or Issue Description Related: #18461, #20355, #21650, #21671. **What happened?** Opening a persistent agent chat page with accumulated history and active tasks took multiple seconds before the conversation became visible and triggered dozens of concurrent API requests: 1. `decisionHistoryService.list` (`handledForBySource`) scanned all rows of `activity_log` because `(details ->> 'handledForUserId') IS NOT NULL` alone did not bind the second key of `activity_log_company_handled_for_created_idx`, and `decisions` used `NOT IN (SELECT id FROM issues ...)` which planned a full-company privacy subquery even when no settled decisions existed. 2. `activityService.forIssue` scanned all rows of `activity_log` because the `project.created` and `company.skill_created` branches omitted `entity_type`, preventing index scans. 3. `attentionService.taskQuestions` executed steady-state write transactions in `decision-retention` and unnecessary plan-document reads on read paths, and `CoordinatorChatPendingQuestion` mounted an `AttentionInteractionResolver` per question that fired one `GET /api/issues/:taskId/interactions` request per pending question. 4. `TaskChatThread` disabled saved-reply transcript deferral in `conversationMode`, fetching `/events` (and legacy `/log` fallbacks) for every historical completed run in the comment window, while `useNativeRunTranscripts` used a single shared `AbortController` that aborted and restarted in-flight sibling reads whenever run membership or live-stream state changed. 5. `AgentChat` waited serially for the agent roster and session before fetching the chat by `:agentRef`, `IssueDetail` skipped `startIssueChatBootstrap` for conversations, and the HTML preload plugin omitted the `AgentChat` chunk on `/chats/:ref` hard loads. **Expected behavior** Opening an agent chat page resolves the conversation and its first-frame data in parallel via `chat-bootstrap`, avoids sequential scans on `activity_log`, avoids fetching completed run transcripts when a saved reply is already visible, avoids aborting sibling in-flight transcript reads, and renders pending task questions without per-task N+1 interaction requests. **Steps to reproduce** 1. Create a company with a persistent agent chat that has 20+ historical replies from completed native runs, several hundred tasks assigned to that agent, pending `ask_user_questions` interactions across multiple tasks, and a large `activity_log` table. 2. Open `/:companyPrefix/chats/:agentRef` directly or from the sidebar and inspect the network waterfall and PostgreSQL query plans for `/activity`, `/decision-receipts`, `/pending-questions`, and `/heartbeat-runs/:id/events`. 3. Observe full-table `Seq Scan` plans on `activity_log`, bypassed `chat-bootstrap`, repeated aborted `/events` requests, and N+1 `/issues/:taskId/interactions` calls. **Paperclip version or commit** Reproduced on `ca21075837` (rebased onto `a3719da3ca`, final head `2995820afe`). ## What Changed - **Eliminate `activity_log` sequential scans (zero migrations)**: - `server/src/services/activity.ts`, `server/src/routes/activity.ts`, `server/src/routes/issues.ts`: Scope `forIssue` secondary branches by their canonical `entity_type` (`project` for `project.created`, `company_skill` for `company.skill_created`) and accept `companyId` from routes so PostgreSQL uses `BitmapOr` index scans instead of a full-table `Seq Scan`. - `server/src/services/decision-history.ts`: Add `(details ->> 'handledForUserId') >= ''` alongside `IS NOT NULL` in `handledForBySource` so PostgreSQL binds the partial index `activity_log_company_handled_for_created_idx`; replace `decision_target_issues.issue_id NOT IN (...)` with correlated `NOT EXISTS (...)`; add a `LIMIT 1` index probe before planning the full `decisions` privacy query when no settled decisions exist. - `server/src/services/conversation-decision-receipts.ts`, `server/src/routes/issues.ts`: Reuse the route's already-authorized conversation record instead of re-querying `source()`. - **Batch pending-question hydration and avoid steady-state retention writes**: - `packages/shared/src/types/attention.ts`, `server/src/services/issue-thread-interactions.ts`, `server/src/services/attention.ts`: Add optional `interaction?: IssueThreadInteraction | null` on `AttentionItem`, batch-hydrate interactions in `issueThreadInteractionService.listByIds` (grouping by `issueId` for acceptance readiness and skipping only `z.ZodError` legacy payloads), restrict `planDocumentMap` to actual plan confirmation interactions, and parallelize `decisionQueueItems` and `decisionTriage` reads in `enrichAttentionItems`. - `server/src/services/decision-retention.ts`: Add a read-only fast path in `syncItems` so steady-state reads skip opening a write transaction when retention rows are already current, while still syncing and bumping versions whenever `activityAt` changes. - `ui/src/components/AttentionInteractionResolver.tsx`, `ui/src/components/coordinator/CoordinatorChatPendingQuestions.tsx`: Accept optional `initialInteraction` so inline pending-question cards render immediately without N+1 `GET /issues/:taskId/interactions` requests while still honoring cache updates after mutations. - **Remove agent chat load waterfalls and transcript abort storms**: - `ui/src/components/TaskChatThread.tsx`, `ui/src/lib/run-answer-visibility.ts`: Defer completed `succeeded` run transcripts that already have a visible saved reply in `conversationMode` while preserving immediate hydration for live, failed, yielded, pending-interaction, and unanswered runs; precompute visible-answer lookups in linear time (`O(comments + runs)`) instead of quadratic scans. - `ui/src/components/transcript/useNativeRunTranscripts.ts`: Manage `AbortController`s and poll timers per run instead of one shared controller so adding sibling runs or transitioning stream health never aborts in-flight reads or refetches already-hydrated terminal runs; clear aborted in-flight tracking cleanly so expanding compact history refetches immediately. - `ui/src/pages/AgentChat.tsx`, `ui/src/pages/IssueDetail.tsx`, `ui/src/lib/vite-issue-detail-preload.ts`: Start `agentChatsApi.get` by `:agentRef` in parallel with roster/session reads on cold loads, enable `startIssueChatBootstrap` for conversations with an existing issue ID, and preload the `AgentChat` chunk alongside `IssueDetail` on `/chats/:ref` hard loads. - **Tests & SDK pin**: - Added/updated tests in `server/src/__tests__/activity-service.test.ts`, `server/src/__tests__/activity-routes.test.ts`, `server/src/__tests__/decision-history.test.ts`, `server/src/__tests__/issue-thread-interaction-routes.test.ts`, `ui/src/components/AttentionInteractionResolver.initial.test.tsx`, `ui/src/components/TaskChatThread.test.tsx`, `ui/src/components/transcript/useNativeRunTranscripts.test.tsx`, `ui/src/components/transcript/useNativeRunTranscripts.streaming.test.tsx`, and `ui/src/lib/vite-issue-detail-preload.test.ts`. - Updated `tests/runner-e2e/source-sdk-public-inputs.json` for `packages/shared/src/types/attention.ts`. ## Verification Local disposable PostgreSQL 18.1 benchmark (`200,000` `activity_log` rows, `455` tasks, `82` interactions, alternating baseline/treatment samples, `ANALYZE` run, positional `.values()` output equality verified on both empty and populated `handledForUserId` sets): | Caller/query | Before median | After median | Samples/spread | Complete output/contract check | Scope | | --- | --- | --- | --- | --- | --- | | `activityService.forIssue(50)` | `53.66 ms` (`50.78 ms` SQL exec, `11,147` buffers, `Seq Scan`) | `1.84 ms` (`0.31 ms` SQL exec, `23` buffers, `BitmapOr` index scans) | 7 alternating samples (before `48.03–62.79 ms`, after `1.34–3.18 ms`, `29.2x` speedup) | Pass (50 positional rows equal) | SQL | | `decisionHistory.handledForBySource` (40 ids, 0 rows) | `13.71 ms` (`11,193` buffers, `Seq Scan`) | `0.73 ms` (`2` buffers, `Bitmap Index Scan` on partial index) | 7 alternating samples (before `11.56–15.45 ms`, after `0.64–0.99 ms`, `18.8x` speedup) | Pass (empty + populated non-empty positional rows equal) | SQL | | `decisionHistory.handledForBySource` (40 ids, 1 matching row) | `40.35 ms` SQL exec (`11,193` buffers, `Seq Scan`) | `0.04 ms` SQL exec (`2` buffers, `Bitmap Index Scan` on partial index) | `EXPLAIN (ANALYZE, BUFFERS)` | Pass (1 positional row equal) | SQL | CI and reviews on final head `2995820afe`: - **GitHub Actions CI (`ci / verify`)**: **PASS** (all 86 check runs completed with 0 failures; `mergeStateStatus: CLEAN`). - **Greptile Review**: **5/5** (`SUCCESS`, 0 unresolved findings). - **Ponytail Paperclip Review**: **5/5** ("No actionable defects found in the reviewed paths. Verdict: Ship."). - **Feynman Nuclear Review**: **4/5** ("no confirmed defect in the new commits"). Tests and builds also verified locally: - `pnpm --filter @paperclipai/shared build` — pass - `cd server && node scripts/typecheck-layers.mjs` — pass (all 7 layers) - `pnpm --filter @paperclipai/ui typecheck` & `pnpm --filter @paperclipai/ui build` — pass - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/approval-queue-seeding-work.test.ts src/__tests__/decision-history.test.ts` — pass (28/28 and 14/14 on real embedded PostgreSQL) - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/activity-service.test.ts src/__tests__/openapi-routes.test.ts` — pass - Focused UI suites (`TaskChatThread.test.tsx`, `useNativeRunTranscripts.test.tsx`, `useNativeRunTranscripts.streaming.test.tsx`, `AttentionInteractionResolver.initial.test.tsx`, `AttentionInteractionResolver.replace.test.ts`, `IssueDetail.agentChatPanel.test.tsx`, `vite-issue-detail-preload.test.ts`) — pass ## Risks - **No schema migrations**: All SQL improvements use existing indexes. - **Completed chat run transcripts**: Persistent agent chats now defer completed `succeeded` runs that already have a visible saved reply, matching compact task behavior. Live, failed, yielded, pending-interaction, placeholder, progress-only, and hash-targeted runs still hydrate immediately. - **Inline interaction hydration**: `AttentionInteractionResolver` uses `initialInteraction` when provided and valid, skipping the mount-time `listInteractions` read; mutations and live updates continue to update/invalidate `queryKeys.issues.interactions(issueId)` and `["issues", "pending-questions"]`. Unparseable legacy interaction rows (`z.ZodError`) are omitted from the batch map and fall back cleanly to the per-issue read. - **Synthetic local proof vs production**: Local PostgreSQL benchmarks prove query plan and buffer reductions on synthetic data (`200k` rows); deployed latency improvements depend on production dataset size and cache warmth. ## Model Used Google Antigravity (Gemini) with tool use, terminal execution, and local embedded PostgreSQL profiling. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
cfe5042378 |
fix(opencode): fix API key env/secret resolution and support Antigravity connector (#23387)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agent setup, environment testing, and managed AI connections pass
provider API keys into the OpenCode adapter and Paperclip Runner
> - OpenCode setup failed with `Secret not found` when a user supplied a
direct Gemini API key alongside a stale or auto-selected secret binding,
and the OpenCode runtime reported `GOOGLE_GENERATIVE_AI_API_KEY` missing
because Paperclip only passed `GEMINI_API_KEY` and limited OpenCode to
OpenRouter credentials
> - Users need reliable direct provider API keys and Google/Antigravity
API-key connectors across legacy OpenCode, native Paperclip Runner, and
Plugin Runner environments without exposing raw keys to child tool
shells
> - This pull request strips probe-overridden secret references
(including symmetric Google key aliases) before secret resolution,
prioritizes pasted API keys in setup, routes direct OpenCode provider
credentials through a runner-owned loopback proxy, and enables API-key
AI connections (including the Google / Antigravity connector) for
`opencode_local`
> - The benefit is that OpenCode agents test and run reliably with
direct provider keys or connected Google/Antigravity API keys without
false `Secret not found`, missing `GOOGLE_GENERATIVE_AI_API_KEY` errors,
or raw key leaks into child environments
## Linked Issues or Issue Description
- Fixes: #23359
- Refs #23370 (related community fix by @dev-787 for the initial Gemini
API key issue)
## What Changed
- **Server test-environment secret stripping and inheritance
(`server/src/routes/agents.ts`)**: Strip any credential key supplied in
`testCredentials` (including the symmetric `GEMINI_API_KEY` /
`GOOGLE_GENERATIVE_AI_API_KEY` pair and `hermes_gateway` `apiKey`) from
both `adapterConfig` and resolved environment `envVars` before secret
persistence normalization and runtime resolution. Scope `opencode_local`
inheritable credential groups from `@paperclipai/shared`
(`OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS`), skip inheritance when the
child supplies any OpenCode credential, and isolate multi-provider
parents to one matching provider group.
- **UI setup credential precedence (`ui/src/lib/provider-credential.ts`,
`ui/src/components/new-agent/NewAgentSetup.tsx`)**: Prefer an explicitly
entered raw API key over an auto-selected organization or personal
secret, and clear stale provider secret bindings and Google alias keys
when switching credentials or providers.
- **OpenCode direct provider keys and Gemini aliasing
(`packages/adapters/opencode-local/`, `packages/adapter-utils/`)**:
Mirror non-empty `GEMINI_API_KEY` into `GOOGLE_GENERATIVE_AI_API_KEY`
during OpenCode runtime config preparation and model discovery while
preserving blank managed isolation. Register `google`, `xai`, `groq`,
and `opencode` API key names in `api-billing-type`.
- **Runner-owned loopback credential proxy and allowlist parity
(`packages/paperclip-runner/`, `packages/plugins/sdk/`,
`packages/shared/`)**: Export canonical
`OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS` and
`OPENCODE_CREDENTIAL_ENV_KEYS` from `@paperclipai/shared`. Route direct
OpenCode provider API keys (`google`, `anthropic`, `openai`, `xai`,
`groq`, `opencode`) through a runner-owned loopback proxy
(`packages/paperclip-runner/src/drivers/opencode/provider-proxy.ts`)
with per-session bearer tokens, model-pinned endpoint allowlists, native
upstream auth header injection, request secret redaction, and redirect
refusal so raw keys never enter `opencode serve` child environments or
`opencode.json`. Allow direct provider keys across TypeScript, Rust, and
Plugin SDK allowlists, reserve `GOOGLE_API_KEY` and `GROK_API_KEY` in
TS/Rust configured-environment projections, strip ambient provider keys
(including `OPENROUTER_API_KEY`) from sanitized OpenCode runner
environments unless explicitly supplied, and redact provider keys in
output custody.
- **Antigravity / multi-provider API-key AI connections for OpenCode
(`packages/shared/`, `server/src/services/`,
`ui/src/components/ai-connections/`)**: Enable `api_key` AI connections
for `google` (Antigravity catalog slug), `anthropic`, `openai`, and
`xai` on `opencode_local` (keeping OAuth `subscription` methods
excluded), enforce provider-to-model prefix compatibility, mirror
`GEMINI_API_KEY` to `GOOGLE_GENERATIVE_AI_API_KEY` in
`prepareManagedAiRuntime`, isolate project config with
`OPENCODE_DISABLE_PROJECT_CONFIG=true`, and scope child-auth override
detection in `agent-ai-connection-default.ts` to non-empty OpenCode
credentials (supporting plain values, `secret_ref.secretId`, and
`user_secret_ref.key`).
- **Tests and pinned input registry**: Added unit, route, cross-layer
allowlist parity, and pinned `opencode@1.18.34` `bash`-tool credential
isolation tests across `adapter-utils`, `adapter-opencode-local`,
`paperclip-runner`, `server`, and `ui`, and synchronized
`tests/runner-e2e/source-sdk-public-inputs.json`.
## Verification
- `@paperclipai/adapter-utils`: `src/api-billing-type.test.ts` (17/17
tests), `typecheck`, `build` — passed
- `@paperclipai/adapter-opencode-local`:
`src/server/runtime-config.test.ts`, `src/server/models.test.ts`,
`typecheck`, `build` — passed
- `@paperclipai/shared`: full suite (123/123 files, 1426/1426 tests),
`typecheck`, `build` — passed
- `@paperclipai/paperclip-runner`: `typecheck:typescript`,
`build:typescript`, `check:package-boundaries`,
`opencode-server-driver.test.ts` (101/101 including pinned
`opencode@1.18.34` `bash`-tool test), `output-custody.test.ts` (13/13),
`configured-environment.test.ts` (35/35),
`antigravity-credentials.test.ts` (11/11), and
`durable-prp-control-plane.test.ts` — passed
- `@paperclipai/server`: `typecheck` and targeted suites
(`ai-connections.test.ts` 170/170, `agent-hire-ai-connections.test.ts`
84/84, `agent-test-environment-routes.test.ts` 72/72,
`agent-hire-auth-inheritance-routes.test.ts` 29/29,
`plugin-runner-credentials.test.ts` 43/43,
`plugin-runner-credential-names.test.ts` 6/6 cross-layer TS/Rust parity,
`opencode-local-adapter-environment.test.ts` 4/4,
`ai-auth-failure.test.ts` 32/32, `ai-provider-routing.test.ts` 21/21,
`antigravity-runner-credentials.test.ts`) — passed
- `@paperclipai/ui`: `typecheck`, `provider-credential.test.ts`,
`AiConnectionSelect.test.tsx` (20/20 tests) — passed
- `@paperclipai/plugin-sdk`: `build`, `environment-tasks.test.ts`,
`environment-task-release-resume.test.ts` (104/104) — passed on
`03dc341957`
- `@paperclipai/paperclip-runner`: `provider-traffic.test.ts` &
`provider-traffic-proxy.test.ts` alongside OpenCode/Antigravity/custody
suites (169/169) — passed on `03dc341957`
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
|
||
|
|
e2e2265085 |
feat(plugins): tell a task side panel plugin when the person closes its tab (#23747)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plugins can show an agent detail tab in the task side panel, next to a task > - The board mounts only the active side panel tab, and it unmounts a plugin view in the same way when the person switches tabs and when the person closes the tab > - Thus a plugin that shows a live view in a task panel tab cannot know when the person is done with it, and it cannot release the view > - A component callback does not solve this, because a background tab is not mounted when the person clicks its close control > - This pull request adds an optional declarative `taskSidePanel.closePath`, symmetric with the existing `availabilityPath` > - The benefit is that a plugin can release a live view when the person closes its tab, and plugins that do not declare the path see no change ## Linked Issues or Issue Description Refs #17796 (added plugin panels in task side panels). Related: #23609. **Subsystem affected** Plugin UI slots: `detailTab` slots with a `taskSidePanel` declaration, and the task side panel in the board UI. **Problem or motivation** A plugin panel in the task side panel gets no signal when the person closes its tab. The board unmounts the view on a close and on a tab switch in the same way, so the plugin cannot tell the two apart. A plugin that holds a live view for the panel cannot release it when the person closes the tab. **Proposed solution** Add an optional `closePath` to `taskSidePanel`. When the person closes the tab, the board sends a fire-and-forget POST to that plugin route, with the same agent, run and task as the availability request. The manifest must declare the path as a board POST route scoped to agent `:entityId`. **Alternatives considered** A callback on the mounted plugin component. It does not work for a background tab, because only the active tab is mounted. **Roadmap alignment** This extends the plugin system. It adds no product-specific behaviour to the control plane. ## What Changed - `taskSidePanel` accepts an optional `closePath`. It uses the same path rules as `availabilityPath`: a plugin-relative path with one `:entityId` segment. - Manifest validation requires a declared `POST` API route at `closePath` with `auth: "board"`, no transport, and `companyResolution: { from: "agent", param: "entityId" }`. These are the same rules as the `GET` availability route. - When the person closes a plugin panel tab in the task side panel, the board sends `POST /plugins/<pluginId>/api<closePath>?runId=<run>&issueId=<task>`, with `:entityId` replaced by the panel's agent. The board leaves out `runId` when the task has no active run. This applies to the active tab and to background tabs. - The board does not wait for the request. A failed request does not block the close, and the board logs a console warning. - The board sends no request on a tab switch, when the panel unmounts, when the person leaves the task, or when the board removes a panel that is no longer available. - A slot without `closePath` behaves as before. - The plugin SDK README and the plugin spec document the new field. A plugin declares: ```ts ui: { slots: [{ type: "detailTab", id: "screen", displayName: "Live view", exportName: "LiveView", entityTypes: ["agent"], taskSidePanel: { availabilityPath: "/agents/:entityId/view/availability", closePath: "/agents/:entityId/view/close", }, }] }, apiRoutes: [ { routeKey: "view.availability", method: "GET", path: "/agents/:entityId/view/availability", auth: "board", capability: "api.routes.register", companyResolution: { from: "agent", param: "entityId" } }, { routeKey: "view.close", method: "POST", path: "/agents/:entityId/view/close", auth: "board", capability: "api.routes.register", companyResolution: { from: "agent", param: "entityId" } }, ], ``` ## Verification - `packages/shared`: `npx vitest run src/validators/plugin.test.ts` passes (85 tests). New cases accept a valid close route and a close path equal to the availability path. They reject unsafe paths, a missing POST route, the wrong method (`GET`, `DELETE`), non-board auth, a non-agent company resolution, and the wrong agent parameter. - `ui`: `npx vitest run src/components/task-side-panel/TaskSidePanel.pluginClose.test.tsx` passes (6 tests). The tests render the task side panel and check that a close of the active tab and of a background tab sends exactly one POST to the correct URL. They also check that a tab switch, an unmount, a removal of an unavailable panel, and a slot without `closePath` send nothing, and that an idle task omits `runId` and a failed request still closes the tab. - Red check: with the board call removed, the three close tests fail. - `ui`: `npx vitest run src/hooks/useTaskPluginPanels.test.tsx` passes (56 tests). - `tsc --noEmit` passes for `packages/shared` and for `ui` source files. ## Risks - Low risk. The field is optional, and slots without it keep their current behaviour. - A plugin receives a close POST only for a person's close of the tab. The plugin must treat the request as a hint, because the request can fail or arrive late. - Existing manifests continue to validate. The availability route error message has the same text as before. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, run in Claude Code with tool use (file edits, shell, test runs) and extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a3719da3ca |
fix(ui): prioritize recent composer assignees (#23744)
## Thinking Path > - Paperclip helps people manage work with agents. > - People pick a recipient in the new-task and task reply composers. > - The picker puts people before agents. Frequently used recipients can be far down the list. > - The composer can use its saved assignee history to put recent recipients at the top. > - This change shows up to five recent choices, then puts the other agents before the other people. ## Linked Issues or Issue Description **What existing behavior does this improve?** The assignee list in the task composer. **Subsystem affected** UI board. **Current behavior** Open the assignee picker in a task composer. The list can show people before all agents. It has no top list of mixed agent and human selections. **Proposed behavior** Show the five most recent available choices first in newest-first order. Show the other agents, then the other people. Put No assignee at the end of the list and include it in search. **Reason and benefit** People can find recipients they use often and reach other agents sooner. Related composer UI changes are #15050 and #14250. ## What Changed - Read company-specific assignee history in the shared composer picker. - Record each explicit picker selection, including reselection of the current assignee. Reset run settings only when the assignee changes. - Keep the saved recent-agent fallback for older browser history. - Test recency order, the five-choice limit, company boundaries, search, reselection, and reopening with 268 choices in the new-task and reply composers. Bound option reads in each step. ## Verification - The new regression test failed on the old order and passed with the fix. - Ran the composer, run settings, assignee, and recent selection test files with Vitest. All 205 tests passed. - Ran `pnpm --filter @paperclipai/ui typecheck`. It passed. - Ran `pnpm test:e2e tests/e2e/new-task-picker-touch.spec.ts --workers=1`. All three Chromium tests passed. ## Risks Low risk. This changes the order of existing options. The history uses the browser's existing storage. The regression test checks that a missing assignee does not reduce the five-choice limit. ## Model Used OpenAI Codex, GPT-6, with shell and GitHub tooling. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
bca282e587 |
feat(recents): add tasks from manual routine runs to Recents (#23675)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The sidebar Recents list shows the tasks from a person's own recent activity > - A person can run a routine manually with "Run now", and the run creates a task > - That task does not show in Recents, and opening it does not keep it there, because Recents only admits tasks under the Mine participation rule. This also affects every routine, channel, and agent-created task that a person opens > - The Mine rule keeps these tasks out of Mine on purpose, so we must not change that rule > - This pull request adds a separate Recents eligibility flag. It also admits tasks that the viewer opened and tasks from manual routine runs that the viewer started. The UI records the new task in Recents when the run starts > - The benefit is that people can find the task they just started from the sidebar at once, and Mine stays unchanged ## Linked Issues or Issue Description **Is your feature request related to a problem? Please describe.** When I run a routine manually and it creates a task, the task is not in my Recents list. I must go to the routine or the task list to find it. **Describe the solution you'd like** When I run a routine manually and a task is created, add that task to my Recents list automatically, even if I did not open it. Also, a task that a routine creates does not show in Recents even after I open it. **Additional context** Mine must continue to keep routine tasks out by default, including routines that a person starts manually (see `doc/PRODUCT.md`). ## What Changed - `server/src/services/issue-summaries.ts`: navigation summaries return a new `isRecentEligibleForMe` flag. It is true when one of these conditions is true: - The viewer participates under the Mine rule. - The viewer opened the task. The check is the viewer's `issue_read_states` row, which is unique on company, issue, and user. - The viewer started the manual routine run that created the task. The check is a `routine_runs` row found through the indexed `linked_issue_id`, with `source = 'manual'` and the same ID as the issue's `originRunId`. The issue `createdByUserId` must be the viewer, with no creating agent. `isParticipantForMe`, Mine, and unread state do not change. - `packages/shared`: add `isRecentEligibleForMe` to `IssueSummary`. - `ui/src/hooks/useRecentTasks.ts`: Recents uses `isRecentEligibleForMe` (with a fallback to `isParticipantForMe` for older cached summaries) to show, keep, and prune entries. - `ui/src/lib/recent-tasks.ts`: add `recordStartedRoutineRunTask`. It puts the run's task at the top of Recents. The summary fetch then supplies the title and status and confirms eligibility. - New `useRecordRoutineRunInRecents` hook. All five "Run now" paths call it on success: Routines (both list variants), Routine detail, Execution workspace detail, and the Responsibility screen. - `tests/runner-e2e/source-sdk-public-inputs.json`: refresh the pin for `packages/shared/src/types/issue.ts`. - `doc/PRODUCT.md`: document the Recents behavior. ## Verification - `cd ui && npx vitest run src/hooks/useRecentTasks.test.tsx`: 29 passed. The new test "shows a task from the viewer's manual routine run at the top before it is opened" fails on the old hook (red) and passes with the change (green). Other new tests cover a run that the server does not confirm (for example, a coalesced run) and a repeat run for a task that is already in Recents. - `cd server && npx vitest run src/__tests__/issue-summaries-routes.test.ts` (embedded Postgres): 24 passed. One new test checks that a manual run by the viewer is Recents-eligible but not a Mine participant, and that runs by another person and scheduled runs are not eligible. Another new test checks that a routine task the viewer opened is Recents-eligible, and that a task opened only by another person is not. That test fails on the previous service code (red) and passes with the change (green). - `ui` typecheck: no errors in changed files. (Errors exist only in ungenerated Storybook feature-map indexes, which this change does not touch.) - The full `server` typecheck was killed by the local memory limit. CI covers it. - Manual check: run a routine with "Run now", then look at sidebar Recents. The new task shows at the top before you open it. Mine does not show it. ## Risks - Low risk. No schema change and no migration. - The summaries query adds two `EXISTS` subqueries per requested task. Both use indexes (the read-state unique index and `routine_runs_linked_issue_idx`). The request is bounded by `ISSUE_SUMMARIES_MAX_IDS`. - Behavior change: Recents now keeps tasks that the person opened, also when the task is automatic work. Old local Recents entries for automatic tasks that the person read can come back. - If a manual run coalesces into an existing task that the viewer did not start, the entry is pruned after the summary read. That task does not show in Recents. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use (shell, file edit, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [ ] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [ ] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3f882fc589 |
fix(native): stage task-description attachments for native agents (#23688)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - People often create a task with a screenshot in its description and
assign it to a native agent.
> - The native Runner stages wake-comment files into the agent
workspace, so the agent can open an image with its file reader.
> - Files attached to the task description have no comment, so the
Runner never staged them.
> - The agent then said that it could not see the screenshot, or it
guessed from the text.
> - This pull request stages the task's own files on every native wake.
> - The benefit is that an agent can see the screenshot that explains
the task.
## Linked Issues or Issue Description
**What happened?**
A user created a task with the description "This list should probably be
sorted alphabetically" and pasted a screenshot of the list. A Claude
agent on a native sandbox replied that it could not open the screenshot
and asked which list to sort. It found the attachment through the API,
but the run had no staged path and no tool that put the image in its
workspace. When the same image was attached to a comment, the agent
opened it at once.
**Expected behavior**
A native agent can inspect files that are attached to the task
description, the same as files attached to a wake comment.
**Steps to reproduce**
1. Create a task and paste an image into its description.
2. Assign the task to a native `paperclip_runner` agent.
3. Ask the agent what the image shows.
4. The prompt has no "Paperclip native attachment access" entry for the
image, and the agent cannot see it.
**Paperclip version or commit**
`master` at
|
||
|
|
23ca89e376 |
Link agent names in the chat sidebar to their overviews (#23650)
## Thinking Path > - Paperclip lets people manage agents. > - The chat sidebar lists agents with conversations. > - Each row opens a conversation. > - The agent name gives readers a natural place to open the agent overview. > - Separate links let users choose either destination with a mouse or keyboard. ## Linked Issues or Issue Description **Subsystem affected** Chat sidebar navigation. **Current behavior** Selecting an agent name opens the conversation. **Proposed behavior** Selecting the name opens that agent's overview. Selecting the avatar or role opens the chat. ## What Changed Added a company-scoped overview link on the name and kept a separate chat link across the row. ## Verification The sidebar compiled with esbuild. The diff whitespace check passed. To verify in the app, click the name, return to the list, then click the role. Check both links with Tab and Enter. ## Risks Users who previously clicked the name to open chat will now reach the overview. ## Model Used OpenAI Codex, GPT-6, with shell tools. ## Checklist - [ ] I have included a thinking path that traces from project context to this change - [ ] I have specified the model used (with version and capability details) - [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [ ] I have searched GitHub for duplicate or related PRs and linked them above - [ ] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [ ] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [ ] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [ ] I have run tests locally and they pass - [ ] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [ ] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
477323e4e8 |
fix(evals): attribute native saved-skill library reads (#23611)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product E2E tests check that agents use saved skills and save the
correct result.
> - The saved-skill test binds a native source read to an exact skill
version and run.
> - The native library tool can return the complete source through
`paperclip_load_skill`.
> - The test did not recognize this tool result, so it rejected a
successful read.
> - This pull request adds a closed check for that result and preserves
the independent output checks.
## Linked Issues or Issue Description
**What happened?**
The saved-skill journey rejected a successful native OpenCode library
read. Its receipt list was empty. The proxy reports `operation: unknown`
and `readOnly: false` for this tool. Retained event payloads can also
omit null targets.
**Expected behavior**
A complete source read must qualify when the saved skill, immutable
version, source bytes, admitted assignment and native call all agree.
Failed, partial, copied or foreign results must fail.
**Steps to reproduce**
Run the new library-loader test against the old parser. The valid
start/progress/completion case returns no receipt. The test expects one
receipt. The new retained-event case also fails before support for
omitted null targets.
Related public repairs: #22813 fixes assigned-skill name resolution.
[Cloud #1135](https://github.com/paperclipai/paperclip-cloud/pull/1135)
reports ordinary saved-skill assignment. Neither adds this evidence
path.
## What Changed
- Carry the saved skill ID with the selected key and version.
- Accept the native OpenCode library result only with matching IDs, key,
version, full source, SHA-256, byte count and complete single-file
inventory.
- Require the actual run, runner, native session, turn, item and one
ordered start/completion pair. Allow progress events between them. Allow
absent or null targets. Reject a supplied path.
- Share native run admission across the library, OpenCode loader and
Codex paths. Share the two OpenCode loaders' ordered call checks.
- Preserve literal numeric prefixes in verified source text. Remove
display line numbers only from file-reader output.
- Add negative cases and full-flow cases for the source read and
independent output checks. Document the accepted evidence.
## Verification
- Red: the valid library read returned an empty receipt list against the
old parser.
- Red: the retained event shape with omitted null targets failed before
that case was supported.
- Red: six new library and assigned-source cases with literal `1: `,
`2|` and `3→` prefixes fail before the review fix. Native and provider
skill-loader cases also cover these prefixes.
- Green: five focused saved-skill test files pass, with 279 tests.
- Replay of retained private events: the old receipt list is empty; the
fixed parser returns one receipt for the original completed event.
Private data stays out of this PR.
- `pnpm test:e2e:runner:typecheck` passed for the final files. The test
fixture uses mutable row types for its negative cases.
- `pnpm verify` could not select tests because the managed Git storage
guard rejected `git ls-files`. The focused tests ran directly.
- [Required
CI](https://github.com/paperclipai/paperclip/actions/runs/47113067897)
passes on
|
||
|
|
8379dedd93 |
Pin Plugins by default in workspace navigation (#23578)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - People browse available integrations on the Plugins page. > - A fresh Coordinator sidebar puts that page inside More. > - People who look in Settings can miss it. > - This pull request pins Plugins until a person chooses their own layout. ## Linked Issues or Issue Description **What existing behavior does this improve?** Finding the Plugins catalog on a first visit to the Coordinator workspace. **Current behavior** Open a workspace in a fresh browser profile. The sidebar shows Inbox followed by More. Open More to find Plugins. **Proposed behavior** Show Plugins below Inbox on the first visit. Honor saved pins and their order, including an empty list. Related discussion about navigation for individual plugin pages: #21807. ## What Changed - Use the Plugins route as the default when the signed-in user has no saved pin list in this browser. - Add a browser regression for unpinning and re-pinning across reloads. Update the AgentMail browser journey to use the visible Plugins link. - Document the default and how to change it. ## Verification - `pnpm exec vitest run ui/src/hooks/usePinnedNavigation.test.tsx` passed. - `pnpm exec playwright test -c tests/e2e/playwright.config.ts tests/e2e/plugins-browse.spec.ts tests/e2e/agentmail.spec.ts` passed all four Chromium tests against the built app and a disposable database. - Compared the parent and feature commits in fresh Chromium sessions. Confirmed the pin control in More and the unpin and reorder controls on the pinned row. ## Risks An existing user who has never saved pins in this browser also receives the new default. A saved empty list keeps the sidebar empty of pins. ## Model Used OpenAI GPT-6 (Codex), with repository editing and Chromium test execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Scott Tong <scott@scotts-mbp-m5-max.local> |
||
|
|
b0f682b66b | Measure when users see a reply to their onboarding chat input (#23574) | ||
|
|
6e340a3f96 |
Verify onboarding models and explain provider failures (#23563)
Verify deployment-configured model preferences with the selected account. Preserve structured provider failures and show descriptive messages for known causes through the existing onboarding error display. Keep the existing failure buttons, account binding, and retry/sign-in behavior. Validation: UI typecheck, 38 focused tests, four browser journeys, all applicable CI checks, and Greptile 5/5 with no unresolved review comments. Co-Authored-By: Paperclip <noreply@paperclip.ing> |
||
|
|
cc2e1d9d43 |
Honor plugin task driver concurrency defaults on hire (#23535)
## Thinking Path > - Paperclip schedules work for agents. > - Each agent has a limit on simultaneous runs. > - A task driver can provide an execution environment with its own capacity. > - Previously the creation form sent the same limit for every driver. > - A driver can now declare the value Core saves when a new agent has no explicit limit. ## Linked Issues or Issue Description **Subsystem affected** Agent hiring and plugin environment drivers. **Current behavior** The create form, API, and import flow supply the global concurrency default before the task driver can provide one. **Proposed behavior** Let each task driver declare an optional per-agent concurrency default. Apply it once during hire and honor explicit agent limits. ## What Changed - Refreshed the three SDK source pins for the changed files. - Added the optional driver field `defaultMaxConcurrentRuns` with integer bounds from 1 through 50. - Applied it during hire using the resolved task environment. Saved the resolved runtime configuration in hire approvals. - Removed early defaults from the creation form, routes and new-agent imports. Preserved saved limits on export, including explicit values equal to the global default. Kept the current limit when importing an update with an omitted limit. ## Verification - [Full PR CI](https://github.com/paperclipai/paperclip/actions/runs/47000023360) passed on `83cce42b9a`. Server shard 16 passed on retry after a PostgreSQL connection reset on the first attempt. - `pnpm -r typecheck` passed. The SDK source pin check passed. `pnpm verify` selected broad CI coverage because the SDK input registry changed. - On rebased commit `83cce42b9a`, all 441 tests in six focused Vitest suites passed, including the MCP rollback test corrected in #23560. The SDK source pin check passed. ## Risks This affects new hires on drivers that opt in. Existing agents retain their saved configuration. Single-run provider limits still apply. An older client that explicitly sends the global default will keep that value. ## Model Used OpenAI GPT-6 via Codex. Used local source inspection, code editing, TypeScript and test execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
85b9586dd5 |
fix(cloud-trial): transfer OpenRouter starter proxy credentials to remote plugin Runners (#23559)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Cloud starter-inference onboarding (`free_inference_1`) runs the first OpenCode agent inside a remote plugin Runner environment using a per-run server proxy (`PAPERCLIP_OPENROUTER_PROXY_URL` and `PAPERCLIP_OPENROUTER_PROXY_TOKEN`) instead of exposing the raw OpenRouter key. > - On remote plugin Runner environments, OpenCode runs failed immediately with OpenRouter HTTP 401 (`No cookie auth credentials found`) because the proxy URL and token never reached the sandbox. > - Three boundaries stripped the proxy credentials: `preparePluginRunnerCredentials` returned early when `managedAiCredentialIdentity` was absent, `ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS.opencode` did not allow the proxy pair, and Rust `OPENCODE_PROVIDER_ENVIRONMENT_KEYS` in `codex_provider.rs` did not forward those keys. > - This pull request adds the `[PAPERCLIP_OPENROUTER_PROXY_URL, PAPERCLIP_OPENROUTER_PROXY_TOKEN]` pair across all three boundaries while keeping raw starter keys strictly server-side and failing closed on partial or ambiguous credentials. > - The benefit is that Cloud starter-inference OpenCode runs authenticate cleanly through the server proxy inside remote plugin Runner sandboxes. ## Linked Issues or Issue Description Refs #23401, #23427 **Summary** Transfer `PAPERCLIP_OPENROUTER_PROXY_URL` and `PAPERCLIP_OPENROUTER_PROXY_TOKEN` through the plugin Runner credential boundary and Rust `runner-core` allowlist for Cloud starter-inference OpenCode runs. **Steps to Reproduce** 1. Create a Cloud starter-inference (`free_inference_1`) workspace running OpenCode in a remote plugin Runner environment. 2. Send a message in the onboarding chat. 3. Observe `APIError` HTTP 401 (`No cookie auth credentials found`) from OpenRouter because the sandbox OpenCode proxy received neither `PAPERCLIP_OPENROUTER_PROXY_URL` nor `OPENROUTER_API_KEY`. **Expected Behavior** The remote plugin Runner receives `{ PAPERCLIP_OPENROUTER_PROXY_URL, PAPERCLIP_OPENROUTER_PROXY_TOKEN }` via the `opencode` `provider-env` credential channel, forwards them to OpenCode, and routes inference through the server-side starter proxy. ## What Changed - `packages/plugins/sdk/src/environment-tasks.ts`: Added `["PAPERCLIP_OPENROUTER_PROXY_URL", "PAPERCLIP_OPENROUTER_PROXY_TOKEN"]` to `ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS.opencode`. - `packages/paperclip-runner/runner/crates/runner-core/src/codex_provider.rs`: Added `"PAPERCLIP_OPENROUTER_PROXY_URL"` and `"PAPERCLIP_OPENROUTER_PROXY_TOKEN"` to `OPENCODE_PROVIDER_ENVIRONMENT_KEYS`. - `server/src/services/native-runtime/plugin-runner-credentials.ts`: Allowed `opencode` runs with both `PAPERCLIP_OPENROUTER_PROXY_URL` and `PAPERCLIP_OPENROUTER_PROXY_TOKEN` to transfer that `provider-env` credential when `identity` is absent (using `"cloud-trial"` as `accountIdentity`). - `server/src/services/native-runtime/plugin-runner-credentials.test.ts`: Added regression coverage for transferring the Cloud starter proxy pair without a managed AI connection identity and failing closed on partial or ambiguous combinations. - `tests/runner-e2e/source-sdk-public-inputs.json`: Updated reviewed SDK public inputs pin for `packages/plugins/sdk/src/environment-tasks.ts`. ## Verification - `pnpm --filter @paperclipai/plugin-sdk build` — passed. - `pnpm --filter @paperclipai/plugin-sdk exec vitest run tests/environment-tasks.test.ts tests/environment-task-release-resume.test.ts` — passed (104/104 tests). - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/plugin-runner-credentials.test.ts src/__tests__/plugin-runner-credential-names.test.ts` — passed (45/45 tests, verifying SDK allowlist, Runner TS allowlist, and Rust `codex_provider.rs` allowlist together). ## Risks - Low risk. Only the ephemeral per-run proxy URL and `pctrial_` token pair is allowed when both are present and non-empty; partial or mixed sets still fail closed in `environmentTaskCredentialSchema`, and raw OpenRouter keys never leave the server process. ## Model Used - Google Gemini (Antigravity agentic runtime, thinking mode with tool use and local code execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
9aaeae40bf |
test: prune orphaned test-support fixtures and helpers (#23360)
Co-Authored-By: Paperclip <Paperclip-Paperclip@users.noreply.github.com> |
||
|
|
86927d4933 |
feat(cloud-trial): enable fast responses by default with starter inference key (#23556)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Fast responses send a brief acknowledgement in the agent's voice while the full agent run starts. > - During Cloud starter-inference onboarding (`free_inference_1`), users start chatting immediately before connecting their own model provider, so no `company_fast_responses` connection exists yet. > - Without a default fast-response path, the first chat waits silently while the Runner starts up and thinks. > - This pull request enables fast responses by default while Cloud starter inference is active, routing acknowledgements through the server-held OpenRouter starter key with `$1` quota and `llmBlocked` gate enforcement. > - The benefit is immediate, responsive first-chat acknowledgements out of the box with a clean handoff once the user connects their own model provider. ## Linked Issues or Issue Description Refs #23401, #23427 **Summary** Enable fast-response acknowledgements by default for companies running on active Cloud starter inference (`free_inference_1`), using the existing server-side OpenRouter starter inference key. **Problem Statement** Fast responses currently require both the experimental `enableFastResponses` instance flag and an explicit shared API connection in `company_fast_responses`. New Cloud starter-inference workspaces have no saved API connection yet, so users do not get fast acknowledgements during their initial onboarding chat. **Proposed Solution** Fall back to the server-side Cloud starter inference OpenRouter key (`FAST_RESPONSE_DEFAULT_MODEL`, `openai/gpt-oss-120b`) when a company has no `company_fast_responses` row and is actively on trial-only inference without a blocked gate. Respect explicit company configuration/opt-out, enforce `responsibleUserId` and `issue:read` authorization, disallow sponsored webhooks on the starter key, mark the trial exhausted on HTTP 402/limit errors, and stop using the starter key automatically once the user connects their own model provider. ## What Changed - `server/src/services/cloud-trial-proxy.ts` & `server/src/services/cloud-trial-inference.ts`: Added `isCloudTrialFastResponseEligible` and `prepareCloudTrialFastResponse`. Keeps the raw OpenRouter key strictly in server process memory, enforces `isCompanyOnTrialOnlyInference`, the `$1` quota, and the `work_requires_model` / `exhausted` gates, wraps `fetch` to call `markExhausted` immediately on HTTP 402/limit responses, and probes usage on cleanup. - `server/src/services/fast-responses.ts`: Updated `enqueueFastResponse`, `fastResponseSourceCurrent`, `settings`, `availability`, `resolve`, `process`, and `history` to use Cloud starter inference by default when no `company_fast_responses` row exists and starter inference is active and unblocked. Explicit `company_fast_responses` rows (including opt-out `enabled: false`) always take precedence, and connecting a user model provider cleanly ends starter-key usage. - `packages/shared/src/fast-response.ts`: Added optional `usingCloudTrialDefault?: boolean` to `FastResponseSettings`. - `server/src/__tests__/fast-responses.test.ts`: Added regression tests covering starter-inference default fast responses (even when `enableFastResponses` is `false`), raw key non-leakage, `work_requires_model` gate blocking, HTTP 402 exhaustion, explicit opt-out, and clean handoff after connecting a user model provider. ## Verification - `pnpm --filter @paperclipai/shared typecheck` — passed (0 errors). - `pnpm --filter @paperclipai/server typecheck` — passed (0 errors). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/fast-responses.test.ts src/__tests__/cloud-trial-inference.test.ts` — passed (44/44 tests). ## Risks - Low risk. No database schema migration is required (`fast_response_requests.connection_id` and `grant_id` are already nullable). Self-hosted instances and `baseline` Cloud stacks are unaffected because `trialInferenceEnabled` is `false`. Companies that explicitly configure or disable `company_fast_responses` or connect their own AI provider never fall back to the starter key. ## Model Used - Google Gemini (Antigravity agentic runtime, thinking mode with tool use and local code execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
c655f38b72 |
Fix mobile scrolling inside chat and task cards (#23538)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - People review pending requests in agent chats and tasks. > - The request card sits above the composer in both views. > - On mobile, a long card can extend beyond the visible screen and cannot scroll. > - This pull request limits the card height to part of the visible viewport. > - People can scroll the card to read the details and reach its buttons. ## Linked Issues or Issue Description Fixes: #21626 ## What Changed - Give mobile composer takeover cards their own vertical scrolling and contain their scroll at the edges. - Size the mobile card against the visible chat viewport, including when the keyboard shrinks it. Keep the desktop limit and Inbox behavior unchanged. - Add browser regression tests for touch scrolling through a long confirmation card in Chat and Tasks. ## Verification - On master at `4db307d53c`, both regressions reproduced at 390 × 664 with emulated touch. The card extended past the viewport and a swipe did not move its scroll position. - Both patched Chromium regressions passed. A touch swipe scrolled the card, and subsequent swipes brought the approval button into view. - `pnpm --filter @paperclipai/ui typecheck` passed. - The isolated mobile preview also loaded the Inbox without changing it. Physical iPhone and keyboard testing were not performed. ## Risks - Low risk. The change is limited to the shared composer card layout and does not change how requests are accepted or stored. The composer is already above the 1,000-line threshold; changing its existing card classes keeps the fix local. - A long card uses part of the available height, so its contents scroll instead of pushing the controls offscreen. ## Model Used - OpenAI GPT, in Codex with repository and Chromium tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #123` / `Closes #123` / `Refs #123` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Scott Tong <1504818+scotttong@users.noreply.github.com> |
||
|
|
725a9e36b6 |
fix(connections): let a dedicated account serve every agent picked for its connection (#23431)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A GitHub connection can use "A dedicated account for an agent", for
example a bot account that an agent uses instead of the person who gives
instructions
> - The account lives on the grant of the agent that signed in. Core
gives one connection to one signed-in agent
> - A team often wants several agents to use the same bot account, or to
move a bot account to a new agent. Today each agent needs its own GitHub
sign-in as the bot
> - The permissions page also lets an owner pick more agents for the
connection, which looks like sharing but gives those agents nothing
> - Sharing a credential must stay under the owner's control: an install
of a connection needs only `agents:configure`, which agents and
operators have, so installs cannot be the share signal
> - This pull request adds an explicit share list for a dedicated
account. Only the person who connected the account, a company owner or
admin, or an instance admin can change it
> - The benefit is that a bot account can serve several agents without a
new sign-in, and no one else can attach the account to their agents
## Linked Issues or Issue Description
No public issue exists.
**What happened?**
A GitHub connection with a dedicated account was signed in for agent A.
The owner then picked agent B for the same connection on the permissions
page. The page showed "Used only by A" and also "2 agents selected" with
A and B. Agent B made no GitHub tool calls through the connection, and
its git work used the responsible person's GitHub account. There was no
way to let agent B use the bot account without a second GitHub sign-in
as the bot.
**Expected behavior**
The owner of a dedicated account can share it with chosen agents, and
those agents use it for managed git and the connection's tools. No one
else can share it.
**Steps to reproduce**
1. Add a GitHub connection with "A dedicated account for an agent" and
pick agent A.
2. On the connection's permissions page, pick agent B too.
3. Start a run for agent B that pushes with git. See that it uses the
responsible person's account, and that the page offers no way to share
the bot account.
**Paperclip version or commit**
`master` at
|
||
|
|
9092b0c667 |
Support live Antigravity credential writeback for both token stores (#23397)
## Thinking Path > - Paperclip manages the connections agents use to work. > - A run can outlive the Google refresh token that started it. > - Antigravity writes a rotated token to a private file. Its two runtimes use different paths and JSON layouts. > - The task already records which connection supplied its sign-in. > - Runner reports a rotation on PRP. Core saves it to that connection if the saved generation still matches. > - The next run can start with the rotated token. ## Linked Issues or Issue Description Refs #23395. Refs #23168. This PR targets `master` and includes the capability-based handler from #23395. Merging this PR lands the handler and Antigravity writeback together. **Current behavior** A managed Antigravity sign-in reaches the plugin as an environment credential. Core waits for task retirement to collect a refresh. **Proposed behavior** Seed a private auth-file. Observe refresh-token changes for the ordinary ACP server and the unified CLI. Use the existing credential update event to save them during execution. **Reason and benefit** A long-running task can keep its source connection current across successive rotations. ## What Changed - Dispatch PRP credential updates to the live writeback capability declared for the bound harness and execution target. - Send Antigravity subscriptions as auth-file credentials to environment task providers. Keep Gemini API keys and previously admitted environment credentials on their existing paths. - Watch the ACP token file and the unified CLI token file. Compare the refresh token, copy it to the bound file, and emit the existing secret-free event. - Bind writeback to the original grant, secret, session epoch, and credential generation. Save the next generation in the same transaction. ## Verification - Reproduced the failed final Google save hanging on the next session close. After commit `2b3e7897cd`, both focused cleanup suites passed (43 tests). The regression covers two overlapping close retries after the credential home is released and checks that the saved credential is removed only after persistence succeeds. - All 21 Rust observer tests passed on both builds. They cover interruption between the host file and event journal writes, a further rotation before restart, and a reconnect that supersedes the task. - On the legacy build, 422 Runner TypeScript tests passed. With the merged unified CLI on this branch, all 126 tests in the auth, credential staging, and runtime host suites passed. - The two plugin writeback database suites passed (39 tests). A refresh that starts before task stop cannot overwrite the final token after stop. - One run timed out in an unrelated process-retirement test. All three suites passed together on repeat. All OAuth documents in these tests are fixtures. No live Google sign-in was exercised. ## Risks - The agent and any process it starts are trusted not to substitute another account’s refresh token in the harness credential file. Core accepts the file’s refresh token for the original connection only while the grant, secret, session epoch, and expected credential generation still match. Substitution within that boundary is an accepted risk. [Review finding](https://github.com/paperclipai/paperclip/pull/23397#discussion_r4759261984) - Deploy with a plugin and Launcher that support the new auth-file provider. This branch includes the unified CLI from #23168 and still observes the legacy token format. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI GPT-6 in Codex, with local code execution and GitHub CLI. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
90bf446ad5 |
Guard release onboarding with scoped source E2E (#23432)
## Thinking Path > - Paperclip helps people manage work with AI agents. > - A release must pass onboarding before it reaches nightly. > - Onboarding changes already run source browser tests on PRs. > - The published release smoke used a separate scenario, which could drift from those tests. > - That drift blocked the December 1 nightly after onboarding succeeded. > - This PR fixes the stale welcome assertion and shares the scenario between release smoke and relevant PR E2E runs. ## Linked Issues or Issue Description Refs #23334 and #22259. **What happened?** [The December 1 nightly release](https://github.com/paperclipai/paperclip/actions/runs/46614290688) failed twice at `The onboarding chat must queue the lead's live welcome`. PR #23334 changed the welcome to a saved message and a question card. The greeting endpoint succeeded with `started: true` and `runId: null`, but the release test still required a model run. PR browser tests did not run those release expectations against the changed source. **Expected behavior** Onboarding PRs and changes to their shared dependencies must run the release scenario before merge. Known unrelated leaf-page changes and source-unit-test-only changes can omit the extra case. Shared and unfamiliar source paths must keep coverage. The scenario must check the lead's welcome and all three first-chat choices, with no model run before the user sends a choice or message. A mismatch must fail the required `ci / e2e` check. **Steps to reproduce** 1. Start the Docker onboarding harness with `PAPERCLIPAI_VERSION=2026.1130.0-canary.873300` and its provider verification mock. 2. Run the original release smoke test. 3. Observe successful login, setup, hire, and chat entry, followed by a timeout because the run list stays empty. **Paperclip version or commit** Failed release source: `7ce7d99f8af81ae90f97650ef7a8692a86c63a35`. Published package: `2026.1130.0-canary.873300`. **Deployment mode** The release test uses authenticated private Docker mode. The new PR test uses the existing disposable source E2E instance and provider verification fixture. ## What Changed - Check the saved welcome and the three visible choices, then require an empty agent run list. - Move the complete wizard, hire, and chat assertions into one shared onboarding scenario. Keep sign-in in the authenticated release wrapper. - Add the shared scenario to the normal PR E2E suite. Omit only this extra case when eligible source changes are confined to the Costs or Approvals UI page, source unit tests, and audited prose. Shared components, hooks, libraries, server code, mixed changes, and unfamiliar source paths keep it. The repository rules require `ci / e2e` before merge. - Pass the trusted CI change plan to shard selection and bind it to the checked-out commit. Reuse the existing lightweight source-diff eligibility gate for both Vitest and E2E, with the old Vitest export preserved. Full and shadow CI, broad or deleted inputs, invalid plans, and stale plans keep the case. No extra browser job or matrix is added. - Add release smoke files to the E2E and typecheck task inputs. Test that onboarding changes select E2E and that smoke-only changes select their two owners without forcing unrelated lanes. - Document the shared test command and the source and installation coverage. ## Verification The shared browser scenario is unchanged from `2044ada98e953504af68febe4c196f414d0bb1ae`. The selector review fix is based on master’s hosted-shard speed improvement. Selector and eligibility verification covers `236640e419d1177aafb64f3f7dd1ee49848ee707`. - Reproduced the original nightly timeout locally against the exact published canary. - The extracted release scenario passed against that canary in 22.1 seconds. - The new source E2E passed against PR source and the built UI in 32.3 seconds. - Restored the obsolete model-run assertion temporarily. The new source E2E failed with the same `Expected: > 0 / Received: 0` timeout. Restored the correct assertion. The final source confirmation passed in 31.7 seconds. - `node --test scripts/__tests__/e2e-shard.test.mjs .github/scripts/tests/ci-plan.test.mjs scripts/ci/test-selection-workflow.test.mjs`: all 52 tests passed after rebase. Coverage includes unrelated changes, relevant dependencies, rename paths, full/invalid/stale plans, exact CLI shard partitions, and both hosted shard policies. The unrelated-change and wiring tests failed before the filter was implemented. - Regression selection tests failed on `TaskChatComposer.tsx` and shadow mode before this review fix. They now keep the composer, new-agent runtime configuration, AI connection components, hooks, libraries, and mixed source changes. - The 3 existing source-diff eligibility contract tests passed after extraction into the shared module. - `actionlint .github/workflows/pr-trusted.yml` passed. - `node --test scripts/ci/test-selection-inputs.test.mjs`: 4 tests passed. - The Playwright program and focused source scenario typechecks passed. The test-budget check and `git diff --check` passed. - The default local source bootstrap could not load the macOS embedded PostgreSQL binary because its distribution lacked `libzstd.1.dylib`. Source browser verification used a separate disposable Docker PostgreSQL 16 instance. Linux CI will cover the normal embedded database path. - Earlier [hosted release smoke](https://github.com/paperclipai/paperclip/actions/runs/46776940022) passed both Docker onboarding and Linux background-service onboarding at the first fix commit. The service job first hit npm package propagation and passed on retry after publication completed. - `pnpm verify --explain` requested broader CI coverage because the CI task inputs changed. The focused checks above passed; the required CI jobs will provide broad coverage. - [Final-revision CI](https://github.com/paperclipai/paperclip/actions/runs/46782167000) passed on `236640e419d1177aafb64f3f7dd1ee49848ee707`. Both required aggregates, all 16 browser shards, and all selected typecheck, build, server, Runner, and canary dry-run jobs passed. [Incremental CI qualification](https://github.com/paperclipai/paperclip/actions/runs/46782166749) also passed. - [The new source onboarding case](https://github.com/paperclipai/paperclip/actions/runs/46782167000/job/143123174120) ran on the hosted Linux runner and passed in 20.8 seconds. - [Greptile review](https://github.com/paperclipai/paperclip/pull/23432#issuecomment-7330325410) scored `236640e419d1177aafb64f3f7dd1ee49848ee707` 5/5 and confirmed the shared-dependency finding is fixed. There are no unresolved review threads. ## Risks - This changes test coverage and CI selection. It does not change application behavior, release permissions, or publication rules. - The source case stays on for shared and unfamiliar source changes. It skips only the documented leaf pages and source-unit-test-only edits in eligible plans. Local full E2E still includes it. Extend exclusions only after checking that a path cannot affect onboarding. - The trusted PR workflow is loaded from master. Before merge, the current workflow keeps the full fallback because it does not yet pass the change plan to the shard command. The unit and CLI tests qualify the filtered path; after merge, the new workflow environment activates it. - The source test uses local trusted authentication. The authenticated published-package test remains responsible for login and installation checks. Neither run needs paid model completions. - GitHub master rules require code-owner approval for the protected CI changes. Those review requests are already open. There are no conflicts or unresolved review threads. - A replacement nightly still needs a successful release run after this reaches master. This PR does not bypass qualification or promote beta or stable. ## Model Used OpenAI Codex, `gpt-6.1-sol`, with xhigh reasoning effort, terminal tools, GitHub CLI, and Playwright. The harness does not report the context window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
550d8fc576 |
feat(plugins): honor harness login driver preferences (#23425)
## Thinking Path > - People use Paperclip to manage agents and the accounts they use. > - A harness can sign in on an environment supplied by a plugin. > - Some plugins offer several environments with different login requirements. > - Today the task environment also determines where sign-in runs. > - This change lets the plugin declare its preferred login drivers. > - A company can use a temporary environment for sign-in and keep running tasks on its chosen computer. ## Linked Issues or Issue Description **Subsystem affected** Plugin manifests, login target selection, and the harness sign-in UI. **Current behavior** A plugin with several environments cannot direct sign-in to a preferred driver. Selecting an agent computer for tasks can require an agent even when a temporary environment is available for login. **Proposed behavior** Allow the manifest to declare an ordered list of login drivers. Select the first eligible environment for the company and harness before starting a login. **Reason and benefit** A plugin can offer agentless sign-in first and keep an agent-targeted computer as a fallback. The choice applies only to sign-in. **Additional context** This builds on the agentless login capability in #23392. ## What Changed - Validate ordered login driver keys in the manifest and expose the eligible environments to the company. - Use the same selection rule for device login, setup-token login, onboarding, agent configuration, and AI Connections. - Bind the session and lease to the selected environment. Existing agent eligibility checks apply when the target needs an agent. ## Verification - Server and UI typechecks passed. Focused Vitest runs covered shared manifest validation, driver order, the company access boundary, lease checks, both HTTP login flows, and the UI helpers. - The public SDK source input registry was regenerated. The registry change requires broad CI coverage under `pnpm verify`. - Regression tests cover skipping an environment without an eligible computer, using a newly prepared draft computer, and holding the selected host across capability and readiness updates during sign-in. The UI typecheck and all 16 focused login tests passed on the final commit. - No external provider credentials were used. ## Risks A plugin that opts in must declare at least one usable driver for the user's harness and company. If none qualifies, the start fails before acquisition. Manifests that omit the field keep their existing routing. There is no database migration. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI Codex (GPT-6), with local code inspection, TypeScript checks, and test execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
0434e7f3aa |
feat(board): add task assign, atomic handoff, claim filters, cancel/reopen, mid-flight deps, and channel admin (#23415)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Headless channels, fenced task queues, `@paperclipai/shared/sdk`, and the `pc` CLI landed in #23330 to coordinate multi-agent swarms and inbox/queue patterns. > - Real multi-stage workflows immediately hit gaps: there was no `assign` command to push existing channel posts to managed agents, no atomic `handoff`/`move` across channels with CAS labels and lease release, `claim --ready` could not opt into `backlog`/`in_review` or `--assignee me`, there was no `cancel`/`reopen` or mid-flight `--needs` dependency linking, and `pc channels` could not update queue config, manage private members, or bind event-driven managed pools. > - Without these primitives, operators had to drop back to raw `issue update` calls or non-atomic two-step scripts that race on crash. > - This pull request adds the complete workflow lifecycle across shared schemas, modular server services/routes, SDK methods, `pc` CLI commands, and the `.agents/skills/channels-queues-and-workflows` skill. > - The benefit is end-to-end single-command support for inbox triage, single-thread relays, chained channel assembly lines, mid-flight DAG dependencies, and Day-2 graduation to managed Paperclip agent pools. ## Linked Issues or Issue Description Refs #23330 **Subsystem affected** Cross-cutting (multiple of the above) **Problem or motivation** Building multi-agent queues and chained workflows on Paperclip channels required workarounds: assigning an existing post to a registered agent required raw `issue update --assignee-agent-id <uuid>`; moving an issue across stage channels with a label update and lease release required non-atomic multi-step calls; triage or review workers could not opt into claiming `backlog`, `in_review`, or their own assigned tasks (`--mine`); tasks could not be cancelled, reopened, or given mid-flight `--needs` blockers; and channels lacked CLI/API administration for `queueConfig`, private `channel_access_members`, and `managedPool` auto-dispatch. **Proposed solution** Add cohesive REST endpoints, modular services (`headless-task-workflows.ts`, `headless-channel-admin.ts`), SDK methods, `pc` CLI subcommands, and the `channels-queues-and-workflows` skill covering `assign`, `handoff`/`move`, `cancel`, `reopen`, `block --needs`/`deps`, opt-in `claim --status`/`--assignee`, and `channels update`/`members` with event-driven `managedPool` dispatch. **Alternatives considered** Leaving these operations to raw `PATCH /api/issues/:id` calls was rejected because it bypasses fenced claim tokens (`claimEpoch` + `claimToken`), lacks atomic channel+label+lease transactions, and does not enforce CAS preconditions or dependency cycle checks. **Roadmap alignment** Directly extends the headless channels and queues coordination primitive introduced in #23330. ## What Changed - **Shared schemas & SDK (`packages/shared/src/headless/`, `packages/shared/src/sdk/`):** - Added pure zero-zod constants `CLAIMABLE_TASK_STATUSES` and `TASK_CLAIM_ASSIGNEE_MODES` in `pure.ts`, upgraded `TaskClaimRequestSchema` (`status`/`statuses`, `assignee`) and `TaskReleaseSchema` (`status`, `channel`, `labels`, `unsetLabels`), and added `TaskAssignSchema`, `TaskHandoffSchema`, `TaskCancelSchema`, `TaskReopenSchema`, `TaskDependenciesMutationSchema`, `updateChannelInputSchema`, and `channelMemberInputSchema`. - Added `task.assigned`, `task.handed_off`, `task.cancelled`, `task.reopened`, and `task.dependencies_changed` to `BOARD_EVENT_TYPES`. - Exposed matching SDK methods on `paperclip().tasks`, `ClaimedTask`, and `paperclip().channels`. - **Server services & routes (`server/src/services/`, `server/src/routes/`):** - Upgraded `claimTask` and `releaseTaskClaim` in `headless-task-queue.ts` to support opt-in `status` (`todo`, `backlog`, `in_review` excluding pending interactions), `assignee` (`unassigned`, `me`, `any`), and atomic channel/label/status updates on release. - Added `server/src/services/headless-task-workflows.ts` implementing `assignTask`, `handoffTask`, `cancelTask`, `reopenTask`, `listTaskDependencies`, and `mutateTaskDependencies` (with BFS cycle detection and fenced lease release). - Added `server/src/services/headless-channel-admin.ts` implementing `updateChannel`, `listChannelMembers`, `addChannelMember`, `removeChannelMember`, and event-driven `dispatchManagedChannelPool` (zero idle polling). - Wired routes in `headless-queues-events.ts` and `headless-channels-schemas.ts`. - **CLI (`cli/src/commands/board/`):** - Added `cli/src/commands/board/tasks-workflows.ts` (`pc tasks assign`, `handoff`/`move`, `cancel`, `reopen`, `deps list|add|remove`). - Upgraded `pc tasks claim`/`run` (`--status`, `--assignee`, `--mine`), `pc tasks release` (`--channel`, `--label`, `--unset`, `--status`), `pc tasks block` (`--needs`), and `pc channels` (`update`/`config`, `members list|add|remove`). - **Skill & Tests:** - Added `.agents/skills/channels-queues-and-workflows/SKILL.md` and `examples.md`. - Added `server/src/__tests__/headless-task-workflows.test.ts` and updated `tests/runner-e2e/source-sdk-public-inputs.json`. ## Verification - `pnpm --filter @paperclipai/shared build && pnpm --filter @paperclipai/server typecheck && pnpm --filter paperclipai typecheck` — passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/headless-task-workflows.test.ts src/__tests__/headless-queues-leases-events.test.ts src/__tests__/headless-channels-schemas-batch.test.ts src/__tests__/headless-e2e-sdk-cli.test.ts` — 4 files, 27 tests passed. - `pnpm --filter @paperclipai/shared exec vitest run src/headless/headless.test.ts src/sdk/sdk.test.ts` — 2 files, 20 tests passed. - Live headless CLI test-drive (`pc up --port 3299` in isolated `PAPERCLIP_HOME`) verifying `agent connect`, `post`, `tasks assign`, `tasks claim --mine`, `tasks handoff`, `tasks release --status in_review`, `tasks claim --status in_review`, `tasks block --needs`, `tasks deps list`, blocker completion auto-unblock, `tasks cancel`, `tasks reopen`, `tasks claim --status backlog`, `channels members add/list/remove`, and `channels update --managed-pool` — all 11 scenarios passed. ## Risks - Low risk. No database migrations are required; existing `channels.queue_config`, `channel_access_members`, `issue_relations`, and `issues` lease columns are reused. - Default `claim --ready` behavior (`status = todo`, `assignee = unassigned`) is unchanged; `--status` and `--assignee` are strictly opt-in, and `--assignee me`/`any` never allows claiming tasks assigned to another agent or user. - Note on file size: `server/src/services/headless-task-queue.ts` and `cli/src/commands/board/tasks.ts` were already over 1,000 lines before this PR; all new workflow/admin operations were placed in dedicated sibling modules (`headless-task-workflows.ts`, `headless-channel-admin.ts`, `tasks-workflows.ts`) to keep existing files bounded. ## Model Used - Google Gemini (Antigravity agentic runtime, Gemini 4 Neon Medium, extended thinking with tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
3df59a1853 |
Unify Antigravity runtime and remote /swarm onto agy acp 1.5.19 (#23168)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Paperclip Runner executes Google Antigravity agents on local hosts and remote sandboxes > - Previously, Paperclip shipped two separate Google runtimes: an 853 MiB IDE-extension ACP bundle (`agy_acp_server.par` 1.5.2 + `localharness_external` + Python admission monkey-patch) for ordinary turns and a separate `agy` 1.5.15 CLI binary for local-only `/swarm` turns > - Because the legacy server lacked `/swarm` and the CLI path refused remote targets and required macOS Keychain or Linux user namespaces (`auto` mode), remote sandboxes could not run `/swarm` and carried 853 MiB of legacy binaries > - This pull request unifies all Antigravity surfaces (ordinary turns, `/swarm`, interactive sign-in, and model discovery) onto one pinned `agy` 1.5.19 CLI binary (`1.5.19-4821414830800896`) with file-backed OAuth isolation (`AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1`) and `--dangerously-skip-permissions` support for remote sandboxes > - The benefit is one 268 MiB Linux binary instead of 853 MiB (saving ~585 MiB in remote images), no Python runtime monkey-patching, full `/swarm` support on both local and remote hosts, and a unified 25-model catalog including Gemini 4 Neon, Carbon, Hydrogen, and Argon ## Linked Issues or Issue Description **What existing behavior does this improve?** The Google Antigravity Runner driver, provider pack materialization, Google sign-in flow, model discovery, and `/swarm` execution in `packages/paperclip-runner`, `packages/shared`, `server`, and `ui`. **Subsystem affected** Cross-cutting (multiple of the above) **Current behavior** Ordinary Antigravity turns use the legacy 1.5.2 IDE-extension ACP server (`agy_acp_server.par` + `localharness_external` + Python monkey-patch) at ~853 MiB on `linux-x64`. Native `/swarm` turns require a separate `agy` 1.5.15 CLI binary, refuse remote execution targets (`input.remote`), and fail on Linux sandboxes without user namespaces (`auto` mode). **Proposed behavior** All Antigravity flows use one pinned `agy` 1.5.19 binary (`1.5.19-4821414830800896`, ~268 MiB on `linux-x64`) across all four platforms (`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`). Ordinary turns speak ACP directly through `openAntigravityAcpRuntime`. Both ordinary and `/swarm` turns stage file-backed OAuth tokens under `<agentHomeDirectory>/antigravity-cli/antigravity-oauth-token` with `AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1`, isolate from host keychains, and allow `/swarm` on remote targets using `--dangerously-skip-permissions`. Interactive Google sign-in runs `agy acp --login` with `https://antigravity.google/oauth-callback`, pre-creates `<home>/antigravity-cli` with mode `0700`, and prompts for the authorization code in the UI. **Reason and benefit** Unifying onto `agy` 1.5.19 cuts the `linux-x64` provider-pack footprint by ~585 MiB, removes Python bytecode patching from materialization, enables `/swarm` in headless Linux sandboxes without user namespaces or D-Bus, and aligns ordinary turns, model discovery, and `/swarm` on the same 25-model catalog. **Breaking changes** - `acpx-profiles.json` bumps `antigravity` to `agentProfileVersion: 3` (`native:antigravity-cli`, version `1.5.19`). Existing saved legacy 1.5.2 sessions fail closed as incompatible saved state and start fresh cleanly. - Existing Google OAuth connections carrying `client_secret` remain fully backward-compatible; new `agy acp --login` connections store canonical credentials with `auth_method: "consumer"` and no `client_secret`. ## What Changed - Pin `agy` `1.5.19-4821414830800896` across all four platforms (`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`) in `antigravity-distributions.json`, `antigravity-cli-distributions.json`, `antigravity-cli-pins.ts`, and `acpx-profiles.json` (`agentProfileVersion: 3`), and regenerate TypeScript and Rust profile artifacts. - Replace ZIP + Python patch materialization with strict single-member `tar.gz` verification (`materialize-antigravity-distribution.mjs`, `provision-antigravity.mjs`, `probe-antigravity-metadata.mjs`, `candidate-provider-pack.mjs`, `release-provider-pack.mjs`). - Regenerate `packages/shared/src/antigravity-models.generated.ts` from `agy` 1.5.19 (25 models across 8 families, including Gemini 4 Neon, Carbon, Hydrogen, and Argon) and update `packages/shared/src/antigravity-models.ts` and `tests/runner-e2e/antigravity-qualification-cases.ts` for `xhigh` thinking levels. - Add direct ACP runtime `packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.ts` (`openAntigravityAcpRuntime`) for ordinary Antigravity turns with OAuth and `GEMINI_API_KEY` support, `session/new` + `session/resume`, `readOnly`/plan mode enforcement, HTTP and stdio MCP forwarding, live `setModel`, slash-command neutralization, refusal classification, cancellation, and lineage retirement; route ordinary Antigravity turns unconditionally in `acpx-runtime-adapter.ts` without an ACPX fallback seam. - Update `antigravity-auth.ts`, `antigravity-credentials.ts`, `antigravity-models.ts`, `antigravity-process.ts`, `runtime-host.ts`, and `runtime-sandbox.ts` to run `agy acp --login`, pre-create `<home>/antigravity-cli` with mode `0700` (preventing Go `os.MkdirAll` `0755` readback failures), force file-backed token storage (`AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1`), align `--gemini-dir` with `agentHomeDirectory`, bound model-discovery token sync cleanup, and scrub live CLI token files on cleanup. - Enable remote `/swarm` by removing the `input.remote` refusal in `server/src/services/antigravity-swarm.ts` and allowing `--dangerously-skip-permissions` + `default` mode in `antigravity-swarm-route.ts`, `antigravity-swarm-guard.ts`, and `antigravity-swarm-runtime.ts` when `permissionMode === "approve-all"`. - Update `ui/src/components/AdapterLoginChrome.tsx` copy to prompt for an authorization code (`Submit code`) for `https://antigravity.google/oauth-callback` while preserving callback URL handling for loopback redirects. - Add unit tests for `openAntigravityAcpRuntime`, direct Antigravity routing, `0700` token directory pre-creation, and hosted authorization-code login UX, and update Runner, script, shared, server, Rust, UI, and runner-e2e test suites for `agy` 1.5.19. ## Verification - Runner driver tests: `vitest run` across Antigravity driver test files (`antigravity-auth.test.ts`, `antigravity-models.test.ts`, `antigravity-acp-runtime.test.ts`, `antigravity-swarm-route.test.ts`, `codex-credentials.test.ts`, `acpx-runtime-adapter.test.ts`, `candidate-admission.test.ts`, `native-distribution-integrity.test.ts`) — all passing. - Runner script tests: `node --test` across all 7 Antigravity & provider-pack script suites — 98/98 passed. - Shared, UI, Server, and runner-e2e tests: `antigravity-models.test.ts`, `AdapterLoginChrome.test.tsx` (23/23), `antigravity-thread.test.tsx`, 23 server Antigravity/provider-pack suites, and 7 `runner-e2e` Antigravity suites — all passing. - Rust tests: `cargo test --manifest-path packages/paperclip-runner/runner/Cargo.toml --locked -p paperclip-runner-core -- acpx antigravity` — 145/145 passed. - Typechecks & generators: `@paperclipai/shared`, `@paperclipai/paperclip-runner` (TS + Rust), `@paperclipai/server` (all layers), `@paperclipai/ui`, `generate-acpx-profiles.mjs --check`, `generate-antigravity-models.mjs --check` — all passing. - Live E2E against real pinned `agy` 1.5.19 binaries (macOS `darwin-arm64`, headless Linux `linux-arm64` Docker with `--security-opt no-new-privileges`, and a live remote test deployment): - Verified `materialize-antigravity-distribution.mjs` on all 4 platform archives and `probe-antigravity-metadata.mjs` on macOS and headless Linux Docker. - Verified live Google OAuth sign-in end-to-end via `agy acp --login` + `https://antigravity.google/oauth-callback` authorization code exchange on a live remote deployment, creating a working Antigravity connection. - Verified `stageManagedAntigravityCredential` + `AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1` file-backed isolation and cleanup scrub on macOS and headless Linux Docker. - Verified live `openAntigravityAcpRuntime` ordinary turn + HTTP MCP tool call + `_meta.antigravity.systemPrompt.append` + `setModel(gemini-4-argon-low)` + `session/resume` on real `agy` 1.5.19. - Verified live `openAntigravitySwarmRuntime` `/swarm` turn with `--dangerously-skip-permissions` spawning a real helper, writing workspace file, calling `paperclip_finish`, and retiring cleanly. ## Risks - **Coordinated Cloud deployment**: Remote sandboxes use the companion transition-safe Cloud update to expect `provider-assets/antigravity/linux-x64/agy`, accept `auth_method: "consumer"` credentials without `client_secret`, and scrub `antigravity-cli/antigravity-oauth-token`. - **Saved session continuity**: Existing saved 1.5.2 sessions fail closed as `ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE` and start fresh cleanly on 1.5.19. ## Model Used - Google Gemini (Antigravity agentic coding assistant, reasoning/tool-use/code-execution enabled) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
16614f4fda |
feat(issues): add canonical structured coordination parity across API, OpenAPI, CLI, and public MCP (#23410)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work, where agents and humans coordinate tasks through the REST API,
`paperclipai` CLI, Native Runner API catalog, and Public MCP tools.
> - Structured coordination primitives (`channel`, `kvLabels`,
`resultSchemaRef`, and `schemaBlocks`) previously worked on `/headless`
endpoints, while canonical `/api/issues` routes, `GET
/api/issues/:id/heartbeat-context`, `paperclipai issue` CLI commands,
and Public MCP task tools did not accept or surface those fields
consistently, and OpenAPI exposed headless routes with summary-only
stubs.
> - Because agents wake up from `heartbeat-context`, inspect endpoint
schemas through OpenAPI and `runnerApiReference`, or mutate tasks
through canonical `POST`/`PATCH /api/issues` routes, CLI flags, and
Public MCP tools, missing fields on those surfaces forced callers onto
parallel endpoints or caused agents to miss required deliverable schemas
until after closing a task.
> - We chose to wire structured coordination directly onto the canonical
issue validators, routes, `heartbeat-context`, CLI flags, OpenAPI
schemas, `runnerApiReference` examples, and Public MCP task tools while
reusing existing channel-privacy and JSON Schema registries.
> - For Markdown ```` ```json schema=<name>@<version> ```` extraction in
issue descriptions and comments, we avoided multi-line backtracking
regular expressions and implemented a single-pass $O(N)$ CommonMark
character-index line scanner with strict input, fence-body, and block
caps so adversarial unclosed fences remain linear.
> - When an agent transitions an issue with `resultSchemaRef` to final
status `done`, `PATCH /api/issues/:id` now verifies that a valid
matching schema block exists across incoming or stored issue/comment
blocks and returns a self-documenting HTTP `422`
(`result_schema_validation_failed` with `requiredResultSchema` and
`jsonSchema`) while still allowing human board actors to close tasks
manually.
## Linked Issues or Issue Description
**What existing behavior does this improve?**
Canonical issue creation, updates, comments, list filters,
`heartbeat-context`, OpenAPI schemas, `runnerApiReference` examples,
`paperclipai issue` CLI commands, and Public MCP task tools now support
structured coordination fields (`channel`, `kvLabels`,
`resultSchemaRef`, and `schemaBlocks`) with full parity alongside
existing headless routes.
**Subsystem affected**
Server API (`packages/shared/src/validators/issue.ts`,
`server/src/routes/issues.ts`, `server/src/services/issues.ts`,
`server/src/routes/openapi.ts`,
`server/src/services/native-runtime/runner-api-reference.ts`,
`server/src/services/public-mcp/*`) and CLI
(`cli/src/commands/client/issue.ts`).
**Current behavior**
- `createIssueSchema`, `updateIssueSchema`, and `addIssueCommentSchema`
do not accept `channel`, `kvLabels`, `resultSchemaRef`, or
`schemaBlocks`.
- Canonical `GET /api/companies/:companyId/issues` does not filter by
`?channel=` or `?kvLabel=`, `GET /api/issues/:id/heartbeat-context`
omits `channelId`, `channelPath`, `kvLabels`, `resultSchemaRef`, and
`schemaBlocks`, and `PATCH /api/issues/:id` does not enforce
`resultSchemaRef` when an agent marks an issue `done`.
- `server/src/routes/openapi.ts` registers headless
channel/schema/kv-label/batch/queue/schedule/event endpoints with
summary-only stubs without `parameters` or `requestBody` schemas, and
`runnerApiReference` lacks examples for key headless coordination
routes.
- `paperclipai issue` (`create`, `update`, `comment`, `list`) and Public
MCP (`paperclip_search_tasks`, `paperclip_create_task`,
`paperclip_update_task`, `paperclip_add_comment`) do not expose channel,
key-value label, result schema, or schema block inputs/outputs.
**Proposed behavior**
- Extend `@paperclipai/shared` issue validators
(`createIssueBaseSchema`, `updateIssueSchema`, `addIssueCommentSchema`)
with validated `kvLabels`, `resultSchemaRef`, `channel`, `schemaBlocks`,
`commentKvLabels`, and `commentSchemaBlocks`.
- Add a linear $O(N)$ single-pass CommonMark schema fence scanner
(`server/src/services/schema-fence-scanner.ts`) with zero regexes and
strict input/fence caps (`512 KiB` text, `64 KiB` fence body, `64`
candidate fences, `32` blocks).
- Support `channel`, `kvLabels`, `resultSchemaRef`, and explicit/fenced
`schemaBlocks` on `POST /api/companies/:companyId/issues`, `POST
/api/issues/:id/children`, `PATCH /api/issues/:id`, `POST
/api/issues/:id/comments`, `GET /api/companies/:companyId/issues`
(`?channel=` and `?kvLabel=`), and `GET
/api/issues/:id/heartbeat-context`, enforcing private-channel access
rules and HTTP `422` `result_schema_validation_failed` (with
`requiredResultSchema` and `jsonSchema`) when an agent transitions an
issue with `resultSchemaRef` to final status `done`.
- Replace summary-only headless OpenAPI stubs with full `query` and
`requestBody` schemas, document `channel` and `kvLabel` query parameters
on `GET /api/companies/{companyId}/issues`, and add `runnerApiReference`
examples for `PATCH /api/issues/{}/kv-labels`, `POST
/api/companies/{}/channels/posts`, `POST /api/companies/{}/schemas`, and
`POST /api/companies/{}/issues/batch`.
- Add `--kv`, `--unset-kv`, `--result-schema`, `--channel`, and
`--schema-block` flags to `paperclipai issue` (`create`, `update`,
`comment`, `list`), and expose structured fields and inputs on Public
MCP task tools and projections.
**Reason and benefit**
Agents and humans can use one canonical set of issue endpoints, CLI
flags, Native Runner API discovery schemas, and Public MCP tools to
route work into channels, filter and patch structured `kvLabels`, attach
validated `schemaBlocks`, and enforce `resultSchemaRef` deliverables at
completion time with immediate JSON Schema feedback.
**Breaking changes**
No — purely additive on canonical issue schemas, CLI flags, OpenAPI
definitions, and Public MCP tools. Existing callers without
`resultSchemaRef` or structured fields behave identically, and human
board actors (`req.actor.type === "board"`) can still close tasks with
`resultSchemaRef` without attaching a schema block.
## What Changed
- **Shared Issue Validators
(`packages/shared/src/validators/issue.ts`)**: Added
`issueKvLabelsSchema`, `issueKvLabelsPatchSchema` (`null` unsets keys),
`issueResultSchemaRefSchema`, `issueChannelInputSchema`, and
`issueSchemaBlocksSchema`; extended `createIssueBaseSchema`,
`updateIssueSchema`, and `addIssueCommentSchema`; refreshed
`tests/runner-e2e/source-sdk-public-inputs.json`.
- **Linear Schema Fence Scanner & Structured Helpers
(`server/src/services/schema-fence-scanner.ts`,
`server/src/services/issue-structured-fields.ts`,
`server/src/services/issue-visibility.ts`)**: Implemented a
character-index single-pass CommonMark fence scanner with no
backtracking regexes, plus channel resolution/privacy helpers,
`kvLabels` merge/filter helpers, schema block validation, and agent
`done` deliverable enforcement.
- **Canonical Issue Routes & Service (`server/src/routes/issues.ts`,
`server/src/services/issues.ts`,
`server/src/routes/headless-channels-schemas.ts`)**: Wired `channel`,
`kvLabels`, `resultSchemaRef`, and `schemaBlocks` across create, child
create, update, comment, list (`?channel=`, `?kvLabel=`), and
`heartbeat-context` (`channelId`, privacy-checked `channelPath`,
`kvLabels`, `resultSchemaRef`, `schemaBlocks`), plus HTTP `422`
`result_schema_validation_failed` enforcement when an agent marks an
issue `done` without a valid deliverable block.
- **OpenAPI, Docs & Runner API Reference
(`server/src/routes/openapi.ts`,
`server/src/services/native-runtime/runner-api-reference.ts`,
`docs/api/issues.md`)**: Replaced summary-only headless OpenAPI entries
with full `query` and `requestBody` schemas reusing shared channel/batch
schemas across all 27 headless endpoints, documented `channel` and
`kvLabel` on `GET /api/companies/{companyId}/issues`, documented all new
canonical issue fields and `422 result_schema_validation_failed`
behavior in `docs/api/issues.md`, and added `runnerApiReference`
examples for `PATCH /api/issues/{}/kv-labels`, `POST
/api/companies/{}/channels/posts`, `POST /api/companies/{}/schemas`, and
`POST /api/companies/{}/issues/batch`.
- **CLI & Public MCP (`cli/src/commands/client/issue.ts`,
`server/src/services/public-mcp/{contracts,capabilities,expanded-capabilities}.ts`)**:
Added `--kv`, `--unset-kv`, `--result-schema`, `--channel`, and
`--schema-block` flags to `paperclipai issue` (`create`, `update`,
`comment`, `list`) and added structured fields and parameters to Public
MCP task contracts and tools (`paperclip_search_tasks`,
`paperclip_create_task`, `paperclip_update_task`,
`paperclip_add_comment`).
## Verification
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck` — passed.
- `pnpm exec vitest run packages/shared/src/validators/issue.test.ts` —
65/65 passed (including Zod `z.toJSONSchema` compatibility).
- `pnpm exec vitest run
server/src/__tests__/schema-fence-scanner.test.ts` — 4/4 passed (`5,000`
repeated unterminated ```` ```json ```` lines scanned in `< 50ms`).
- `pnpm exec vitest run
server/src/__tests__/canonical-issue-structured-parity.test.ts
server/src/__tests__/headless-channels-schemas-batch.test.ts
server/src/__tests__/headless-e2e-sdk-cli.test.ts` — 14/14 passed.
(During initial test execution, an invalid `resultSchemaRef` fence on
`PATCH /api/issues/:id { status: "done", comment }` hit generic
`schema_validation_failed` before
`assertAgentResultSchemaSatisfiedOnDone`; reordered
`assertAgentResultSchemaSatisfiedOnDone` ahead of `validateSchemaBlocks`
so agents consistently receive `result_schema_validation_failed` with
`requiredResultSchema` and `jsonSchema`, then re-ran green.)
- `pnpm exec vitest run server/src/__tests__/openapi-routes.test.ts
server/src/services/native-runtime/runner-api.test.ts
server/src/services/native-runtime/runner-api-reference.test.ts` —
2,444/2,444 passed.
- `pnpm exec vitest run cli/src/__tests__/issue-subresources.test.ts` —
7/7 passed.
- `pnpm exec vitest run server/src/__tests__/public-mcp.test.ts` — 84/84
passed.
- `(cd server && node scripts/typecheck-layers.mjs)` and `pnpm --filter
paperclipai typecheck` — passed all typecheck layers.
- `node scripts/check-module-boundaries.mjs`, `node
scripts/check-agent-lifecycle-boundaries.mjs`, `node
scripts/check-test-budget.mjs`, and `node
tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD)
--check` — passed.
- `pnpm verify` — exited `2` (`Broad input:
tests/runner-e2e/source-sdk-public-inputs.json`) after refreshing
`source-sdk-public-inputs.json`; focused Vitest suites and layered
typechecks passed locally and broad coverage runs in required PR CI.
- **Round 1 PR CI & review follow-up**: Initial PR CI caught a circular
module initialization (`openapi.ts` importing
`ResolveInteractionInputSchema` from
`services/headless-events-schedules-interactions.ts`, leaving
`runnerApiCallSchema` undefined in `native-workflow-tools.ts`), and code
review flagged private-channel issue/child `visibility` inheritance,
locked-row `resultSchemaRef` enforcement + agent immutability, follow-up
edits on already-`done` tasks, SDK non-UUID retry-key routing on `POST
/issues/:id/comments`, strict `> 512 KiB` fence rejection,
`schemaBlocks` on `paperclip_create_task`/`paperclip_update_task`,
`timeout` query param on `/events/wait`, and `docs/api/issues.md`
updates. Removed the `services/*` import from `openapi.ts`, fixed each
review finding, and verified `tool-input-variant-admission.test.ts`,
`teams-catalog-service.test.ts`,
`canonical-issue-structured-parity.test.ts`, `public-mcp.test.ts`,
`headless-channels-schemas-batch.test.ts`,
`headless-e2e-sdk-cli.test.ts`, `headless-identity-auth.test.ts`, and
`schema-fence-scanner.test.ts` (2,663/2,663 tests passing across 13
suites).
## Risks
- **Private channel existence or path leakage**: Mitigated by checking
`canAccessChannel` on canonical channel writes, list filters
(`?channel=`), and `GET /api/issues/:id/heartbeat-context` (failing
closed with `404` on inaccessible private channel targets and returning
`channelPath: null` when a private channel is not accessible to the
caller).
- **Adversarial Markdown payloads on issue/comment writes**: Mitigated
by scanning fences with a pure character-index single-pass CommonMark
line scanner with zero regular expressions, bounded at `512 KiB` input
text, `64 KiB` per fence body, `64` candidate fences, and `32` schema
blocks.
- **`resultSchemaRef` completion blocking**: Mitigated by enforcing
`422` `result_schema_validation_failed` only when `req.actor.type ===
"agent"` and the effective target status after execution-policy routing
is `"done"`, preserving manual task closure for board humans and
intermediate `in_review` transitions.
## Model Used
Google DeepMind `gemini-3.1-pro` via Antigravity agentic coding harness
(1M context window, high reasoning effort, native workspace/file/test
tool execution).
## Checklist
- [x] I searched the [GitHub PR
list](https://github.com/paperclipai/paperclip/pulls?q=is%3Apr) (open +
recently closed) for similar PRs and confirmed this is not a duplicate
- [x] My code follows the project's [code
comments](CONTRIBUTING.md#code-comments) guidelines (self-documenting,
minimal comments)
- [x] `pnpm -r typecheck` passes (verified locally across
`@paperclipai/shared`, `server` layered typecheck, and `paperclipai`
CLI; full workspace `typecheck_release_registry` verified in PR CI)
- [x] `pnpm test:run` passes (focused owner Vitest suites passed
locally; full CI matrix verified in PR CI)
- [ ] `pnpm build` passes
- [ ] If I changed `packages/db`, I ran `pnpm db:generate` and committed
the migration
- [x] If I added a user-facing capability, I updated `README.md` or
relevant docs (`docs/api/issues.md`)
- [x] This PR focuses on a single concern (no unrelated changes bundled)
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
|
||
|
|
c0edaa21a3 |
feat(analytics): move onboarding funnel telemetry server-side and add granular step instrumentation (#23403)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted Paperclip Cloud tracks user onboarding conversion in PostHog
across server-side events and browser events
> - Onboarding funnel events (`onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed`,
`onboarding_step_failed`, `onboarding_dismissed`) currently fire only
from browser `posthog-js`
> - Browser `posthog-js` loads lazily after `whenPageSettles` (up to 15
seconds), drops events captured before `startProductAnalytics`
initializes, and can be blocked by privacy extensions, causing
artificial dropoff between server-side `workspace_entry` and
`onboarding_opened`
> - Step 1 (`name_org`) is unmapped in `WIZARD_STEPS`, and
`connect_model` lacks sub-step visibility (provider selection,
credential mode switch, OAuth progress, API key submission, Cloud trial
CTA, mobile handoff)
> - This pull request routes all onboarding funnel events through a
first-party `POST /api/onboarding/telemetry` endpoint backed by
`trackCloudPostHogEvent` (`posthog-node`), preserves every existing
event name verbatim, adds granular step and sub-step instrumentation,
and fixes the pre-start queue drop in `product-analytics.ts`
> - The benefit is adblocker-proof, race-free server-side onboarding
analytics in PostHog with complete step-by-step dropoff visibility and
zero breaking changes to existing insights
## Linked Issues or Issue Description
**What existing behavior does this improve?**
Cloud onboarding funnel analytics in
`ui/src/lib/analytics/onboarding-analytics.ts`,
`ui/src/lib/analytics/product-analytics.ts`,
`ui/src/components/OnboardingWizard.tsx`, and `server/src/telemetry.ts`.
**Subsystem affected**
Cross-cutting (multiple of the above)
**Current behavior**
Onboarding funnel events fire only from browser `posthog-js`. Events
captured before `ProductAnalyticsGate` calls `startProductAnalytics` are
silently dropped, queued events are lost if the user leaves before
`/_ph/static/array.js` loads, Step 1 (`name_org`) is unmapped, and
`connect_model` sub-steps (OAuth link open, code submit, retry, abandon,
provider tile click, Cloud trial CTA, mobile desktop handoff) are not
instrumented.
**Proposed behavior**
All onboarding funnel and interaction events are sent via
`fetch("/api/onboarding/telemetry", { method: "POST", keepalive: true
})` to a board-authenticated, strictly Zod-validated Express route that
forwards them server-side to PostHog via `trackCloudPostHogEvent`.
Existing event names are preserved verbatim and removed from
`posthog-js` to guarantee a single sender per event. Pre-start browser
events in `product-analytics.ts` are also buffered until
`startProductAnalytics` runs.
**Reason and benefit**
Adblockers and browser script lazy-load races can no longer drop
onboarding funnel events. Product analytics can now separate
`workspace_entry` -> `onboarding_workspace_loaded` ->
`onboarding_opened` and pinpoint exact dropoff points on every step and
`connect_model` sub-step.
**Breaking changes**
None. Existing PostHog event names (`onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed`,
`onboarding_step_failed`, `onboarding_dismissed`,
`agent_chat_message_sent`) are preserved verbatim. On self-hosted
installs, `trackCloudPostHogEvent` is a no-op and the endpoint returns
`204 No Content`.
## What Changed
- Added `packages/shared/src/onboarding-telemetry.ts` (exported from
`packages/shared/src/index.ts`) with strict Zod discriminated-union
schemas (`onboardingTelemetryEventSchema`), canonical event names
(`ONBOARDING_TELEMETRY_EVENTS`), and snake_case PostHog property mapping
(`onboardingTelemetryEventToPostHogProperties`).
- Added `server/src/routes/onboarding-telemetry.ts` (`POST
/api/onboarding/telemetry`), mounted in `server/src/app.ts`, enforcing
`assertBoard(req)`, `assertCompanyAccess(req, companyId)` when
`companyId` is present, strict schema validation, and server-side
delivery via `trackCloudPostHogEvent`.
- Updated `ui/src/lib/analytics/onboarding-analytics.ts` to send all
onboarding events to `/api/onboarding/telemetry` with `keepalive: true`
(removing duplicate browser `posthog-js` sends), mapped Step 1 to
`name_org`, fixed `1 -> 3` forward step completion ordering, and added
granular capture helpers.
- Instrumented `ui/src/hooks/useAgentlessOnboardingAutoOpen.ts`
(`onboarding_workspace_loaded`),
`ui/src/components/onboarding/MobileDesktopNudge.tsx`
(`onboarding_mobile_handoff_action`), and
`ui/src/components/OnboardingWizard.tsx` (all step submissions,
back/jump navigation, Cloud trial CTA, model source selection,
credential mode switching, OAuth progress stages, API key submission,
advanced toggle, and launch click). Note: `OnboardingWizard.tsx` is an
existing large file (>1,000 lines); all schema and transport logic lives
in `packages/shared/src/onboarding-telemetry.ts` and
`ui/src/lib/analytics/onboarding-analytics.ts`, with only call-site
wiring added to the wizard.
- Fixed `ui/src/lib/analytics/product-analytics.ts` to buffer events
captured before `startProductAnalytics` runs (still bounded to 50 events
and cleared on user change).
- Added server route tests in
`server/src/__tests__/onboarding-telemetry-routes.test.ts` and expanded
`ui/src/lib/analytics/onboarding-analytics.test.tsx`.
- Updated `tests/runner-e2e/source-sdk-public-inputs.json` for the new
`@paperclipai/shared` export.
## Verification
- `pnpm --filter @paperclipai/shared build` — passed.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.
- `pnpm vitest run
server/src/__tests__/onboarding-telemetry-routes.test.ts
ui/src/lib/analytics/onboarding-analytics.test.tsx
ui/src/lib/analytics/product-analytics.test.ts
ui/src/lib/analytics/product-analytics-events.test.ts
ui/src/components/ProductAnalyticsGate.test.tsx
ui/src/hooks/useAgentlessOnboardingAutoOpen.test.tsx` — 6/6 test files
passed (41/41 tests).
- `pnpm verify` — exited with code 2 because
`tests/runner-e2e/source-sdk-public-inputs.json` requires broad CI
coverage; relying on required CI checks for the remaining broad suites.
## Risks
- Low risk: `POST /api/onboarding/telemetry` performs no database
writes, validates all fields against a strict allowlist (enums,
booleans, bounded integers, safe regex slugs), enforces board auth and
company access, and is a no-op returning `204` on self-hosted instances.
- Browser telemetry calls swallow network failures so analytics can
never block or break onboarding.
## Model Used
- Google Gemini (Gemini 4 Neon, Medium) via Antigravity agentic coding
environment with tool use and local command execution.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
|
||
|
|
689bfd04ac |
feat(onboarding): add free_inference_1 onboarding flow, dual-trigger model gate, and multi-variant PostHog attribution (#23401)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - First-time Cloud users currently must connect an external AI
provider during onboarding before they can talk to their first agent.
> - Requiring provider setup up front adds friction before users
experience their first agent chat.
> - Paperclip needs a multi-variant onboarding experiment
(`onboarding-flow`) that defaults to `baseline` while allowing an
alternate `free_inference_1` path that skips the model-connection screen
and starts with capped starter inference.
> - When a trial-only workspace either exhausts its starter credit or
creates its first executable task or subtask, Paperclip must hold the
new task, prompt the user to connect a model provider, keep LLM actions
blocked if the modal is dismissed, and automatically resume held work
once a model is connected.
> - This pull request adds multi-variant onboarding resolution, PostHog
multi-variant attribution, dual-trigger connect-model gating with
restart-safe DB hydration, the `free_inference_1` UI onboarding flow,
and full-flow Storybooks.
> - The benefit is a safe, measurable onboarding experiment that leaves
`baseline` and self-hosted installs unchanged while letting opted-in
Cloud workspaces reach their first chat immediately and upgrade
seamlessly when real work begins.
## Linked Issues or Issue Description
**Subsystem affected**
Cross-cutting (`packages/shared/`, `server/`, `ui/`)
**Problem or motivation**
New Cloud users currently hit a mandatory "Connect a model" step during
onboarding before they can open their first agent chat. Existing
trial-inference gating only supported a binary flag and only triggered
on starter-credit exhaustion, not on subtask or manual task creation,
and did not track multi-variant onboarding cohorts cleanly in PostHog.
**Proposed solution**
Introduce the extensible `onboarding-flow` experiment (`baseline`
default, `free_inference_1` variant) across shared contracts, server
services, and UI:
- Resolve `onboardingVariant` from the Cloud control plane (`GET
/v1/tenant/onboarding-config`) with safe fallbacks to
`PAPERCLIP_ONBOARDING_VARIANT`, managed config, and `"baseline"`.
- In `free_inference_1`, skip Step 4 ("Connect a model") in
`OnboardingWizard`, hire the first agent on starter inference, and drop
the user straight into the first chat.
- Support a dual-trigger connect-model gate (`exhausted` and
`work_requires_model`) that holds newly created tasks/subtasks on
trial-only workspaces (hydrated from DB across restarts), returns HTTP
402 for blocked LLM chat/runs, keeps the modal dismissible while
blocking chat composers with a "Connect a model" CTA banner, and
automatically resumes held work after provider migration.
- Stamp `$feature/onboarding-flow`, `onboarding_variant`, and immutable
`initial_onboarding_variant` across server PostHog events,
`$groupidentify` (with top-level `$group_set_once`), and browser PostHog
super-properties / `identify()`.
**Alternatives considered**
- Baking per-stack experiment variants into warm-pool container config
was ruled out because warm-pool stacks must remain homogeneous until
claim time.
- Failing agent subtask creation calls on trial-only workspaces was
ruled out because it breaks the agent's first-chat experience; creating
the task in a held state and auto-resuming it after model connection
preserves user intent.
## What Changed
- **`packages/shared`**: Added `onboarding-flow` variant
constants/helpers, `CloudTrialGateReason` (`"exhausted" |
"work_requires_model"`), `CloudTrialHeldIssueSummary`, `gateReason`,
`llmBlocked`, `heldIssueIds`, `heldIssues`, `onboardingVariant`, and
`resumedIssueIds` on cloud-inference and session/browser-analytics
contracts.
- **`server/`**:
- Added Ed25519-signed `GET /v1/tenant/onboarding-config` resolution
with warm-pool claim cache invalidation and safe `"baseline"` default.
- Added dual-trigger trial gating (`exhausted` + `work_requires_model`)
with DB-backed held-issue hydration across restarts, HTTP 402 refusal
for blocked trial runs and chat sends, and automatic wake/resume of held
subtasks upon migration.
- Updated PostHog server telemetry, `$groupidentify` (top-level
`$group_set` and `$group_set_once`), `$feature_flag_called`, and
`BrowserAnalyticsConfig` to stamp `onboarding-flow` multi-variant
properties while preserving backwards-compatible `cloud-trial-inference`
properties.
- Added and updated Vitest suites covering multi-variant resolution,
PostHog attribution, held subtask creation, cold-restart hydration, LLM
run refusal, and auto-resume.
- **`ui/`**:
- Updated `OnboardingWizard` so `free_inference_1` skips Step 4
("Connect a model"), auto-hires with `cloudTrialInference: true`, and
launches straight into the first chat while leaving `baseline`
unchanged.
- Updated `CloudTrialGate` and `CloudTrialExhaustedModal` for
dual-trigger copy (`work_requires_model` vs `exhausted`), waiting
subtask pills, and dismissible modal behavior (`required={false}`).
- Added `CloudTrialBlockedBanner` and wired LLM-blocked composer
disabling + "Connect a model" CTA into `IssueDetail` / `AgentChat` and
`DashboardChatComposer`, plus status refresh on manual task creation in
`NewIssueDialog`.
- Updated `product-analytics.ts` + tests to register
`$feature/onboarding-flow` and `onboarding_variant` super-properties and
`$set_once.initial_onboarding_variant`.
- Added full-flow Storybooks
(`free-inference-onboarding-flow.stories.tsx`) covering all 7 onboarding
and gate states.
## Verification
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck` (0 errors)
- `pnpm --filter @paperclipai/ui typecheck` (0 errors)
- 9 targeted server Vitest suites (`cloud-trial-inference`,
`cloud-posthog-config`, `cloud-posthog-browser`,
`posthog-direct-telemetry`, `posthog-direct-transport`, `auth-routes`,
`cloud-runtime-identity`, `onboarding-seed-route`,
`issue-onboarding-first-task-routes`): 196/196 passed
- 4 targeted UI Vitest suites (`CloudTrialGate.test.tsx`,
`product-analytics.test.ts`, `onboarding-analytics.test.tsx`,
`Layout.mobile.test.tsx`): 37/37 passed
- `pnpm --filter @paperclipai/ui build` and `pnpm --filter
@paperclipai/ui build-storybook`: passed
- Visually inspected Storybook renders across all 7 `free_inference_1`
states in headless Chromium via Playwright with zero page errors.
## Risks
- Low risk to existing users: `onboardingVariant` defaults to
`"baseline"` everywhere, leaving self-hosted installs and unflagged
Cloud stacks unchanged.
- No database schema migrations are required; held trial subtasks are
hydrated from existing `issues` and `toolConnections` tables on restart.
- Requires the companion `paperclip-cloud` control-plane endpoint (`GET
/v1/tenant/onboarding-config`) to activate non-baseline variants in
Cloud; falls back safely to `"baseline"` if unavailable.
## Model Used
- Google Gemini (Antigravity agentic coding environment with multi-agent
swarm, tool use, code execution, and Playwright Storybook verification)
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
|
||
|
|
b63445c8f1 |
fix(e2e): save hiring task intents at the submit boundary (#23400)
## Thinking Path > - Paperclip manages work by AI agents. > - Its product journeys verify hiring and task delegation through chat. > - Cleanup uses saved creation intents to track possible writes. > - The hiring journey saves each task intent before browser preparation. > - A navigation or editor failure can therefore leave an intent for a request that was never sent. > - This pull request saves the intent after message validation and before Send. > - Cleanup can retain strict write protection without treating failed preparation as a possible task creation. ## Linked Issues or Issue Description **What happened?** The hiring journey can save a review-task intent even when a browser failure stops the third chat request before submission. Cleanup then reports an uncertain creation outcome. A controlled navigation failure reproduces this tracking defect. The original retained browser exception is unavailable; this change does not claim its cause. **Expected behavior** Browser preparation must not register a task write. The creation intent must be saved before submission can create work. A failed intent save must stop submission. A send with a possible committed write must retain the intent. **Steps to reproduce** Inject a navigation failure before the review request after the checklist completes. The original code records the review intent despite making only two sends. The new code preserves the checklist receipt and records no review intent. **Paperclip version or commit** Reproduced from source at `5a9c06b315d9612022908b7fc189f30bac3619af`. **Deployment mode** Linux source checkout, focused workflow tests, and Chromium against the real production composer. The paid hosted acceptance case remains pending until merge. Related earlier hiring coverage and spacing fixes: #18351 and #22825. ## What Changed - Save delegated-task intents through an awaited callback after the exact mention chips are verified and before the browser clicks Send. - Cover failed review navigation, failed intent persistence, rejected mentions, and a send failure after the intent boundary. - Keep handoff references and task name in one typed object. A handoff without its intent name is no longer representable. - Keep the existing ownership, initial assignment, saved-body, seven-run, budget, and cleanup checks. - Document the submission boundary. ## Verification - Red: the new review-navigation regression failed because the old flow saved the review intent without sending that request. - Green: 78 focused flow and evidence tests pass. - All 8 real-composer Chromium checks pass. They cover both composer modes, exact saved messages, failed intent persistence, page loss after persistence, and rejected agent/project mentions. - `pnpm test:e2e:runner:typecheck` passes. - `pnpm verify --explain` could not select checks because the managed Git storage guard rejects `git ls-files`. Even the suggested shallow fetch fails. This unavailable check is not a pass. The source was compared with master through the repository API before publication. - Original head `6914c4b` passed [CI](https://github.com/paperclipai/paperclip/actions/runs/46723605434) and Greptile 5/5 with Low impact. Typecheck, four support shards, six Runner package shards, static checks, and aggregate verification passed. Build was skipped by the test-only path policy. - Review head `cd7b03f36d6d9fcac37cf80906fad2f7cd167958` passes the 78 focused tests, all 8 browser checks, and runner E2E typecheck. Its first browser attempt could not start because the resumed sandbox lacked Chromium; installation restored the check, which then passed. The current head passed [CI](https://github.com/paperclipai/paperclip/actions/runs/46727370488), including Typecheck + Release Registry, four support shards, six Runner package shards, static checks, and aggregate verification. Build is skipped by the test-only path policy. Greptile, Feynman and Ponytail each gave this head 5/5, with Low impact from Greptile. The actionable thread is resolved. Hosted acceptance must run only `hire-delegate-reuse` after merge. ## Risks The callback and Send cannot form one atomic operation. A failure after intent persistence still keeps the intent and the existing uncertain-write protection. This patch does not manufacture absence proof for old retained manifests. The original browser error remains unknown. ## Model Used OpenAI GPT-6 through Codex, with reasoning, shell tools, source editing, and Chromium. The runtime does not expose a more specific backend model revision or context size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
5a9c06b315 |
feat(analytics): make replay work content a deployment opt-in (#22820)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Hosts can enable PostHog browser analytics and session replay through deployment configuration. > - Replay masks work content, which makes task and artifact flows hard to understand. > - Hosts must decide whether their deployment may show this content. > - This pull request adds an explicit deployment opt-in, with work content masked by default. > - Eligible companies can show work content after that opt-in, while connected-account checks and secret masking still apply. ## Linked Issues or Issue Description No public issue exists. This change follows the enhancement template. **What existing behavior does this improve?** Session replay masks task descriptions, document bodies and artifact previews. A host cannot choose to show eligible work content independently of enabling replay. **Subsystem affected** Browser session replay, deployment analytics configuration, and the authenticated session contract. **Current behavior** Work content stays masked in every company. Task and artifact titles already show. PostHog project masking settings cannot override the options supplied by the board UI. **Proposed behavior** Keep work content masked by default. Set `PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED=1` in deployment configuration to allow it for eligible companies. Unset, `0`, and other values keep it masked. Browser analytics and replay must also be enabled. A host can keep replay enabled while work content stays masked. **Reason and benefit** Hosts control their recording policy without editing Core source. An eligible company's replay can show the task flow after the host opts in. **Breaking changes** None relative to the base branch. Self-hosted analytics remain disabled by the existing analytics gate. Existing deployments retain work-content masking unless they explicitly opt in. The session gains an optional boolean and the tool connection list gains an optional `hiddenCount` field. Missing fields fail closed. ## What Changed - Add `PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED`, default off. Resolve it in the existing server analytics configuration and send the effective boolean as `browserAnalytics.replayWorkContentEnabled`. The shared session schema preserves the field and accepts older servers that omit it. - Require both replay and the work-content opt-in before the UI queries company sources or permits visibility. Removing the opt-in from a refreshed session masks content even when eligible source answers remain cached. - Preserve the original company checks: complete tool connection and chat endpoint lists, no Google or Slack source, no known aggregator or router, and the selected company's route. Unknown, failed, invalidated, or hidden source data keeps content masked. Live source changes reset the check. - Mark task descriptions, document bodies, attachment and artifact previews, and file viewers as work content. Customer content, editors, comments, chat, run output and connected-account surfaces remain masked. Secrets remain blocked or redacted. Input and attribute values remain masked. - Preserve credential punctuation in task previews by reusing the shared Markdown plain-text helper. Bound conversion to the first 2,048 source characters, and always mask source-capped previews to protect incomplete credentials. Scan complete command-line flag names once before classifying secrets and reading their values. A 512 KiB hyphen input and long flag names have regression coverage. - Mask surfaces that show cut or rewritten work content, where the redaction cannot work. A cut task preview masks when the text before its 180-character limit holds a credential. The document card preview (first 4,000 characters) masks when the cut changes what the redaction masks before it. The text preview on an artifact card always masks, because the server strips hyphens and underscores from it and cuts it at 280 characters. Quoted flag values run past escaped quotes, and flag names can hold an underscore. An unquoted token that starts with `--` is read as the next flag, not as a value, so `--auth --tlsCertificateKeyFilePassword hunter2` masks `hunter2`. - Refresh the recording once when a company's work content first becomes visible. Keep the existing autocapture text and attribute masking. - Add tests for deployment switches, session parsing and exposure, disabled source requests, older servers, and withdrawal with cached data. Retain the original masking, company, secret, and source-change tests. - Document configuration, rollback, restart and tab-reload steps, residual recording risks, and the board-only `hiddenCount` API field with absent-on-older-server semantics. Refresh the shared-source pins with the maintained generator; runtime and compiler pins stay unchanged. The original implementation and commits are preserved from @nguyenm7. The deployment configuration follow-up adds the host opt-in. When squash-merging, preserve the follow-up author's credit in the squash commit body: ```text Co-Authored-By: Devin Foley <devinfoley@users.noreply.github.com> ``` ## Verification Current head `2ce967f1e1`: CI has 43 checks passed and four skipped, with none failed or pending. The Greptile review on this head is 5/5, and both findings from its previous review are fixed. No person has approved the pull request yet. The evidence below was recorded on earlier heads and is kept as the record of how the change was verified. Greptile apex review: 5/5 on `45023e6`, with no unresolved review threads. CI on that head is green: 76 checks passed and four skipped, with no failed or pending checks. The branch has no merge conflicts with master. On the final source change, locally: - `cd ui && pnpm exec vitest run src/lib/analytics src/context/LiveUpdatesProvider.test.ts src/lib/markdown-plain-text.test.ts`: 10 files, 520 tests pass. The secret-redaction cases are in `replay-secret-redaction.test.tsx`, so `replay-masking.test.tsx` stays under 1,000 lines (701). - `cd server && pnpm exec vitest run src/__tests__/cloud-posthog-config.test.ts src/__tests__/cloud-posthog-browser.test.ts src/__tests__/auth-routes.test.ts src/__tests__/posthog-direct-transport.test.ts`: 4 files, 124 tests pass. - `cd packages/shared && pnpm exec vitest run src/validators/access.test.ts`: 22 tests pass. - `pnpm exec vitest run -c tests/runner-e2e/vitest.config.ts source-sdk-public-inputs`: 13 tests pass. - Shared, server and UI package typechecks pass. Server and UI builds pass. - Token gates, module boundaries, the test budget check for changed suites, and `git diff --check` pass. - Long-preview regression proof: four rendered tests initially fail on `9f2039d` because it passes 128,005 characters to conversion. They now verify a 2,048-character input bound while calling the real helper, a maximum 180-character summary, and complete replay masking for capped sources. Inputs include backticks, stars, underscores and brackets. The earlier short-preview credential tests still pass. - Review regression proof: three rendered task-preview tests expose GitLab, GitHub and OpenAI fixture credentials on `7533fbe`; they pass after preserving token punctuation. An 80,000-hyphen input took about 3.25 seconds on that head and failed the 500 ms bound. The single-pass flag scan passes the guard with a 512 KiB prefix followed by a real password flag. - Regression proof: the added tests first failed on the prior implementation, including work content visible with a missing or false opt-in and after withdrawal. They pass with the new gate. - `pnpm verify`: exit 2, broader verification required because the analytics document is a global CI input. Required CI supplies repository-wide coverage. An earlier exit 1 identified stale shared-source pins; the maintained generator refreshed them and the 13 pin tests pass. - Direct UI `tsc --noEmit` initially lacked generated Storybook catalogs in the fresh checkout. The maintained UI typecheck generates those files and passes. A preliminary Vitest `--project ui` invocation matched no named project; the commands above use the package configuration. - Secret scan reviewed the commit diff. Gitleaks reports two generic-key matches in the generated source-pin registry; both equal the corresponding Git blob hashes. The remaining commit content scans clean. No run artifacts or private deployment data are committed. CI follow-up on `45023e6`: [server shard 10/20](https://github.com/paperclipai/paperclip/actions/runs/45560174673/job/139021948661) timed out twice at the existing 15-second limit in `issue-document-batch.integration.test.ts`, test "rejects many large documents using a size-only query before loading any bodies". The test prepares 200 half-MiB documents and later rewrites them. The same test and server code are unchanged from `9f2039d`, where [the same shard passed](https://github.com/paperclipai/paperclip/actions/runs/45558505382/job/139016469065) and this test took 8.39 seconds. The intervening commit changes UI and documentation only. The exact failing case passes locally on the current head with `cd server && pnpm exec vitest run src/services/native-runtime/issue-document-batch.integration.test.ts -t 'rejects many large documents using a size-only query before loading any bodies'` (one passed, 15 skipped). This shows local recovery; it does not establish the cause of the CI timeout. A targeted shard rerun was requested, but GitHub refused because the workflow is still running. No test limits or product code have been changed to hide the failure. This initial failure is retained here as evidence; the successful second-attempt outcome is recorded below. CI follow-up, second shard: [server shard 13/20](https://github.com/paperclipai/paperclip/actions/runs/45560174673/job/139021948654) failed `ai-connections.test.ts`, test "requires sign-in after the receiver process dies with an exchanged but unsaved token". The first attempt failed its wait for one token exchange and an advisory-lock waiter within 25 seconds. The automatic retry failed earlier because the first attempt had already inserted the fixed membership fixture. The suite, receiver helper and AI connection service are unchanged by this work. The [original PR head passed this shard](https://github.com/paperclipai/paperclip/actions/runs/45544519067/job/138970880217), with the same test taking 21.06 seconds. The exact case passes locally on `45023e6` with `cd server && pnpm exec vitest run src/__tests__/ai-connections.test.ts -t 'requires sign-in after the receiver process dies with an exchanged but unsaved token'` (one passed, 164 skipped). The cause of the missed CI wait remains unconfirmed. This local pass does not clear the failed CI result. Targeted reruns were initially blocked by GitHub while the workflow was running. See the successful second-attempt outcome below. CI recovery: [workflow attempt 2](https://github.com/paperclipai/paperclip/actions/runs/45560174673/attempts/2) completed successfully on unchanged head `45023e6`. Both previously failed shards now pass. No source edits, timeout increases, or test removals were needed. The original timeout and missed-wait causes remain unconfirmed; the earlier failures and comparison evidence above are preserved. Final acceptance uses the green current-head CI result together with the local checks and 5/5 review. Not run locally: repository-wide tests/builds or a live PostHog recording. The tests exercise the masking callback and UI state, not the externally loaded recorder. After deployment, compare a masked replay with the work-content flag unset against an opted-in eligible company. Then verify that Google/Slack or a hidden source keeps the same surfaces masked. Restart the server and reload open tabs after changing deployment environment values. ## Risks - The opt-in belongs to the host, not to the people who use the deployment. Nothing in this pull request asks or tells a user. A host that sets the flag must tell its users first. The plan for the hosted service is in #23338. - Enabling the new flag allows eligible work content to leave the instance in replay data. Leave it unset or set it to `0` to keep work content masked. No deployment or fleet policy is changed by this PR. - The flag does not bypass company eligibility checks or secret masking. Changing it affects future recording after the configuration reaches the browser; it does not remove previously recorded content. - Connection detection is a best effort. A custom MCP server with an unrelated name and URL, or credentials used directly by an agent, can carry Google or Slack data without appearing as a known source. - Secret redaction is a best effort. Unknown or unlabeled secrets, non-English labels, values on a later line or under a table header, and values outside bounded line context can be missed. Some ordinary values are over-masked. - Source changes can race with recording until the live update arrives. A missed update can extend that window to the five-minute refresh. Connection count and list queries can disagree briefly and then mask conservatively. - Hidden drafts and aggregators can keep harmless content masked. Text rendered during a source recheck stays masked until it renders again. The first visible state adds a full recording snapshot. - Task previews now inspect at most 2,048 source characters before conversion. Very long markup can produce an incomplete summary. Source-capped previews stay fully masked; opening the full task keeps the normal work-content policy. - Artifact card text previews stay masked in every company. Document card previews and cut task previews mask when a credential sits at or before the cut, so some replays show stars there while the full document shows. - Task titles, names and other previously visible surfaces remain visible and can contain copied customer text. New work-content surfaces must preserve company scoping. ## Model Used - Original implementation: Anthropic Claude Opus 5.5 (`claude-opus-5-5`) and Claude Fable 5.2 (`claude-fable-5-2`) through Claude Code, with shell, edits, tests and the original read-only exploration subagent. - Deployment configuration follow-up: OpenAI `gpt-6.1-sol` through the Codex, xhigh reasoning, shell, file edits and test tools. Context window size is not exposed by the runtime. No additional subagents. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Devin Foley <devin@paperclip.ing> Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Dotta <bippadotta@protonmail.com> |
||
|
|
07af22c57f |
feat(plugins): support agentless harness sign-in (#23392)
## Thinking Path > - Paperclip manages agents and the AI accounts they use. > - A company can connect an account before creating its first agent. > - Some plugin drivers can run sign-in in a dedicated sandbox. > - Core currently selects a saved agent for every plugin login. > - This change lets each driver declare that it can sign in without an agent. ## Linked Issues or Issue Description **Subsystem affected** Environment drivers, managed AI connections, and the agent setup UI. **Current behavior** A company with zero agents cannot start a provider login on a plugin environment, even when that driver can provision a temporary environment. **Proposed behavior** A driver can declare `supportsAgentlessLogin`. Core uses this capability when it selects a login target and acquires the lease. Drivers that omit it retain the existing agent selection. **Reason and benefit** Operators can finish connecting the account before they configure its first agent. **Additional context** The driver capability follows the per-driver adapter declaration in #22827. The onboarding flow keeps the agent readiness check from #23383. ## What Changed - Added the optional capability to the manifest, capabilities response, and login UI. - Kept company and driver validation at sign-in and lease acquisition. - Applied the plugin device-login deadline to sessions with no agent. Ordinary task provisioning keeps its existing contract. ## Verification - 122 tests passed across shared capabilities, environment target resolution, lease construction, device-login HTTP routes, and session lifecycle. - The server typecheck passed. - The SDK input registry matches the source revision. `pnpm verify` requests broader CI coverage for that registry. - After merging the current base, 82 focused tests passed, including the onboarding tests. The UI typecheck passed. All required GitHub checks passed. ## Risks Drivers must advertise this capability only when they can run and clean up a login without an agent. Existing manifests retain their previous behavior. No database migration is required. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI Codex, GPT-6, with local code inspection and test execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
ce2e6ccc00 |
feat(ui): surface channel, key-values, lease, and schema elements on tasks (#23382)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip tasks and comments now store channel, key-value, claim lease, profile attribution, and structured schema fields on existing issue and comment tables (`channelId`, `kvLabels`, `schemaBlocks`, `resultSchemaRef`, `createdByProfile`, `actorProfile`, and claim lease fields). > - Existing board task views (`IssueProperties`, `MarkdownBody`, `CommentThread`, `IssueChatThread`, and `IssueDetail`) do not yet display these fields, and canonical `/api/issues/:id` routes do not resolve `channelPath` or strip `claimTokenHash` at serialization time. > - Users and reviewers cannot see channel provenance, key-values, active or expired claim leases, `--as <profile>` attribution, or structured `schema=<name>@<version>` blocks when they open a task in the UI. > - This pull request synchronizes the shared `Issue` and `IssueComment` contracts, resolves `channelPath` only when channel access and actor scopes allow it, strips `claimTokenHash` from issue responses, renders channel, key-values, lease, result schema, and structured schema cards across existing task views (only when set), and adds production-component Storybooks. > - The benefit is that existing task surfaces show channel, lease, key-value, profile, and schema state cleanly in place without cluttering standard tasks or adding a separate Channels navigation item, while preserving secret isolation on claim tokens. ## Linked Issues or Issue Description Refs #23329 Refs #23330 **What existing behavior does this improve?** Existing task detail, properties, Markdown body, comment thread, chat thread, and `/api/issues` HTTP serialization for tasks that carry channel, claim lease, key-value, profile attribution, or structured schema data. **Subsystem affected** Cross-cutting (`packages/shared`, `server/`, `ui/`, `ui/storybook/`, and `docs/api/`) **Current behavior** Canonical `/api/issues` routes return raw issue columns without a resolved `channelPath` and include `claimTokenHash: null` on the response shape. In `ui/`, `IssueProperties` omits channel provenance, `Key-values` editing, claim lease status, `resultSchemaRef` verification, and `--as <profile>` creator attribution. `MarkdownBody` renders ```` ```json schema=<name>@<version> ```` blocks only as plain code blocks, and comment threads show `local-board` or generic user labels instead of `actorProfile` and omit comment-level key-values. **Proposed behavior** `Issue` and `IssueComment` expose safe coordination and schema fields in `@paperclipai/shared`. Server issue routes strip `claimTokenHash` from serialized issue objects and resolve `channelPath` in batch via `findInaccessibleChannelIds` only when actor scopes and channel membership succeed (with zero extra SQL queries when `channelId` is null). `IssueProperties` mounts cohesive task property rows (`structured-task-rows.tsx`) strictly when set: `#<channelPath>` badge on `Channel`, inline `Key-values` add/edit/remove with CAS preconditions (`PATCH /api/issues/:id/kv-labels`), active vs expired `Lease` status with inline status dot and live countdown, `Result schema` matching status, and creator `--as <profile>` attribution. `MarkdownBody` and task discussion/chat threads render token-styled `SchemaBlockCard` views (`finding@1`, `test-report@1`, `git-commit@1`, `pull-request@1`, and custom `<name>@<version>` schemas) with a `Structured` / `JSON` toggle, deduplicated standalone `schemaBlocks`, `--as <actorProfile>` attribution, and comment key-value pills. Four production-component Storybooks document these states under `tasks-channels-leases-and-schemas`. **Reason and benefit** Agents and CLI workflows coordinate through existing Paperclip tasks and comments. Surfacing channel provenance, claim leases, key-values, profile attribution, and typed schema blocks directly on existing task views (and hiding those rows completely when unset) lets people inspect and edit structured task state in place without introducing new top-level navigation, while guaranteeing that `claimTokenHash` never leaves the server. **Breaking changes** None for external callers. `claimTokenHash` is omitted from serialized `/api/issues` JSON responses as a security invariant, and `channelPath` (`string | null`) is added on canonical issue read and update responses. ## What Changed - `packages/shared/src/types/issue.ts` and `tests/runner-e2e/source-sdk-public-inputs.json`: expose safe fields on `Issue` (`channelId`, `channelPath`, `createdByProfile`, `kvLabels`, `schemaBlocks`, `resultSchemaRef`, `claimEpoch`, `claimHolderAgentId`, `claimHolderUserId`, `claimHolderProfile`, `claimLeasedAt`, `claimLeaseExpiresAt`, `claimAttemptCount`) and `IssueComment` (`actorProfile`, `kvLabels`, `schemaBlocks`), never `claimTokenHash`, and synchronize the SDK public input registry pin. - `server/src/services/issues.ts`, `server/src/routes/issues.ts`, and `docs/api/issues.md`: omit `claim_token_hash` from SQL issue selections and `withIssueLabels`, strip `claimTokenHash` on HTTP serialization across issue routes, clear `kvLabels` and `schemaBlocks` on tombstoned comments, resolve `channelPath` in batch via `resolveHeadlessActor` and `findInaccessibleChannelIds` (zero extra SQL queries when `channelId` is `null`), and document the API response contract. - `server/src/__tests__/fixtures/issue-detail-response.json`, `server/src/__tests__/issue-activity-events-routes.test.ts`, and `server/src/__tests__/headless-channels-schemas-batch.test.ts`: update issue detail and update response snapshots (`channelPath: null`, no `claimTokenHash`) and add route contract coverage for `channelPath` visibility, scope enforcement, comment fields, and `claimTokenHash` omission. - `ui/src/api/issues.ts` and `ui/src/api/issues.test.ts`: add `issuesApi.updateKvLabels` targeting `PATCH /api/issues/:id/kv-labels` with CAS precondition normalization (`set`, `unset`, `if`) and unit test coverage. - `ui/src/components/issue-properties/structured-task-rows.tsx` and `IssueProperties.tsx`: add `IssueChannelRow`, `IssueKvLabelsRow` (`Key-values` with inline edit, remove, `+ Add`, CAS preconditions, touch-safe 16px inputs, and complete omission when empty), `IssueClaimLeaseRow` (inline status dot, live countdown, and omission when unset or released), `IssueResultSchemaRow` (unwrapping `InfiniteData` and identifier-keyed comment query caches, plus distinguishing `"unverified"` truncated scans from `"missing"`), and `IssueProfileAttributionRow`. - `ui/src/components/SchemaBlockCard.tsx`, `ui/src/lib/schema-block-utils.ts`, and `ui/src/components/MarkdownBody.tsx`: parse ```` ```json schema=<name>@<version> ```` fences (plus `{ schema, data }` JSON envelopes) via a static remark plugin and a bounded linear $O(N)$ single-pass CommonMark fence scanner (no multi-line backtracking regexes); render semantic-token cards for `finding@1`, `test-report@1`, `git-commit@1`, `pull-request@1`, and custom `<name>@<version>` blocks with `Structured` / `JSON` toggle, `https://`-only link safety, malformed-JSON code-block fallback, and iterative stack-safe `schemaBlocks` deduplication. - `ui/src/components/CommentStructuredMeta.tsx`, `CommentThread.tsx`, `IssueChatThread.tsx`, `TaskChatBubble.tsx`, `TaskChatDescriptionBubble.tsx`, `IssueDetail.tsx`, and chat adapters: render `--as <actorProfile>` attribution, comment-level key-value chips, and unfenced `schemaBlocks` across classic and chat task threads. - `ui/storybook/stories/tasks/channels-leases-and-schemas.stories.tsx`: add `ChannelTaskPropertiesActiveLease`, `ExpiredLeaseProperties`, `BuiltInAndCustomSchemaBlocks`, and `ChannelTaskThreadEndToEnd` stories registered under `tasks-channels-leases-and-schemas`. - `ui/src/components/issue-properties/structured-task-rows.test.tsx` and `ui/src/components/SchemaBlockCard.test.tsx`: add unit tests covering unset-row omission on standard tasks, single-badge channel provenance, CAS key-value mutations and `409` conflict rollback, inline lease status dots and countdown expiry, `InfiniteData` comment unwrapping, structured schema cards, malformed JSON fallback, linear $O(N)$ scanning on 5,000 unterminated JSON fences, newline-clamped markdown bounds, and deep deduplication. ## Verification - `pnpm --filter @paperclipai/shared build` — passed. - `cd server && node scripts/typecheck-layers.mjs` — passed (0 errors across all layers and test trees). - `cd server && npx vitest run src/__tests__/service-read-disconnect-retry.test.ts src/__tests__/issue-activity-events-routes.test.ts src/__tests__/issue-detail-statements.test.ts src/__tests__/headless-channels-schemas-batch.test.ts` — passed (54/54 tests). - `pnpm --filter @paperclipai/ui typecheck` — passed (0 errors). - `cd ui && npx vitest run src/components/issue-properties/structured-task-rows.test.tsx src/components/SchemaBlockCard.test.tsx src/api/issues.test.ts src/lib/issue-chat-messages.test.ts src/components/task-chat/task-chat-adapter.test.ts` — passed (115/115 tests). - `node scripts/check-token-gates.mjs`, `node scripts/check-test-budget.mjs`, `node scripts/check-module-boundaries.mjs`, and `node scripts/check-query-error-rendering.mjs` — all passed. - `node scripts/storybook-catalog.mjs && node scripts/storybook-catalog.mjs --check` and `node --test scripts/check-maps.test.mjs scripts/storybook-catalog.test.mjs scripts/storybook-feature-index.test.mjs` — passed (30/30 tests). - `pnpm --filter @paperclipai/ui build-storybook` — passed and verified built story IDs (`tasks-channels-leases-and-schemas--channel-task-properties-active-lease`, `tasks-channels-leases-and-schemas--expired-lease-properties`, `tasks-channels-leases-and-schemas--built-in-and-custom-schema-blocks`, `tasks-channels-leases-and-schemas--channel-task-thread-end-to-end`). ## Risks - Low risk. Standard board tasks with unset `Channel`, `Key-values`, `Lease`, and `Result schema` omit all four property rows completely, preserving existing `IssueProperties` layout and SQL query count (`0` extra queries when `channelId` is `null`). - Fenced code blocks without `schema=<name>@<version>` metadata (or with invalid JSON) fall back directly to the existing `CodeBlock` renderer. ## Model Used - Google Gemini (`gemini-3.1-pro` / Antigravity agentic coding runtime with extended thinking, code search, file editing, and terminal verification tools). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
176cb8eee2 |
test(e2e): retain safe Skill Studio failure steps (#23108)
## Thinking Path > - Paperclip lets people manage agents and their saved work. > - Product E2E tests check a skill from creation through a saved Studio edit. > - A browser failure can happen after the agent completes its work. > - The report replaces each raw browser error with one general failure code. > - That code does not show which Studio step failed. > - This change keeps a fixed step code and excludes raw browser data. ## Linked Issues or Issue Description **What happened?** A skill edit journey can fail after skill creation passes. Its saved result has only `journey_operation_failed`. It cannot distinguish a missing task card from an unloaded file or a failed save. Raw browser errors can contain private content, so copying those errors into reports is unsafe. **Expected behavior** Keep a fixed code for the failed step. Keep the failed grade. Exclude browser messages, URLs, skill contents and nested error causes. **Steps to reproduce** Run the shared browser helper with a missing skill card or an editor whose saved file never loads. Before this change, both errors lose their step when the Product E2E report grades them. Refs #18305, which fixed delayed file loading and is already present. #19095 changes a separate frozen catalog observer. Neither supplies these shared journey failure codes. This patch does not establish the cause of an earlier hosted failure. ## What Changed - Give the shared Studio helper a closed set of step codes. - Keep the original browser actions, assertions and save/readback checks. - Test a missing card and an unloaded file with real Chromium. - Check that the normal journey failure formatter keeps the code and drops private error text. - Document the report codes. Classic and Cloud callers share the helper. ## Verification - On the old code, the browser suite had 2 failures and 2 passes. The failures exposed the missing step codes. - With the repair, all 4 browser checks pass. Immediate and delayed file loading still preserve the original content, save the edit, reload and read it from the task card. An unloaded file still receives no input or save. - All 5 `journey-failure.test.ts` checks pass. The new case runs the helper and the real failure formatter together. - Commands: `pnpm exec playwright test --config tests/runner-e2e/playwright-support.config.ts skill-studio-flow.spec.ts`; `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts journey-failure.test.ts`. - `pnpm test:e2e:runner:typecheck` passes. Current-head CI and reviews remain required. - `pnpm verify` could not select tests: the managed Git storage guard rejects `git ls-files`. This is not a pass. Focused commands ran directly. - These are controlled browser checks on Linux with synthetic data. No hosted provider run, staging recovery or full-plan pass is claimed. ## Risks The code names identify a failed step. They do not establish its root cause. The helper drops raw errors and their causes to protect private data. The change affects both callers of this shared helper. It adds no retries and changes no selectors, deadlines, grades, selected cases or protected pins. ## Model Used OpenAI Codex, GPT-6 family, with reasoning and code execution. The host does not expose the exact runtime model ID or context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes: #` / `Refs: #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
f14929d21b |
test(e2e): retain bound question-run failure evidence (#23041)
## Thinking Path > - Paperclip helps people manage AI agents for work. > - Product E2E tests check real tasks and their saved results. > - The question journey must keep evidence when an agent run fails. > - It currently rejects that run before the first stable checkpoint is saved. > - The private report then has checks but no run failure code. > - This PR saves a small, bound failure receipt before rejection. > - The test still fails. The receipt helps the next diagnosis. ## Linked Issues or Issue Description **Describe the bug** When a native run fails before the first question checkpoint, `readClarificationState` throws `agent_run_failed`. The final `clarification.json` has no checkpoints. The report cannot show the run's machine error code. **Steps to reproduce** 1. Give the question journey an owned native task with a terminal failed run. 2. Read the first question state. 3. Inspect the private report after the journey fails. **Expected behavior** Keep a private receipt with the bound task and run IDs, status, and machine error code. Preserve the failed verdict and the empty checkpoint list. **Additional context** This repairs missing evidence. It does not repair or establish the cause of an agent failure. The reference-grading repair in #22949 is separate and remains unchanged. ## What Changed - Split binding checks from outcome checks in the shared journey validator. Check every run's company, task, agent, model, and environment before retaining a failure. Existing consumers still use the full validator. - Save `clarification-run-failure.json` in the private story directory when the question journey rejects a failed run. Keep only IDs, status, and a bounded machine code. Exclude raw errors, prompts, and provider state. - Keep the original failure if the receipt write fails. Add a fixed secondary cause code. - Add failure, binding, privacy, and final-grading regressions. Document the private receipt. ## Verification - Red: the initial regression had 6 failures and 4 passes on the old code. It reproduced the lost receipt and the first-error binding gap. - Green: 175 tests in 9 affected agent and clarification support files pass with the repository's Product E2E Vitest config. - `pnpm test:e2e:runner:typecheck` passes. - `pnpm verify` could not select tests. The managed Git storage guard rejects `git ls-files`. The focused checks above ran directly. Final CI must supply its required coverage. - The journey regression calls the real observer and validator, saves the private files, and reads them after final grading. It checks that all 11 checks still fail and no question checkpoint is invented. The task-creation UI boundary is simulated. - No live provider run was started. This is local report-path evidence, not a new staging pass. The reviewed harness must be adopted and checked through the authorized QA process after merge. ## Risks Low scope. Only Product E2E support code and its docs change. The shared validator now checks all bindings before it reports the first failed outcome. Foreign evidence still fails closed. The existing outcome, run limit, cancellation, and recovery checks remain in place. The private receipt is not added to the public report. ## Model Used - OpenAI Codex, based on GPT-6, with reasoning, tools, and code execution. This run does not expose a more specific provider model ID. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
ab099dc379 |
feat(plugin-sdk): declare supported adapters per environment driver (#22827)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Environment plugins can run agent tasks on remote computers, and can run the provider sign-in for those computers > - Core decides which adapters can sign in on a plugin environment from a fixed Claude and Codex rule and a `supportsCodexLogin` flag > - A plugin cannot say which adapters it supports, so Grok has no sign-in on a plugin computer, and a plugin can run an adapter that it cannot sign in > - This pull request lets a Runner task driver declare its supported adapters, and makes support mean the full adapter lifecycle: runs and, where Paperclip offers one, sign-in > - The benefit is one extensible support contract per driver, with no partial matrix, and Grok subscription sign-in on plugin computers ## Linked Issues or Issue Description **Subsystem affected** Plugin SDK environment drivers, plugin sign-in (login pseudo-terminal), plugin Runner task credentials, and agent Runner selection. **Problem or motivation** Core allows plugin-computer sign-in only for Claude, and for Codex when the plugin can read back a credential file. The flag for that is named `supportsCodexLogin`, which does not describe what it does. A plugin cannot advertise which adapters it supports. Grok has a device sign-in in Core, but it has no sign-in on a plugin computer, and a Grok subscription cannot reach a plugin task. A plugin can also run an adapter that has no sign-in on that plugin. This gives a partial support matrix. **Proposed solution** A Runner task driver declares `supportedAdapters`. Support for an adapter means the full lifecycle. The driver must run the adapter, and it must run the Paperclip sign-in when the adapter has one. Core validates the declaration in the manifest, and Core checks it again against the methods of the running worker. An adapter that fails either check is not offered for sign-in, for save, or for runs. The sign-in contract moves to one shared map, so a new adapter sign-in is one entry in that map. **Alternatives considered** A separate per-capability table (runs, sign-in, credential read-back) was rejected. It permits the partial matrix that this change removes. The existing sign-in map and credential sets already contain the necessary data. **Additional context** Related open pull requests: Refs #14001 (Kubernetes plugin login pseudo-terminal), Refs #21327 (Grok device link in the sign-in UI). ## What Changed - Environment drivers can declare `supportedAdapters`. The manifest is rejected when the list has duplicates, when the driver is not a Runner task driver, or when it lists an adapter that has a Paperclip sign-in and the driver does not declare the login pseudo-terminal with `creationOperationVersion: 1`. - Core removes a listed adapter when the running worker does not implement the methods it needs (task methods, and sign-in methods with credential read-back for file sign-ins). Core logs a warning one time for each removed adapter. - `supportsCodexLogin` is replaced by `loginAdapters`, the adapters that can sign in on that environment. Drivers without `supportedAdapters` keep the current behaviour: Claude, and Codex when the worker reads back credentials. - A new shared sign-in map holds the adapters that Paperclip signs in and where each sign-in leaves its credential (terminal output or a file). Manifest validation, server admission, environment presentation, and the Connections sign-in step use this map. Two hard-coded Claude and Codex lists are removed. - Credential read-back accepts any file sign-in key and returns `{ kind: "auth-file", content }`. - The plugin task credential `codex-auth-json` becomes `{ type: "auth-file", provider: "codex" | "grok", content }`. - A Grok subscription is delivered to plugin tasks as an `auth-file` credential. A refreshed Grok file returns to the account through the existing write-back. The write-back record now stores its provider. - On a driver that lists adapters, Core refuses to save, offer, or submit a Runner harness that is not on the list. The error is `agent_runner_unavailable`. - The SDK README and the plugin environment task and AI connection docs describe the contract. ## Verification - `pnpm --filter @paperclipai/server typecheck`, `pnpm --filter @paperclipai/plugin-sdk typecheck`, and `pnpm --filter @paperclipai/ui typecheck` pass. - Targeted server tests pass: plugin environment driver capabilities, plugin login credential, plugin Runner credentials, plugin task credential write-back (Codex and Grok, with a provider mismatch case), environment task runtime submit gating, agent Runner selection, login environment, login session runtime, device login routes and service, setup token, login command, and adapter routes. - Plugin Runner probe and integration tests pass (run from the repository root). - Shared tests (77) and plugin SDK tests (129) pass, including the new manifest validation cases. - UI AI connection tests (67) pass. - Not run locally: the full suite (CI runs it), a render test for the Connections credential step, and an end-to-end route test for computer device sign-in admission. Unit tests cover that admission. ## Risks - Breaking change for plugins that use the plugin SDK task credential or credential read-back. `codex-auth-json` becomes `auth-file`, and the read-back result kind changes. A plugin must update to the new SDK shapes in the same release. - Plugins that do not declare `supportedAdapters` keep the current behaviour. No warning is logged for them. - `supportedAdapters` applies to Runner task drivers only. Sandbox providers reject the field. Support for sandbox providers is a separate change. - The new-agent screen does not offer sign-in on a plugin computer. That sign-in needs a target computer, and the Connections flow selects it. This is the current behaviour for Claude and Codex. - No migration. The write-back record treats a missing provider as Codex, so records written before this change still work. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, test runs) and extended thinking. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
caaa013a69 |
fix(e2e): wait for reset preparation and repository recovery (#23288)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Product E2E tests check real user work through the app and native agents. > - A chat reset gets its reset marker during run preparation. > - The observer can count that active reset as extra model work before preparation ends. > - The repository observer also omits the deadline needed to recognize a scheduled same-run recovery. > - This pull request keeps both observations open until the existing bounded transition completes. > - The final success checks still require the original run counts, saved results, and evidence. ## Linked Issues or Issue Description **What happened?** The chat observer can throw `chat_continuity_extra_run` while `/new` is queued or running without its reset marker. The repository observer throws `agent_run_failed` for an exact-session recovery that the server has already scheduled. **Expected behavior** Observe each transition under the original campaign deadline. Require the same final reset receipt, model turn count, completed repository runs, and artifact checks. An active or failed run must never count as a pass. **Steps to reproduce** 1. Return an unmarked queued or running reset between the second model reply and the completed reset receipt. 2. Run the chat journey observer. Before this change it reports extra model work. 3. Return a bound native repository run with `retryable_failure` and an eligible `retry_scheduled` projection. Before this change the observer rejects it before its scheduled recovery. Related: https://github.com/paperclipai/paperclip/pull/18784 and https://github.com/paperclipai/paperclip/pull/22826. The latter adds the shared recovery rule. This change supplies the repository caller's missing deadline. ## What Changed - Count excess unmarked provider runs after they succeed. Keep the existing reset count, scope, run cap, deadline and final grading checks. - Supply the repository campaign deadline to the existing native recovery validator. - Add observer regressions for queued and running reset preparation, completed extra work, immediate failed/cancelled rejection, scheduled repository recovery through success, exhausted or late recovery and the original deadline. ## Verification - Chat regression before the fix: 2 failed and 16 passed. Both failures report `chat_continuity_extra_run`. - Repository regression before the fix: 2 failed and 1 passed. Both failures report `agent_run_failed`. - After the fixes: 109 tests pass in five affected observer, grading and recovery files. - `pnpm test:e2e:runner:typecheck` passes on the final source. - `pnpm verify` cannot select tests because the managed Git storage guard rejects `git ls-files`. The focused command above supplies local test evidence. Final-head CI 46425283547 passes the selected Runner support, package, static, typecheck, policy and verification gates. General/build jobs are path-skipped. - The real observer functions ran with simulated API/browser boundaries. No new hosted provider run or deployment was made. A fresh hosted journey with the reviewed harness is still required for staging acceptance. ## Risks The chat observer can wait longer before it rejects active extra work. The original deadline and four-run cap still bound it. A completed extra provider run remains fatal. Failed or cancelled chat runs already fail in the reader before the excess-work predicate; tests prove first-read rejection with no new message. Repository recovery uses the existing shared eligibility rules; terminal, exhausted, foreign or late recovery still fails. This change does not repair or explain an underlying provider timeout. No prompt, grading rule, test selection, budget, pin or production behavior changes. ## Model Used OpenAI Codex, GPT-6 family, with reasoning and code execution. The exact model build is not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
00a792999c |
test(e2e): retain failed agent-settings task identity (#23371)
## Thinking Path > - Paperclip lets people manage agents and their saved work. > - Product E2E tests check whether saved agent instructions affect the next task. > - A failed work run must keep a failed test result. > - The observer currently saves task identity only after the task completes. > - A failed run leaves no task or run ID in its retained settings evidence. > - This change saves the observed identity before the failure check. > - Engineers can then find the failed run without storing raw instruction or provider data. ## Linked Issues or Issue Description **What happened?** The saved-instructions journey reads a failed native run and throws `agent_settings_native_run_failed`. Its private report then writes `issueId: null` and `runIds: []`. The observer already read the task and run, but loses their identity because it fills completed evidence only after a successful wait. **Expected behavior** Keep the created task ID, requested run IDs and observed status/native phase. Keep the test failed. Do not record instruction text, raw errors, output excerpts, account configuration or provider payloads. **Steps to reproduce** Run the existing agent-settings flow fixture with a failed native run. Read `agent-settings-observations.json`. Before this change its task ID is null. The new regression fails on that value. A denied run-detail read also loses its requested identity. Related work: #23041 retains question-journey failure evidence. #23108 adds Skill Studio browser-step codes. #23288 changes reset and repository observation waits. None covers the saved-instructions observer. This change does not repair the underlying native run failure. ## What Changed - Keep the created task identity before the first task observation. - Save requested run IDs before detail reads. Keep status and native phase from each completed read. - Keep this diagnostic separate from completed evidence and all grading checks. - Test failed runs, denied detail reads, successful completion and raw-data exclusion. - Document the private evidence fields. ## Verification - The new failed-run assertion failed before the fix: expected task ID `task`, received null. The other nine flow checks passed. - After the fix, 89 checks pass in `agent-settings-flow.test.ts`, `agent-settings-evidence.test.ts` and `observation-read.test.ts`. - Command: `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts` with those three files. - `pnpm test:e2e:runner:typecheck` passes on the final source. - The real observer and private file writer ran on Linux with simulated browser/API boundaries. Failed work still fails. A denied detail read keeps an empty observed-runs list. No second settings save occurs after either failure. - `pnpm verify` could not select tests because the managed Git guard rejects `git ls-files`. This is not a pass. Preflight installed dependencies and built required packages, then could not find Cargo. Focused checks ran directly. - No hosted provider rerun or deployment was made. Local evidence does not establish a staging pass. Hosted acceptance requires approved harness adoption. - Final-head CI and automated reviews are pending. ## Risks The new record contains private task/run IDs and lifecycle fields. It uses an explicit field projection and does not copy the full run object. It cannot make a pending or failed run pass. The change adds no work runs, retries, requests, settings edits or budget. Existing grading, cleanup and public projection remain in place. This is a reporting repair; the underlying provider or infrastructure cause remains open. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, tool use and code execution. The runtime does not expose an exact model ID or context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes: #` / `Refs: #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
ea56320e10 |
feat(board): add headless channels, fenced task queues, paperclipai/sdk, and pc CLI (#23330)
<!-- Write all pull request text in Simplified Technical English (ASD-STE100): short sentences, one instruction per sentence, simple approved vocabulary, and the active voice. --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Multi-agent workflows and terminal scripts often need lightweight shared channels, structured task queues, and scriptable CLI/SDK primitives without building a full project UI first. > - Today, Paperclip issues require board-oriented setup, lack lazy hierarchical channels, lack fenced task claim leases, and lack a zero-dependency TypeScript SDK and short CLI alias for fast script coordination. > - Without fenced leases, blocking queue claims, CAS key-value labels, and race-free event streaming, multiple headless workers collide on shared work or fall back to wasteful polling loops. > - This pull request adds headless channels, versioned JSON schemas, topological `plan.json` batch creation, fenced task queues with `FOR UPDATE SKIP LOCKED` claims, CAS key-value labels, one-line ask/confirm interactions, SSE event streaming, `paperclipai/sdk`, and the `pc` CLI with `paperclipai up`. > - The benefit is zero-ceremony, machine-readable, race-safe coordination across terminal agents, CI scripts, and local Paperclip servers while staying compatible with existing Web UI issue threads. ## Linked Issues or Issue Description **Subsystem affected** Cross-cutting (`packages/db`, `packages/shared`, `server/`, `cli/`, `doc/`, `skills/`) **Problem or motivation** Agents and terminal workflows need a fast way to post updates, queue DAG tasks, claim work without double-execution, ask humans for approval, and wait on board events without browser setup or polling loops. Existing Paperclip routes assume UI-driven projects, lack fenced claim leases for pools of workers, and lack a minimal `pc` CLI and `paperclipai/sdk` client. **Proposed solution** Build a headless coordination layer directly on top of Paperclip `issues` and `issue_comments` using `issues.scope = 'channel'`: - **Database & Contracts (`packages/db`, `packages/shared`)**: Add `0511_pale_kronos.sql` (`issues.scope`) and `0512_stormy_the_hood.sql` for lazy hierarchical `channels`, `channel_access_members`, immutable `company_schemas`, monotonic `board_events`, `scheduled_board_posts`, `issue_batch_idempotency_keys`, scoped `board_api_keys`, `agent_identity_policy`, `kv_labels`, `schema_blocks`, and fenced claim leases. Export Zod contracts, DAG sorting, KV CAS helpers, and the zero-dependency `paperclip()` SDK (`packages/shared/src/sdk/`), including an in-memory test backend. - **Server APIs & Workers (`server/`)**: Add routes and services for progressive `--as` actor resolution (`open_local_profiles`, `delegated_profiles`, `strict_agent_keys`), `pc agent connect` auth challenges, lazy channels, CAS `kv-labels`, versioned schemas, topological batch creation, `FOR UPDATE SKIP LOCKED` pool claims with fenced TTL renewal/release/complete/fail, one-line `ask`/`confirm`/`approve`/`reject` interactions, SSE cursor streaming (`events/wait`, `events/stream`), and sleep-aware lease expiry and scheduled post workers. - **CLI, Launcher & Docs (`cli/`, `doc/`, `skills/`)**: Expose the `pc` binary alias and `paperclipai/sdk` export, add the zero-prompt `paperclipai up` / `pc up` local launcher, add `pc` commands (`post`, `reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent connect/login`), add documentation (`doc/CHANNELS-AND-QUEUES.md`, `doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`), and add `skills/paperclip-lite/SKILL.md`. **Alternatives considered** - **Separate message and queue tables outside `issues`**: Rejected because channel posts and queued tasks would lose Paperclip identifiers (`PC-1`), comments, attachments, privacy ACLs, and direct Web UI issue URLs (`/<prefix>/issues/PC-1`). - **Advisory locks or polling loops for task workers**: Rejected because advisory locks drop on reconnect across laptop sleep, and polling wastes tokens and prevents database sleep. Fenced `(claimToken, claimEpoch)` TTL leases with `events/wait` and `waitSec` solve both safely. **Roadmap alignment** Extends core Paperclip agent orchestration and CLI workflows with a headless board, SDK, and queue primitive without altering existing Web UI board behavior. **Additional context** This PR builds on the `issues.scope` surface visibility foundation from #23329 (included as the base commit in this stacked branch so CI and reviewers can test the full integration against `master`). ## What Changed - **Schema & Migrations (`packages/db`)**: Added online-compatible migrations `0511_pale_kronos.sql` and `0512_stormy_the_hood.sql`, schema definitions (`channels.ts`, `company_schemas.ts`, `headless_board.ts`), and column extensions on `issues`, `issue_comments`, `companies`, `board_api_keys`, and `cli_auth_challenges`. - **Shared Contracts & SDK (`packages/shared`)**: Added `packages/shared/src/headless/*` (channels, events, identity, labels, leases, DAG plans, schemas) and `packages/shared/src/sdk/*` (`paperclip()` client, env loader, SSE parser, and in-memory backend). - **Server Routes & Services (`server/`)**: Added `headless-channels-schemas.ts`, `headless-queues-events.ts`, `headless-identity.ts` routes and supporting services (`headless-channels.ts`, `headless-common.ts`, `headless-events-schedules-interactions.ts`, `headless-identity.ts`, `headless-labels-batch.ts`, `headless-schemas.ts`, `headless-task-queue.ts`), plus `issues.scope` visibility isolation and `board-auth.ts` extensions. - **CLI & SDK Export (`cli/`, `scripts/`)**: Exposed `pc` bin alias and `paperclipai/sdk` entrypoint, added `up.ts` zero-prompt launcher and `cli/src/commands/board/*` commands (`post`, `reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent`). - **Docs, Skill & Runner Registry (`doc/`, `skills/`, `tests/runner-e2e/`)**: Added `doc/CHANNELS-AND-QUEUES.md`, `doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`, plan docs, `skills/paperclip-lite/SKILL.md`, and synchronized `tests/runner-e2e/source-sdk-public-inputs.json`. ## Verification - `pnpm --filter @paperclipai/shared build` — passed. - `pnpm --filter @paperclipai/db check:migrations` — passed (`0511_pale_kronos.sql` and `0512_stormy_the_hood.sql` verified online-compatible, 2 new migrations since `630cf0423024`, none blocked). - `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD) --check` — passed (`598` inputs, `changed: false`). - `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/source-sdk-public-inputs.test.mjs` — 13/13 tests passed. - `node scripts/check-maps.mjs` — passed (`35` areas, `192` capability IDs aligned). - `pnpm exec vitest run packages/shared/src/headless/headless.test.ts packages/shared/src/sdk/sdk.test.ts cli/src/__tests__/headless-board-cli.test.ts` — 3 files, 22/22 tests passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-scope-visibility.test.ts src/__tests__/headless-channels-schemas-batch.test.ts src/__tests__/headless-identity-auth.test.ts src/__tests__/headless-queues-leases-events.test.ts src/__tests__/headless-e2e-sdk-cli.test.ts` — 5 files, 25/25 tests passed. - `pnpm --filter @paperclipai/shared typecheck && pnpm --filter @paperclipai/db typecheck && pnpm --filter @paperclipai/server typecheck && pnpm --filter paperclipai typecheck` — all passed. - `pnpm --filter paperclipai build` — passed. ## Risks - **Two new migrations (`0511`, `0512`)**: Both migrations are marked online-compatible (`NOT VALID` constraints validated afterwards, `CONCURRENTLY` index creation, idempotent statements for non-transactional execution) and checked by `check:migrations`. If #23329 lands separately with `0511` modified or renumbered, this branch will rebase on top cleanly. - **Large surface area (91 files)**: Changes are primarily additive new modules (`headless-*`, `cli/src/commands/board/*`, `packages/shared/src/headless/*`, `packages/shared/src/sdk/*`); existing Web UI board behavior remains isolated via `issues.scope`. - **Full repository Vitest suite**: Only the targeted headless, SDK, CLI, server, and runner-e2e pin suites ran locally after rebasing; full cross-package CI checks will validate the remaining suite. ## Model Used - Google DeepMind Antigravity (Gemini coding agent) with tool use and code execution ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
66a8aa7f7e |
feat(issues): add issues.scope surface visibility foundation (#23329)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Issues currently store human board tasks, agent-created operational
tasks, and persistent 1:1 Agent Chats in the same `issues` table.
> - Default board lists, counts, and Mine views previously relied on
ad-hoc creator and origin predicates to hide chats and separate agent
tasks.
> - Upcoming headless channels also need a clean way to isolate channel
issues from default board lists without inventing a separate task
entity.
> - This pull request adds an explicit `issues.scope` column (`board`,
`channel`, `agent`, `chat`) across the schema, shared types, service
filters, client filters, and issue routes.
> - The benefit is unified surface visibility filtering and explicit
scope derivation while keeping rolling deploys safe and preserving
existing Agent Chat and board behavior.
## Linked Issues or Issue Description
**Subsystem affected**
Cross-cutting (`packages/db`, `packages/shared`, `server/` REST API &
orchestration services, `ui/` client filters, and `docs/api/issues.md`).
**Problem or motivation**
Paperclip uses the `issues` table for human board work, automated or
agent-created operational work, and persistent 1:1 Agent Chats. Without
a dedicated surface-scope column, list, count, and Mine queries depend
on `conversationAgentId`, `createdByAgentId`, and `originKind` checks,
and there is no first-class way to isolate channel streams from default
board views.
**Proposed solution**
Add an `issues.scope` column (`board` | `channel` | `agent` | `chat`)
with `issues_scope_check` and composite indexes, expose `scope` in
shared types and Zod validators, derive default scope on issue creation
and batch imports, protect `chat` scope on 1:1 conversations and block
unauthorized agent `scope: "board"` writes across routes and
`issueService`, update server visibility queries and `applyIssueFilters`
on the client to honor `scope`, add `scope` filtering on `GET
/api/companies/:companyId/issues` and `/count`, and document the new
parameter in `docs/api/issues.md`.
**Alternatives considered**
1. Create separate tables for chats and channels. We ruled this out
because Paperclip builds assignment, comments, approvals, and execution
around a single `issues` model.
2. Add a DB `CHECK ((conversation_agent_id IS NULL) OR (scope =
'chat'))` constraint in this expand migration. We ruled this out for the
initial rollout because `ADD CONSTRAINT ... NOT VALID` still enforces
checks on new writes from older server instances that omit `scope`
during a rolling deploy.
3. Continue filtering only by `originKind` and `conversationAgentId` at
query time. We ruled this out because it cannot distinguish an explicit
chat-to-board handoff from a background agent task.
**Roadmap alignment**
Supports the **Agent Chat (including CEO Chat)** and **Work Queues** /
channel-intake directions in `ROADMAP.md` by separating surface
visibility on the shared `issues` table.
**Additional context**
This PR introduces the expand-phase schema, shared contract,
service-layer derivation, client filter handling, API filter foundation,
and API documentation. Follow-up work will build channel UI surfaces on
`issues.scope` and add the contract-phase DB check constraint after
older writers drain and re-backfill any rolling-deploy conversation
rows.
## What Changed
- Added `scope` (`board` | `channel` | `agent` | `chat`, default
`board`) to `packages/db/src/schema/issues.ts` with
`issues_scope_check`, `issues_company_scope_status_idx`, and
`issues_company_scope_updated_idx`.
- Added online-compatible migration
`packages/db/src/migrations/0511_simple_the_hunter.sql` (plus updated
Drizzle snapshot/journal and `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`
entry in `packages/db/src/client.ts`) to backfill existing `chat` and
`agent` rows in bounded 1,000-row primary-key cursor batches matching
`isAgentCreatedIssue`, validate `issues_scope_check` with `NOT VALID` +
`VALIDATE CONSTRAINT`, and build indexes `CONCURRENTLY`.
- Exported `ISSUE_SCOPES`, `IssueScope`, and `deriveDefaultIssueScope`
in `packages/shared`, added `scope?: IssueScope` to `Issue` and
`CompactIssue`, and added optional `scope` validation to
`createIssueSchema` and `updateIssueSchema`.
- Extracted `parseScopeFilter` and `surfaceScopeCondition` in
`server/src/services/issue-visibility.ts`, and updated `issueService`
(`create`, `importIssues`, `update`, `list`, `count`, blocked inbox
counts, and Mine views) to derive default scope (including `scope:
"agent"` for creatorless imports), enforce `chat` scope on 1:1
conversations, reject `scope: "chat"` on non-conversation issues, reject
unauthorized agent `scope: "board"` creation without handoff provenance,
default chat-to-board handoffs to `board`, preserve
`nonIdleSlackIssueCondition` on non-chat/channel scope filters, let
explicit `scope` filters override `includeAgentCreatedTasks=false`, and
exclude `chat` and `channel` rows from default board queries unless
filtered by `scope`, `q`, or `issueIds`.
- Updated `applyIssueFilters` (`isBoardVisibleByDefault`) in
`ui/src/lib/issue-filters.ts` so agent-created tasks with `scope:
"board"` (such as chat-to-board handoffs) stay visible by default.
- Added `scope` query parsing (`parseIssueListScopeQueryParam`
delegating to `parseScopeFilter`) and `assertActorMayWriteIssueScope`
across `POST /companies/:companyId/issues`, `POST /issues/:id/children`,
`POST /issues/:id/accepted-plan-decompositions`, and `PATCH /issues/:id`
in `server/src/routes/issues.ts`, included `scope` in `toCompactIssue`,
and documented `scope` in `docs/api/issues.md`.
- Added tests in `server/src/__tests__/issue-scope-visibility.test.ts`
and `ui/src/lib/issue-filters.test.ts`, updated
`server/src/__tests__/fixtures/issue-detail-response.json` and
`server/src/__tests__/issues-creation-visibility.test.ts`, and refreshed
`tests/runner-e2e/source-sdk-public-inputs.json`.
## Verification
- `pnpm --filter @paperclipai/db typecheck` (`check:migrations` + `tsc
--noEmit`), `pnpm --filter @paperclipai/shared typecheck`, and `pnpm
--filter @paperclipai/server typecheck` — passed on
`3db819854ff28ebc5e875b8d9d0daa74055bef35`.
- `npx vitest run packages/db/src/migration-snapshot-drift.test.ts
server/src/__tests__/issue-scope-visibility.test.ts
server/src/__tests__/issues-creation-visibility.test.ts
server/src/__tests__/company-portability-import-batching.test.ts
ui/src/lib/issue-filters.test.ts` — 5 files, 51 tests passed (1
pre-existing skip in `company-portability-import-batching.test.ts`).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
|