diff --git a/.github/workflows/canary-finalize.yml b/.github/workflows/canary-finalize.yml index 5950c076d2f..cc0b56a0142 100644 --- a/.github/workflows/canary-finalize.yml +++ b/.github/workflows/canary-finalize.yml @@ -32,7 +32,7 @@ jobs: name: Confirm canary on npm and tag it if: github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && github.ref == 'refs/heads/master' runs-on: ubuntu-latest - timeout-minutes: 45 + timeout-minutes: 75 permissions: contents: write actions: write diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 744eea46d2a..92c8aff2ece 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -638,7 +638,7 @@ jobs: (needs.smoke_nightly.result == 'success' || (needs.smoke_nightly.result == 'skipped' && github.event_name == 'workflow_dispatch' && inputs.dry_run)) runs-on: ubuntu-latest - timeout-minutes: 150 + timeout-minutes: 170 environment: npm-canary # The workflow-level concurrency group is per event, so a forced dispatch # nightly could otherwise overlap the scheduled one and race it to the @@ -927,7 +927,7 @@ jobs: (needs.verify_beta_candidate.result == 'success' || (needs.verify_beta_candidate.result == 'skipped' && needs.select_beta.outputs.mode == 'promote')) runs-on: ubuntu-latest - timeout-minutes: 150 + timeout-minutes: 170 environment: npm-beta # Serialize beta publishes so two dispatches cannot race to the same next # -beta.N version; release.sh additionally refuses to double-publish a @@ -1392,7 +1392,7 @@ jobs: if: ${{ !cancelled() && github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && !inputs.dry_run && needs.preflight_stable.result == 'success' && needs.verify_stable.result == 'success' && needs.release_runner_source.result == 'success' && (needs.release_runner_source.outputs.required == 'false' || needs.release_runner_binaries.result == 'success') }} needs: [preflight_stable, verify_stable, release_runner_source, release_runner_binaries] runs-on: ubuntu-latest - timeout-minutes: 150 + timeout-minutes: 170 environment: npm-stable permissions: contents: write diff --git a/doc/RELEASING.md b/doc/RELEASING.md index bd0317195ca..ea58a4d96e7 100644 --- a/doc/RELEASING.md +++ b/doc/RELEASING.md @@ -109,7 +109,7 @@ Every push to `master` runs the canary path inside [`.github/workflows/release.y - requires the source commit to be on master and the canary number to come from it (`N / 100` equals the commit's master position), so a dispatch with invented inputs cannot tag another commit - checks npm provenance ([`scripts/verify-canary-provenance.mjs`](../scripts/verify-canary-provenance.mjs)): any package whose provenance names something other than `.github/workflows/release.yml` on `refs/heads/master` at the source commit fails the check. A package with no provenance is accepted, because that is the supported retry after a duplicate transparency-log entry, only the trusted release workflow can publish, and the number check above already ties the version to the commit. Brief npm errors are retried. - verifies that `canary` resolves to this version or a newer canary, and that published internal dependencies exist on npm -- installs the exact `paperclipai@` into a clean temporary prefix +- installs the exact `paperclipai@` into a clean temporary prefix, retrying every 30 s within a 20-minute deadline that also stops a stuck install (`NPM_INSTALL_VERIFY_TIMEOUT_SECONDS`, `NPM_INSTALL_VERIFY_DELAY_SECONDS`; nightly, beta and stable use the same retry for their `paperclipai@` install): npm can expose a large package's metadata minutes before its tarball downloads (on 2026-11-16 `@paperclipai/server`, about 524 MB unpacked, still returned 404 several minutes after its recorded publish time) - fails by default if npm leaves `latest` pointing at a canary; use `--allow-canary-latest` only when that state is intentional - creates and pushes the git tag `canary/vYYYY.MDD.P-canary.N` (a tag that already points at the same commit is accepted, so a rerun is safe). Nightly still selects only tagged canaries. - dispatches `docker.yml` at the tag diff --git a/doc/heartbeat-internals.md b/doc/heartbeat-internals.md index 174f167cd51..c848a781377 100644 --- a/doc/heartbeat-internals.md +++ b/doc/heartbeat-internals.md @@ -339,6 +339,23 @@ Forwarding callbacks preserve construction order for budget, retry, recovery, and queue services. Existing public helpers remain re-exported by `heartbeat.ts`. Keep cancellation policy changes separate from this extraction and execution. +An operator Stop during preparation can settle before any adapter starts. The +preparation owner records `executionCancellation.state = acknowledged` only after +it unwinds and the retained dispatch, process, session, event and lease evidence confirms +that provider work never started. A terminal run status alone is not this proof. +The locked run must have no `budgetDispatch.handedOffAt` marker. The dispatch gate +writes that marker before adapter entry, so a missing invocation event or an old +owner's local flag cannot prove that dispatch never occurred. +The task page shows a confirmed operator Stop as Stopped and accepts a new message +through normal admission. Stop does not automatically restart the task. Recovery +holds, approvals, budget limits and uncertain termination keep their own gates. +The receipt's `preparation_settled` proof identifies that evidence path. Both page +projections read the same bounded evidence and require that proof; an acknowledged +receipt from a different path does not clear the preparation failure notice. +Only a user's operator Stop gets this acknowledgement and clears an obsolete +automatic-recovery marker. A system cancellation keeps its existing recovery +delivery metadata, so saved comments and continuation intents still reach admission. + Scheduling is in `server/src/services/heartbeat/scheduling.ts`. It owns timer ticks, issue-monitor claims and dispatch, exhausted-monitor recovery, and session-goal recovery. `createHeartbeatScheduling` binds explicit dependencies diff --git a/doc/link-previews.md b/doc/link-previews.md new file mode 100644 index 00000000000..67d3f89184c --- /dev/null +++ b/doc/link-previews.md @@ -0,0 +1,65 @@ +# Rich link status caching + +Rich link metadata belongs to the link preview service. GitHub pull requests are +the first provider. Links retain their exact navigation URL and use a canonical +resource URL for cache identity. + +`link_previews` stores company, viewer, channel, resource kind, canonical URL, +free-form status, JSON metadata, check time and freshness expiry. It has no task +foreign key. The same resource on different tasks reuses a record. Channel, +resource kind, status and metadata are not GitHub enums; future provider adapters +can use their own values. This change does not register plugin resolvers. + +Personal provider access remains viewer-scoped. The unique index is +`(company_id, viewer_id, canonical_url)`. The empty viewer is reserved for local +trusted mode. Company/board authorization runs before cache reads. Neither cache +endpoint is accessible to agents. Personal results never enter `external_objects`. +A cache fill is derivative read data; it does not mutate tasks or produce activity +feed events. Cache HTTP responses use `private, no-store`. + +The browser registers mounted rich links after render. Up to 200 unique links +per active company view are eligible for automatic enrichment; further links +still work on hover/focus. One request reads up to 50 cached previews using one +indexed database select, without provider calls or task joins. The read-only GET +route also supports viewer-role members. Encoded request URLs stay below 6 KB. Duplicate links +share one browser query. Fresh browser results take precedence over older database +reads. Cache failures are quiet and do not block the task page. + +After document load, core query settlement and a 500ms quiet delay, browser idle +callbacks resolve stale or missing status with at most three requests in flight. +Hover/focus uses the same query and server path, so overlapping requests coalesce. +Queued links are removed on unmount and scope changes dispose the coordinator. +There is no recurring refresh, window-focus lookup or server background worker. +New links from subsequent page content get their own one-shot enrichment. + +The existing provider timeout, fixed-host lookup, managed connection selection, +public-access checks, negative cache window and process concurrency bound remain. +Provider results are stored before the successful lookup response completes when +the store is available within the shared five-second deadline. Stalled SQL keeps +its concurrency slot until it settles; the deadline still releases the response. +Expired process entries re-read durable storage before provider work. Both batch +reads and lookup fallback use check time to retain the newest known status; a +longer cache lifetime does not make an older status newer. When the durable read +fails too, provider-failure backoff stays local, so it cannot overwrite a saved +status that this process could not read. Database outages fall back to the +optional process cache/provider path. Successful +and unavailable results normally remain fresh for one minute; provider backoff +can extend that window up to one hour. Expired records retain last known status +for immediate display. An outage keeps that status and saves the negative +freshness window, so the page does not repeatedly retry. + +Each company/viewer scope retains at most 1,000 rows. A write removes rows beyond +that limit, keeping the newest check times, and rows whose freshness expired more +than 30 days before the write's check time. A transaction-scoped advisory lock +serializes writes for that scope across replicas, so concurrent URL misses cannot +exceed the cap. Cleanup makes no queries during page hydration and starts no +background worker. Inactive scopes remain bounded and are cleaned on their next +write; company deletion removes all their rows. Normal stale status remains +available until it ages out or the scope reaches its quota. Negative results use +the same cap and retention policy as known status. + +The single-link lookup route also limits each company/viewer to 600 requests per +minute per server process, using the existing in-memory request limiter. Excess +requests return 429 with Retry-After. Cached batch reads remain available during +that backoff and do not allocate stored rows. The durable quota is enforced across +replicas and remains effective when process-local request limits reset. diff --git a/docs/deploy/environment-variables.md b/docs/deploy/environment-variables.md index 0460ab91346..70d804fc346 100644 --- a/docs/deploy/environment-variables.md +++ b/docs/deploy/environment-variables.md @@ -19,7 +19,7 @@ All environment variables that Paperclip uses for server configuration. | `PAPERCLIP_DEPLOYMENT_MODE` | `local_trusted` | Runtime mode override | | `PAPERCLIP_DEPLOYMENT_EXPOSURE` | `private` | Exposure policy when deployment mode is `authenticated` | | `PAPERCLIP_API_URL` | (auto-derived) | Paperclip API base URL. When set externally (e.g., via Kubernetes ConfigMap, load balancer, or reverse proxy), the server preserves the value instead of deriving it from the listen host and port. Useful for deployments where the public-facing URL differs from the local bind address. | -| `PAPERCLIP_CHAT_WEBHOOK_PUBLIC_URL` | (board public origin) | Optional HTTPS origin for native chat provider webhooks when ingress and the board use different hosts. Must have no credentials, path, query, or fragment; invalid configuration refuses startup. Used only for provider callback URLs, not board links, authentication, trusted hosts, or identity confirmation. | +| `PAPERCLIP_CHAT_WEBHOOK_PUBLIC_URL` | (board public origin) | Optional HTTPS origin for native chat provider webhooks when ingress and the board use different hosts. Must have no credentials, path, query, or fragment; invalid configuration refuses startup. Used only for provider callback URLs, not board links, authentication, trusted hosts, or identity confirmation. In `authenticated` mode with `private` exposure, also add the ingress hostname to `PAPERCLIP_ALLOWED_HOSTNAMES`. Otherwise the private-hostname guard rejects provider callbacks with 403 before they reach the webhook route. The guard reads `X-Forwarded-Host` before `Host`, so a reverse proxy that rewrites `Host` but forwards the original `X-Forwarded-Host` still gets 403. | | `PAPERCLIP_RUNNER_PUBLIC_URL` | (unset) | Explicit `wss://` base URL used only when a remote `paperclip_runner` target dials Paperclip directly. Paperclip appends `/api/runner/v1/connect/`; the reverse proxy must forward WebSocket upgrades for that route. This value is never inferred from request headers. Daytona ignores it and uses provider ingress. | | `PAPERCLIP_RUNNER_CA_BUNDLE_PATH` | (unset) | Optional PEM CA bundle for direct runner WSS. Platform roots remain enabled. There is no insecure TLS bypass. | | `PAPERCLIP_RUNNER_REMOTE_BINARY_PATH` | (host build) | Host-local path to a `paperclip-runnerd` artifact built for the remote target OS and architecture. Required when Paperclip and the remote sandbox do not share a compatible platform; build metadata and the required transport mode are verified before launch. | diff --git a/packages/adapter-utils/src/execution-target.ts b/packages/adapter-utils/src/execution-target.ts index 5e2ea679cc0..077cb38b63d 100644 --- a/packages/adapter-utils/src/execution-target.ts +++ b/packages/adapter-utils/src/execution-target.ts @@ -1832,6 +1832,7 @@ printf '\0PAPERCLIP_GIT_CONTEXT_END\0' /** Stage token-free launchers next to the execution, not in shared global Git config. */ export async function prepareGitHubOperationLaunchers(input: { runId: string; target: AdapterExecutionTarget | null | undefined; cwd: string; env: Record; + broker?: { url: string; token: string }; }): Promise> { const remote = input.target?.kind === "remote" ? input.target : null; const directory = githubOperationLauncherDirectory(input); @@ -1851,8 +1852,9 @@ export async function prepareGitHubOperationLaunchers(input: { // Remote launchers live beneath the checkout. Pin their own package scope // so an enclosing project's "type": "module" cannot reinterpret require(). ["package.json", '{"type":"commonjs"}\n'], - ...["git", "gh"].map((name) => [name, githubLauncherSource()] as const), + ...["git", "gh"].map((name) => [name, githubLauncherSource({ brokerFile: input.broker !== undefined })] as const), ...[".zshenv", ".zprofile", ".zshrc", ".bash_profile", ".bashrc", ".profile"].map((name) => [name, profile] as const), + ...(input.broker ? [["broker.json", `${JSON.stringify({ url: input.broker.url, token: input.broker.token })}\n`] as const] : []), ]); if (remote) { const runner = adapterExecutionTargetCommandRunner(remote); @@ -1863,6 +1865,7 @@ export async function prepareGitHubOperationLaunchers(input: { label: "GitHub operation launcher", action: "stage GitHub operation launcher", lockDir: path.posix.join(directory, `.${program}.lock`), executable: program === "git" || program === "gh", + private: program === "broker.json", })), ensureDirectories: [configDirectory], action: "stage GitHub operation launchers", timeoutMs: 15_000, shellCommand: adapterExecutionTargetShellCommand(remote), @@ -1870,7 +1873,11 @@ export async function prepareGitHubOperationLaunchers(input: { } else { await fs.mkdir(directory, { recursive: true, mode: 0o700 }); await fs.mkdir(configDirectory, { recursive: true, mode: 0o700 }); - for (const [program, body] of Object.entries(files)) await fs.writeFile(path.join(directory, program), body, { mode: 0o700 }); + for (const [program, body] of Object.entries(files)) { + const partial = path.join(directory, `.${program}.${randomUUID()}.partial`); + await fs.writeFile(partial, body, { mode: program === "broker.json" ? 0o600 : 0o700 }); + await fs.rename(partial, path.join(directory, program)); + } } return { ...input.env, PATH: managedPath, ZDOTDIR: directory, BASH_ENV: `${directory}/.bashrc`, GH_CONFIG_DIR: configDirectory, PAPERCLIP_GITHUB_LAUNCHER_DIR: directory }; diff --git a/packages/adapter-utils/src/remote-text-file-sync.ts b/packages/adapter-utils/src/remote-text-file-sync.ts index 309964038b9..2b2edd36d09 100644 --- a/packages/adapter-utils/src/remote-text-file-sync.ts +++ b/packages/adapter-utils/src/remote-text-file-sync.ts @@ -12,6 +12,7 @@ export interface RemoteTextFileSyncFile { action: string; lockDir: string; executable?: boolean; + private?: boolean; } export interface RemoteTextFileSyncInput extends RemoteTextFileSyncFile { @@ -52,6 +53,7 @@ function program(input: RemoteTextFileSyncFile) { const sha256 = createHash("sha256").update(input.body, "utf8").digest("hex"); const script = [ "set -eu", + ...(input.private ? ["umask 077"] : []), `remote_dir=${shellQuote(input.remoteDir)}`, `remote_path=${shellQuote(input.remotePath)}`, `remote_partial=${shellQuote(remotePartial)}`, @@ -79,7 +81,7 @@ function program(input: RemoteTextFileSyncFile) { " current_sha=\"$(hash_file \"$remote_path\" 2>/dev/null)\" || current_sha=\"\"", "fi", "if [ -n \"$current_sha\" ] && [ \"$current_sha\" = \"$expected_sha\" ]; then", - ...(input.executable ? [' chmod 700 "$remote_path"'] : []), + ...(input.executable ? [' chmod 700 "$remote_path"'] : input.private ? [' chmod 600 "$remote_path"'] : []), " printf '{\"uploaded\":false}\\n'", " exit 0", "fi", @@ -94,7 +96,7 @@ function program(input: RemoteTextFileSyncFile) { "else", ` echo ${shellQuote(`${input.label} sha verify skipped: no sha256sum/shasum on remote.`)} >&2`, "fi", - ...(input.executable ? ['chmod 700 "$remote_partial"'] : []), + ...(input.executable ? ['chmod 700 "$remote_partial"'] : input.private ? ['chmod 600 "$remote_partial"'] : []), "mv \"$remote_partial\" \"$remote_path\"", "printf '{\"uploaded\":true}\\n'", ].join("\n"); diff --git a/packages/adapter-utils/src/sandbox-callback-bridge.test.ts b/packages/adapter-utils/src/sandbox-callback-bridge.test.ts index 5222af5b201..bf59f88667b 100644 --- a/packages/adapter-utils/src/sandbox-callback-bridge.test.ts +++ b/packages/adapter-utils/src/sandbox-callback-bridge.test.ts @@ -1446,6 +1446,31 @@ describe("sandbox callback bridge", () => { ).resolves.toEqual([]); }); + it("creates every staged copy of a private file without group or other access", async () => { + const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-private-sync-")); + cleanupDirs.push(rootDir); + const shimDir = path.join(rootDir, "shim"); + const umaskLog = path.join(rootDir, "umask.log"); + await mkdir(shimDir); + await writeFile(path.join(shimDir, "base64"), + `#!/bin/sh\numask > ${JSON.stringify(umaskLog)}\nPATH=${JSON.stringify(process.env.PATH ?? "")} exec base64 "$@"\n`, { mode: 0o700 }); + const inner = createExecRunner(); + const runner = { + execute: (input: Parameters[0]) => + inner.execute({ ...input, env: { ...input.env, PATH: `${shimDir}:${process.env.PATH ?? ""}` } }), + }; + const remoteDir = path.join(rootDir, "launchers"); + const remotePath = path.posix.join(remoteDir, "broker.json"); + const result = await syncRemoteTextFileWithHashSkip({ + runner, remoteCwd: rootDir, remoteDir, remotePath, body: "{\"token\":\"fixture\"}\n", + label: "Private fixture", action: "sync private fixture", + lockDir: path.posix.join(remoteDir, ".broker.json.lock"), private: true, timeoutMs: 30_000, + }); + expect(result.uploaded).toBe(true); + expect((await readFile(umaskLog, "utf8")).trim()).toMatch(/^0?077$/); + expect((await fs.stat(remotePath)).mode & 0o777).toBe(0o600); + }); + it("test_process_session_script_rewritten_on_hash_mismatch: a mismatched remote hash still rewrites the script", async () => { const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-hashskip-cold-")); cleanupDirs.push(rootDir); diff --git a/packages/db/src/migrations/0489_real_sage.sql b/packages/db/src/migrations/0489_real_sage.sql new file mode 100644 index 00000000000..57c2b02e88a --- /dev/null +++ b/packages/db/src/migrations/0489_real_sage.sql @@ -0,0 +1,14 @@ +CREATE TABLE IF NOT EXISTS "link_previews" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL CONSTRAINT "link_previews_company_id_companies_id_fk" REFERENCES "public"."companies"("id") ON DELETE cascade, + "viewer_id" text NOT NULL, + "channel" text NOT NULL, + "resource_kind" text NOT NULL, + "canonical_url" text NOT NULL, + "status" text, + "metadata" jsonb DEFAULT '{}'::jsonb NOT NULL, + "checked_at" timestamp with time zone NOT NULL, + "expires_at" timestamp with time zone NOT NULL +); +--> statement-breakpoint +CREATE UNIQUE INDEX IF NOT EXISTS "link_previews_scope_url_uq" ON "link_previews" USING btree ("company_id","viewer_id","canonical_url"); diff --git a/packages/db/src/migrations/meta/0484_snapshot.json b/packages/db/src/migrations/meta/0489_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0484_snapshot.json rename to packages/db/src/migrations/meta/0489_snapshot.json index 1debf9ce54b..4eee50702b2 100644 --- a/packages/db/src/migrations/meta/0484_snapshot.json +++ b/packages/db/src/migrations/meta/0489_snapshot.json @@ -1,6 +1,6 @@ { - "id": "9389124c-379a-4b64-9c20-c7b37538e7c8", - "prevId": "ceaa38c4-681b-430e-9578-0854650d85b3", + "id": "dc61c7f3-cf3d-44c5-9296-86973e5f0925", + "prevId": "8f935a52-5f1e-4afe-8d13-c1770ca33968", "version": "7", "dialect": "postgresql", "tables": { @@ -6582,6 +6582,111 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.automatic_run_brakes": { + "name": "automatic_run_brakes", + "schema": "", + "columns": { + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'closed'" + }, + "reason": { + "name": "reason", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "state_changed_at": { + "name": "state_changed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "opened_at": { + "name": "opened_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "next_probe_at": { + "name": "next_probe_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "probe_run_id": { + "name": "probe_run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "probe_successes": { + "name": "probe_successes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "release_window_started_at": { + "name": "release_window_started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "release_window_starts": { + "name": "release_window_starts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_creation_at": { + "name": "next_creation_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "automatic_run_brakes_company_id_companies_id_fk": { + "name": "automatic_run_brakes_company_id_companies_id_fk", + "tableFrom": "automatic_run_brakes", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.board_api_keys": { "name": "board_api_keys", "schema": "", @@ -36029,6 +36134,78 @@ "method": "btree", "with": {} }, + "heartbeat_runs_company_finished_idx": { + "name": "heartbeat_runs_company_finished_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "finished_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"finished_at\" is not null", + "concurrently": true, + "method": "btree", + "with": {} + }, + "heartbeat_runs_settled_process_identity_idx": { + "name": "heartbeat_runs_settled_process_identity_idx", + "columns": [ + { + "expression": "process_host_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"runtime_mode\" = 'native' and \"heartbeat_runs\".\"status\" in ('failed', 'cancelled', 'timed_out', 'interrupted')\n and \"heartbeat_runs\".\"finished_at\" is not null\n and (\"heartbeat_runs\".\"process_pid\" is not null or \"heartbeat_runs\".\"process_group_id\" is not null or \"heartbeat_runs\".\"process_started_at\" is not null)", + "concurrently": true, + "method": "btree", + "with": {} + }, + "heartbeat_runs_pending_api_stop_idx": { + "name": "heartbeat_runs_pending_api_stop_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"status\" = 'cancelled' and \"heartbeat_runs\".\"driver_kind\" = 'cursor_cloud_api'\n and (\"heartbeat_runs\".\"result_json\"->'executionCancellation'->>'state') = 'requested'", + "concurrently": true, + "method": "btree", + "with": {} + }, "heartbeat_runs_company_created_at_desc_idx": { "name": "heartbeat_runs_company_created_at_desc_idx", "columns": [ @@ -40722,6 +40899,131 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.issue_recovery_deferrals": { + "name": "issue_recovery_deferrals", + "schema": "", + "columns": { + "queue": { + "name": "queue", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "due_at": { + "name": "due_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "issue_recovery_deferrals_issue_id_issues_id_fk": { + "name": "issue_recovery_deferrals_issue_id_issues_id_fk", + "tableFrom": "issue_recovery_deferrals", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "issue_recovery_deferrals_company_id_companies_id_fk": { + "name": "issue_recovery_deferrals_company_id_companies_id_fk", + "tableFrom": "issue_recovery_deferrals", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "issue_recovery_deferrals_pk": { + "name": "issue_recovery_deferrals_pk", + "columns": [ + "queue", + "issue_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.issue_recovery_full_passes": { + "name": "issue_recovery_full_passes", + "schema": "", + "columns": { + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "queue": { + "name": "queue", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "issue_recovery_full_passes_company_id_companies_id_fk": { + "name": "issue_recovery_full_passes_company_id_companies_id_fk", + "tableFrom": "issue_recovery_full_passes", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "issue_recovery_full_passes_pk": { + "name": "issue_recovery_full_passes_pk", + "columns": [ + "company_id", + "queue" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.issue_reference_mentions": { "name": "issue_reference_mentions", "schema": "", @@ -44779,6 +45081,123 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.link_previews": { + "name": "link_previews", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "viewer_id": { + "name": "viewer_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel": { + "name": "channel", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_kind": { + "name": "resource_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "canonical_url": { + "name": "canonical_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "checked_at": { + "name": "checked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "link_previews_scope_url_uq": { + "name": "link_previews_scope_url_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "viewer_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "canonical_url", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "link_previews_company_id_companies_id_fk": { + "name": "link_previews_company_id_companies_id_fk", + "tableFrom": "link_previews", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.managed_agent_profiles": { "name": "managed_agent_profiles", "schema": "", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 464a6addffb..ee03bddd7a5 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3410,6 +3410,13 @@ "when": 1794820062730, "tag": "0488_issue_recovery_full_passes", "breakpoints": true + }, + { + "idx": 489, + "version": "7", + "when": 1794841384470, + "tag": "0489_real_sage", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index 68878bc412f..f27b014644c 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -290,3 +290,4 @@ export { projectTaskExecutionPolicies, executionAdmissions, executionAdmissionPr export { budgetEvaluationWork } from "./budget_evaluation_work.js"; export { tailscaleConnections } from "./tailscale_connections.js"; export { nativeProviderArtifacts, nativeProviderArtifactReferences } from "./native_provider_artifacts.js"; +export { linkPreviews } from "./link_previews.js"; diff --git a/packages/db/src/schema/link_previews.ts b/packages/db/src/schema/link_previews.ts new file mode 100644 index 00000000000..c7b7ee334aa --- /dev/null +++ b/packages/db/src/schema/link_previews.ts @@ -0,0 +1,19 @@ +import { jsonb, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core"; +import { companies } from "./companies.js"; + +/** Optional enrichment, independent of tasks and of provider-specific status vocabularies. */ +export const linkPreviews = pgTable("link_previews", { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + // Personal provider results must not be reused by another viewer. Empty is local-trusted. + viewerId: text("viewer_id").notNull(), + channel: text("channel").notNull(), + resourceKind: text("resource_kind").notNull(), + canonicalUrl: text("canonical_url").notNull(), + status: text("status"), + metadata: jsonb("metadata").$type>().notNull().default({}), + checkedAt: timestamp("checked_at", { withTimezone: true }).notNull(), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), +}, table => ({ + identity: uniqueIndex("link_previews_scope_url_uq").on(table.companyId, table.viewerId, table.canonicalUrl), +})); diff --git a/packages/db/src/test-embedded-postgres.test.ts b/packages/db/src/test-embedded-postgres.test.ts index 84856638701..5a7ea81a1e7 100644 --- a/packages/db/src/test-embedded-postgres.test.ts +++ b/packages/db/src/test-embedded-postgres.test.ts @@ -412,6 +412,31 @@ describeWithPostgres("startEmbeddedPostgresTestDatabase template path", () => { } }); + it.each([ + { mode: "template", setting: undefined }, + { mode: "fresh", setting: "0" }, + ])("hides NOTICE messages from new clients on the $mode path", { timeout: EMBEDDED_POSTGRES_TEST_TIMEOUT_MS }, async ({ mode, setting }) => { + if (setting === undefined) delete process.env.PAPERCLIP_TEST_POSTGRES_TEMPLATE; + else process.env.PAPERCLIP_TEST_POSTGRES_TEMPLATE = setting; + const database = await startEmbeddedPostgresTestDatabase("paperclip-quiet-notices-"); + try { + expect(lastStartMode()).toBe(mode); + const notices: unknown[] = []; + const sql = postgres(database.connectionString, { max: 1, onnotice: (notice) => notices.push(notice) }); + try { + expect((await sql`show client_min_messages`)[0]?.client_min_messages).toBe("warning"); + await sql`create table quiet_parent (id int primary key)`; + await sql`create table quiet_child (parent_id int references quiet_parent (id))`; + await sql`truncate quiet_parent cascade`; + expect(notices).toEqual([]); + } finally { + await sql.end(); + } + } finally { + await database.cleanup(); + } + }); + describeOnPosix("cache root safety", () => { it("uses fresh clusters when the cache root is not a private directory of this user", { timeout: EMBEDDED_POSTGRES_TEST_TIMEOUT_MS }, async () => { delete process.env.PAPERCLIP_TEST_POSTGRES_TEMPLATE; diff --git a/packages/db/src/test-embedded-postgres.ts b/packages/db/src/test-embedded-postgres.ts index c2a4b4fa984..0e2488523c6 100644 --- a/packages/db/src/test-embedded-postgres.ts +++ b/packages/db/src/test-embedded-postgres.ts @@ -15,7 +15,13 @@ import { import { prepareEmbeddedPostgresNativeRuntime } from "./embedded-postgres-native.js"; import { loadWithoutEmbeddedPostgresExitHooks } from "./embedded-postgres-lifecycle.js"; import { ownTestPostgres, TestPostgresShutdownError, type TestPostgresInstance } from "./test-postgres-owner.js"; -import { checkTestPostgresAdmin, startTestPostgresDatabase, testPostgresAdminUrl } from "./test-postgres-admin.js"; +import postgres from "postgres"; +import { + checkTestPostgresAdmin, + QUIET_TEST_DATABASE_SQL, + startTestPostgresDatabase, + testPostgresAdminUrl, +} from "./test-postgres-admin.js"; // Time budget (ms) for a vitest test in the embedded-Postgres cost class: a // test that starts an embedded Postgres cluster and runs migrations. Measured @@ -156,6 +162,12 @@ async function createEmbeddedPostgresTestInstanceAt(dataDir: string) { return { dataDir, port, instance, getRecentLogs: () => logBuffer.getRecentLogs() }; } +async function quietTestDatabase(adminUrl: string, databaseName: string): Promise { + const sql = postgres(adminUrl, { max: 1, onnotice() {} }); + try { await sql.unsafe(QUIET_TEST_DATABASE_SQL(databaseName)); } + finally { await sql.end({ timeout: 1 }); } +} + function adminConnectionStringFor(port: number): string { return `postgres://${EMBEDDED_POSTGRES_USER}:${EMBEDDED_POSTGRES_PASSWORD}@127.0.0.1:${port}/postgres`; } @@ -667,6 +679,7 @@ export async function startEmbeddedPostgresTestDatabase( // Both calls are no-ops on a template copy and keep the returned database // identical to the fresh path even if the template were ever stale. await ensurePostgresDatabase(adminConnectionStringFor(port), "paperclip"); + await quietTestDatabase(adminConnectionStringFor(port), "paperclip"); const connectionString = databaseConnectionStringFor(port); await applyPendingMigrations(connectionString); diff --git a/packages/db/src/test-postgres-admin.test.ts b/packages/db/src/test-postgres-admin.test.ts index 7498a4a467c..2b7b887a77a 100644 --- a/packages/db/src/test-postgres-admin.test.ts +++ b/packages/db/src/test-postgres-admin.test.ts @@ -1,4 +1,5 @@ import { randomUUID } from "node:crypto"; +import postgres from "postgres"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { createDb } from "./client.js"; import { @@ -83,4 +84,18 @@ describe.skipIf(!support.supported)("shared PostgreSQL fixtures", () => { } }, 90_000); + it("hides NOTICE messages from new clients of a disposable database", async () => { + __setEmbeddedPostgresCtorProviderForTests(async () => { throw new Error("Must not start another PostgreSQL server"); }); + const database = await startEmbeddedPostgresTestDatabase("ignored-"); + databases.push(database); + const notices: unknown[] = []; + const sql = postgres(database.connectionString, { max: 1, onnotice: (notice) => notices.push(notice) }); + try { + expect((await sql`SHOW client_min_messages`)[0]?.client_min_messages).toBe("warning"); + await sql`CREATE TABLE quiet_parent (id integer PRIMARY KEY)`; + await sql`CREATE TABLE quiet_child (parent_id integer REFERENCES quiet_parent (id))`; + await sql`TRUNCATE quiet_parent CASCADE`; + expect(notices).toEqual([]); + } finally { await sql.end(); } + }, 90_000); }); diff --git a/packages/db/src/test-postgres-admin.ts b/packages/db/src/test-postgres-admin.ts index a76848fcc05..95e91a447ab 100644 --- a/packages/db/src/test-postgres-admin.ts +++ b/packages/db/src/test-postgres-admin.ts @@ -2,6 +2,9 @@ import { randomUUID } from "node:crypto"; import postgres from "postgres"; import { applyPendingMigrations, closeRegisteredClients } from "./client.js"; +export const QUIET_TEST_DATABASE_SQL = (databaseName: string) => + `ALTER DATABASE "${databaseName}" SET client_min_messages = warning`; + export function testPostgresAdminUrl(): string | undefined { const value = process.env.PAPERCLIP_TEST_POSTGRES_ADMIN_URL?.trim(); if (!value) return undefined; @@ -41,6 +44,7 @@ export async function startTestPostgresDatabase(adminUrl: string): Promise<{ })(); try { await admin.unsafe(`CREATE DATABASE "${name}"${template ? ` TEMPLATE "${template}"` : ""}`); + await admin.unsafe(QUIET_TEST_DATABASE_SQL(name)); await applyPendingMigrations(connectionString); return { connectionString, cleanup }; } catch (error) { diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs index 6da5c8d45f3..e9242bee000 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs @@ -963,6 +963,7 @@ impl AcpxProviderSession { let mut next_bridge = self.tool_bridge.clone(); let mut next_reserved_bridge = self.reserved_tool_bridge.clone(); let mut reconciled_events = Vec::with_capacity(events.len()); + let mut retryable_rejections = Vec::new(); for event in events { let mut expose_event = true; match &event { @@ -998,9 +999,19 @@ impl AcpxProviderSession { if let Err(error) = bridge.begin_call(call_id.clone(), operation_id.clone(), input.clone()) { - return Err(self.fail_closed(LocalRunnerError::invalid(format!( - "ACPX provider tool authorization failed: {error}" - )))); + if !error.is_retryable() { + return Err(self.fail_closed(LocalRunnerError::invalid(format!( + "ACPX provider tool authorization failed: {error}" + )))); + } + if let Err(error) = next_state.complete_tool(call_id, operation_id) { + return Err(self.fail_closed(error)); + } + retryable_rejections.push(( + call_id.clone(), + error.safe_provider_message().unwrap_or_default().to_owned(), + )); + expose_event = false; } } AcpxProviderStateEvent::SemanticResult(result) => { @@ -1125,6 +1136,22 @@ impl AcpxProviderSession { self.state = next_state; self.tool_bridge = next_bridge; self.reserved_tool_bridge = next_reserved_bridge; + if let Some(turn_id) = (!retryable_rejections.is_empty()) + .then(|| self.state.active_turn_id().map(str::to_owned)) + .flatten() + { + for (call_id, message) in retryable_rejections { + let response = self + .transport + .request_tool_resolve(json!({ + "callId": call_id, + "turnId": turn_id, + "error": {"message": message}, + })) + .map_err(|(error, _)| self.fail_closed(error))?; + self.verify_resolution(&response, "tool")?; + } + } if let Some(turn_id) = terminal_turn { self.offer_provider_turn(&turn_id, terminal_completed, terminal_live); } diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs index 8bd51438e54..370a840ec86 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs @@ -104,7 +104,10 @@ fn run() -> Result<(), Box> { .try_into() .map_err(|_| "lifetime fence requires three ports")?; // Only the receiver-admission fixture writes this task-owned command journal. - let mut admission_journal = if matches!(mode, "admission-tool" | "admission-tool-oversized") { + let mut admission_journal = if matches!( + mode, + "admission-tool" | "admission-tool-oversized" | "admission-tool-burst" + ) { let path = args .windows(2) .find(|pair| pair[0] == "--journal") @@ -641,7 +644,10 @@ fn run() -> Result<(), Box> { } if let Some(journal) = admission_journal.as_mut() { write_json(journal, &json!({"request":request}))?; - let response = if command == "tool.resolve" { + let response = if command == "tool.resolve" && mode == "admission-tool-burst" { + json!({"protocolVersion":GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, + "id":id,"ok":true,"result":{"resolved":true}}) + } else if command == "tool.resolve" { json!({"protocolVersion":GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, "id":id,"ok":true,"result":{"resolved": request["params"]["callId"] == "call-admission" @@ -660,7 +666,20 @@ fn run() -> Result<(), Box> { ) }; write_json(&mut stdout, &response)?; - if command == "turn.start" { + if command == "turn.start" && mode == "admission-tool-burst" { + for index in 0..11 { + let frame = json!({ + "protocolVersion":GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, + "sequence":next_sequence,"eventType":"runtime.tool_called", + "runId":"run-1","turnId":request["params"]["turnId"], + "payload":{"callId":format!("call-burst-{index}"),"operationId":"issues.read", + "input":{"id":format!("issue-{index}")}}, + }); + write_json(journal, &json!({"emitted":frame}))?; + write_json(&mut stdout, &frame)?; + next_sequence += 1; + } + } else if command == "turn.start" { let frame = json!({ "protocolVersion":GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, "sequence":next_sequence,"eventType":"runtime.tool_called", diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/src/provider_backend.rs index 7e811ce6c7d..02907217626 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/provider_backend.rs @@ -72,7 +72,7 @@ fn invalid_tool_call_result( "message": error .safe_provider_message() .unwrap_or(GENERIC_INVALID_TOOL_CALL_MESSAGE), - "retryable": false, + "retryable": error.is_retryable(), }, }), is_error: true, diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/provider_bridge.rs b/packages/paperclip-runner/runner/crates/runner-core/src/provider_bridge.rs index b1ab2939aad..bf9d33ebd24 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/provider_bridge.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/provider_bridge.rs @@ -39,6 +39,9 @@ const MAX_SETTLED_CALL_IDS: usize = 65_536; const REPLAY_FILTER_WORDS: usize = 32_768; const ACTIVE_TURN_RECEIPT_LIMIT_MESSAGE: &str = "durable provider tool receipt limit reached for the active turn"; +const TOOL_CALLS_IN_FLIGHT_MESSAGE: &str = + "too many provider tool calls are in flight for the retained result reserve"; +const TOOL_CALLS_IN_FLIGHT_HINT: &str = "Too many tool calls are in flight. This call was not executed. Wait for the pending tool results, then retry it."; const COMPLETION_INPUT_SCHEMA_HINT: &str = "Invalid paperclip_finish arguments. Required fields: reportedWorkDisposition, summary, completionClaim, evidence, and verification. When reportedWorkDisposition is yielded, continuation must include kind=response_wake or monitor, summary, and idempotencyKey."; const HUMAN_INPUT_SCHEMA_HINT: &str = "Invalid request_human_input arguments. Put version and supersedeOnUserComment at payload.version and payload.supersedeOnUserComment, never at the root. For questions, use payload.version=1 and a complete payload.questionSet. Preserve question and option IDs. Correct the arguments and retry."; const APPROVAL_INPUT_SCHEMA_HINT: &str = "Invalid request_human_input arguments. Put version and supersedeOnUserComment at payload.version and payload.supersedeOnUserComment, never at the root. Keep approval requests in their confirmation or checkbox interactionKind; do not replace them with questions. Correct the arguments and retry."; @@ -310,6 +313,17 @@ impl ProviderBridgeError { self.message == ACTIVE_TURN_RECEIPT_LIMIT_MESSAGE } + fn tool_calls_in_flight() -> Self { + Self { + message: TOOL_CALLS_IN_FLIGHT_MESSAGE.to_owned(), + safe_provider_message: Some(TOOL_CALLS_IN_FLIGHT_HINT.to_owned()), + } + } + + pub fn is_retryable(&self) -> bool { + self.message == TOOL_CALLS_IN_FLIGHT_MESSAGE + } + pub fn safe_provider_message(&self) -> Option<&str> { self.safe_provider_message.as_deref() } @@ -779,7 +793,7 @@ impl ProviderToolBridge { .and_then(|total| total.checked_add(result_reserve)) .is_none_or(|total| total > MAX_RETAINED_TOOL_VALUE_BYTES) { - return Err(ProviderBridgeError::active_turn_receipt_limit()); + return Err(ProviderBridgeError::tool_calls_in_flight()); } // Reserve the complete encoded receipt, including this exact input and // a maximum-sized result, before accepting work. An admitted call can @@ -791,7 +805,7 @@ impl ProviderToolBridge { return Err(ProviderBridgeError::active_turn_receipt_limit()); } if self.ensure_settled_result_capacity(Some(&call)).is_err() { - return Err(ProviderBridgeError::active_turn_receipt_limit()); + return Err(ProviderBridgeError::tool_calls_in_flight()); } self.pending.insert(call_id, call.clone()); Ok(call) @@ -1656,6 +1670,108 @@ mod tests { bridge } + fn get_task_bridge() -> ProviderToolBridge { + let operation = AuthorizedTool { + operation_id: "get_task".to_owned(), + version: 1, + description: "Read a task.".to_owned(), + input_schema: json!({"type": "object"}), + response_schema: json!({"type": "object"}), + }; + let mut bridge = ProviderToolBridge::default(); + bridge + .prepare(AuthorizedToolSet { + schema: TOOL_SET_SCHEMA.to_owned(), + schema_version: 1, + catalog_digest: authorized_tool_catalog_digest(std::slice::from_ref(&operation)) + .unwrap(), + operations: vec![operation], + }) + .unwrap(); + bridge + } + + fn settle_get_task(bridge: &mut ProviderToolBridge, call_id: &str, result_bytes: usize) { + bridge + .begin_call(call_id.to_owned(), "get_task".to_owned(), json!({})) + .unwrap(); + bridge + .apply_result(ToolResult { + call_id: call_id.to_owned(), + operation_id: "get_task".to_owned(), + result: json!({"body": "x".repeat(result_bytes)}), + is_error: false, + }) + .unwrap(); + } + + #[test] + fn parallel_calls_over_the_result_reserve_reject_only_the_overflow_call() { + let mut bridge = get_task_bridge(); + settle_get_task(&mut bridge, "settled", 600 * 1024); + for index in 0..9 { + bridge + .begin_call( + format!("parallel-{index}"), + "get_task".to_owned(), + json!({}), + ) + .expect("calls within the result reserve are admitted"); + } + let error = bridge + .begin_call("parallel-9".to_owned(), "get_task".to_owned(), json!({})) + .expect_err("the call that overflows the reserve is rejected"); + assert!(!error.is_active_turn_receipt_limit()); + assert!(error.is_retryable()); + assert_eq!( + error.safe_provider_message(), + Some(TOOL_CALLS_IN_FLIGHT_HINT) + ); + assert!(!bridge.durable_run_receipt_limit_reached()); + assert!(!bridge.has_call_receipt("parallel-9")); + assert_eq!(bridge.pending_calls().count(), 9); + + bridge + .apply_result(ToolResult { + call_id: "parallel-0".to_owned(), + operation_id: "get_task".to_owned(), + result: json!({"ok": true}), + is_error: false, + }) + .unwrap(); + bridge + .begin_call("parallel-9".to_owned(), "get_task".to_owned(), json!({})) + .expect("the rejected call is admitted once a pending result settles"); + assert!(!bridge.durable_run_receipt_limit_reached()); + } + + #[test] + fn held_result_bytes_over_the_limit_still_stop_the_turn() { + let mut bridge = get_task_bridge(); + let mut settled = 0; + let error = loop { + match bridge.begin_call(format!("held-{settled}"), "get_task".to_owned(), json!({})) { + Ok(_) => { + bridge + .apply_result(ToolResult { + call_id: format!("held-{settled}"), + operation_id: "get_task".to_owned(), + result: json!({"body": "x".repeat(760 * 1024)}), + is_error: false, + }) + .unwrap(); + settled += 1; + } + Err(error) => break error, + } + }; + assert!(settled >= 9); + assert_eq!(bridge.pending_calls().count(), 0); + assert!(error.is_active_turn_receipt_limit()); + assert!(!error.is_retryable()); + assert!(bridge.durable_run_receipt_limit_reached()); + } + #[test] fn completion_summary_enforces_the_canonical_unicode_character_limit() { let mut within_limit = completion_bridge(); diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_provider_session.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_provider_session.rs index 9478a755975..3d383bc310d 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_provider_session.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_provider_session.rs @@ -385,6 +385,68 @@ fn receiver_admits_normal_tool_event_and_resolves_only_correlated_call_once() { check_tool_receiver_admission(false); } +#[test] +fn receiver_rejects_only_the_tool_call_that_overflows_the_result_reserve() { + let root = std::env::temp_dir().join(format!("acpx-burst-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&root).unwrap(); + let journal = root.join("commands.jsonl"); + let mut fixture = config("admission-tool-burst"); + fixture + .transport + .args + .extend(["--journal".to_owned(), journal.to_str().unwrap().to_owned()]); + let mut session = AcpxProviderSession::start(&fixture).unwrap(); + session + .start_turn("turn-admission", "Read the issues", &std::env::temp_dir()) + .unwrap(); + let mut exposed = 0; + while (0..10).any(|index| { + session + .state() + .pending_tool(&format!("call-burst-{index}")) + .is_none() + }) || exposed < 10 + { + exposed += session + .poll_event(Duration::from_secs(1)) + .unwrap() + .map_or(0, |events| events.len()); + } + for _ in 0..3 { + let _ = session.poll_event(Duration::from_millis(100)).unwrap(); + } + assert_eq!(exposed, 10); + assert!(session.state().pending_tool("call-burst-10").is_none()); + session + .deliver_tool_result(&paperclip_runner_core::provider_bridge::ToolResult { + call_id: "call-burst-0".to_owned(), + operation_id: "issues.read".to_owned(), + result: json!({"id":"issue-0"}), + is_error: false, + }) + .unwrap(); + session.shutdown("burst test complete").unwrap(); + let rows: Vec = std::fs::read_to_string(&journal) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + let resolutions: Vec<_> = rows + .iter() + .filter_map(|row| row.get("request")) + .filter(|request| request["command"] == "tool.resolve") + .map(|request| request["params"].clone()) + .collect(); + assert_eq!(resolutions.len(), 2); + assert_eq!(resolutions[0]["callId"], "call-burst-10"); + assert!(resolutions[0]["error"]["message"] + .as_str() + .unwrap() + .contains("Too many tool calls are in flight")); + assert_eq!(resolutions[1]["callId"], "call-burst-0"); + std::fs::remove_dir_all(root).unwrap(); +} + #[test] fn pi_thinking_effective_identity_is_admitted_before_any_turn() { use paperclip_runner_core::acpx_provider_session::{ diff --git a/packages/paperclip-runner/src/contracts/control-plane-port.ts b/packages/paperclip-runner/src/contracts/control-plane-port.ts index 1e7b5664a7f..98cd2aeb117 100644 --- a/packages/paperclip-runner/src/contracts/control-plane-port.ts +++ b/packages/paperclip-runner/src/contracts/control-plane-port.ts @@ -36,7 +36,8 @@ export interface AppendControlPlaneEventOptions { */ deferPostCommitObservers?: true; /** - * For an `item.delta` only, on a port with `pipelinesStreamingEvents`: the + * For an event type in the port's `pipelinedEventTypes` (only `item.delta` + * when the port does not name them), on a port with `pipelinesStreamingEvents`: the * caller does not wait for this receipt before its next append, so the port * may hold the delta briefly to commit it with later ones. */ @@ -95,6 +96,7 @@ export interface ControlPlanePort { * commits. */ readonly pipelinesStreamingEvents?: boolean; + readonly pipelinedEventTypes?: ReadonlySet; /** Commits the queued streaming deltas now, without waiting for the batch timer. */ flushStreamingEvents?(): void; normalizeReplayPayload?(payload: PrpEvent["payload"]): PrpEvent["payload"]; diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-login-text.test.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-login-text.test.ts new file mode 100644 index 00000000000..5ad29ba2763 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-login-text.test.ts @@ -0,0 +1,107 @@ +import { spawn } from "node:child_process"; +import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:http"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import type { AcpRuntimeEvent } from "acpx/runtime"; +import { expect, it, vi } from "vitest"; + +import { openCodexAcpxRuntime } from "./acpx-runtime-adapter.js"; +import type { VerifiedAcpxCommandLease } from "./installation-integrity.js"; +import { resolveQualifiedAcpxProfile } from "./qualified-profiles.js"; +import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js"; + +const QUOTED_LOGIN_TEXT = 'The probe exited 1: "Not logged in ยท Please run /login". I posted its output.'; + +async function runTurn() { + const root = await mkdtemp(join(tmpdir(), "claude-login-text-")); + const home = join(root, "home"), cwd = join(root, "workspace"), config = join(home, ".claude"); + await Promise.all([mkdir(config, { recursive: true }), mkdir(cwd)]); + let sequence = 0; + const api = createServer(async (request, response) => { + let raw = ""; + for await (const chunk of request) raw += chunk; + if (request.method === "GET") { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ data: [], has_more: false })); + return; + } + if (request.url?.includes("count_tokens")) { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ input_tokens: 1 })); + return; + } + const body = JSON.parse(raw || "{}") as { model?: string; stream?: boolean }; + const model = body.model ?? "claude-sonnet-5"; + if (body.stream !== true) { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ id: "msg_fixture", type: "message", role: "assistant", model, + content: [{ type: "text", text: "OK" }], stop_reason: "end_turn", usage: { input_tokens: 1, output_tokens: 1 } })); + return; + } + const frames: Array> = [ + { type: "message_start", message: { id: `msg_${++sequence}`, type: "message", role: "assistant", model, content: [], + stop_reason: null, stop_sequence: null, usage: { input_tokens: 7, output_tokens: 0 } } }, + { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }, + { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: QUOTED_LOGIN_TEXT } }, + { type: "content_block_stop", index: 0 }, + { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 3 } }, + { type: "message_stop" }, + ]; + response.writeHead(200, { "content-type": "text/event-stream" }); + for (const frame of frames) response.write(`event: ${frame.type}\ndata: ${JSON.stringify(frame)}\n\n`); + response.end(); + }); + await new Promise(resolve => api.listen(0, "127.0.0.1", resolve)); + const address = api.address() as { port: number }; + + const entry = createRequire(import.meta.url).resolve("@agentclientprotocol/claude-agent-acp/dist/index.js"); + const command: VerifiedAcpxCommandLease = { + spawn: (args, input) => spawn(process.execPath, [entry, ...(args ?? [])], { ...input, detached: true, stdio: ["pipe", "pipe", "pipe"] }), + close: async () => undefined, + }; + const options: AcpxRuntimePortOpenOptions = { + command, + profile: resolveQualifiedAcpxProfile("claude", "claude-sonnet-5"), + cwd, + stateDirectory: join(root, "state"), + providerSessionKey: "claude-login-text", + permissionMode: "approve-all", + permissionPolicy: { autoApprove: ["read", "write", "execute", "other"], defaultAction: "approve" }, + launchEnvironment: { HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/bin:/bin", TMPDIR: root, + ANTHROPIC_API_KEY: "local-fixture-only", ANTHROPIC_BASE_URL: `http://127.0.0.1:${address.port}`, + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1", ENABLE_TOOL_SEARCH: "false" }, + credentialFenceFds: [42, 43] as const, + activateCredentialFenceOwner: async () => undefined, + systemInstructions: "Report the probe output.", + mcpServers: [], + retainFailedAdmissionCleanup: vi.fn(), + } as AcpxRuntimePortOpenOptions; + let port: Awaited> | undefined; + try { + port = await openCodexAcpxRuntime(options, { + awaitProviderOwnership: async () => undefined, + awaitProviderExit: child => new Promise(resolve => child.once("exit", () => resolve())), + }); + const turn = port.startTurn({ text: "Run the probe and report its output.", requestId: "turn-1", + onPermissionRequest: async () => ({ outcome: "allow_once" }) }); + const events: AcpRuntimeEvent[] = []; + for await (const event of turn.events) events.push(event); + return { result: await turn.result, events }; + } finally { + try { await port?.close({ reason: "sign-in hint verified" }); } + finally { + api.closeAllConnections(); + await new Promise(resolve => api.close(() => resolve())); + await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); + } + } +} + +it("completes a turn whose successful reply quotes the CLI's sign-in hint through the real ACP stream", async () => { + const { result, events } = await runTurn(); + expect(result).toMatchObject({ status: "completed", stopReason: "end_turn" }); + expect(JSON.stringify(events)).toContain("Please run /login"); +}, 60_000); diff --git a/packages/paperclip-runner/src/native-session-runtime.test.ts b/packages/paperclip-runner/src/native-session-runtime.test.ts index 93813aab14b..c5a8842fc5f 100644 --- a/packages/paperclip-runner/src/native-session-runtime.test.ts +++ b/packages/paperclip-runner/src/native-session-runtime.test.ts @@ -312,7 +312,8 @@ describe("executeNativeSession recovery", () => { }); /** A batching port whose queued deltas commit only when flushed: it has no timer. */ - const batchingDeltaFixture = (events: () => AsyncGenerator, commitDelta: (sourceSeq: number) => Promise = async () => {}) => { + const batchingDeltaFixture = (events: () => AsyncGenerator, commitDelta: (sourceSeq: number) => Promise = async () => {}, + pipelinedEventTypes?: ReadonlySet) => { const capabilities = { resume: true, typedEvents: true, steering: false, interruption: true, structuredResult: true }; const session: NativeSession = { identity: () => identity, @@ -335,6 +336,7 @@ describe("executeNativeSession recovery", () => { let queued: Array<() => void> = []; const port: ControlPlanePort = { pipelinesStreamingEvents: true, + ...(pipelinedEventTypes ? { pipelinedEventTypes } : {}), flushStreamingEvents() { log.push("flush"); const flushed = queued; @@ -345,7 +347,7 @@ describe("executeNativeSession recovery", () => { async appendEvent(event: PrpEvent, options) { if (event.sourceKind !== "runner") return { cursor: 0, highestContiguousSourceSeq: event.sourceSeq, disposition: "committed" }; log.push(`append:${event.sourceSeq}`); - if (event.eventType === "item.delta") { + if ((pipelinedEventTypes ?? new Set(["item.delta"])).has(event.eventType)) { expect(options?.streaming).toBe(true); await new Promise(resolve => queued.push(resolve)); await commitDelta(event.sourceSeq); @@ -375,6 +377,26 @@ describe("executeNativeSession recovery", () => { expect(execution).toMatchObject({ nativeEventCount: 7, highestContiguousSourceSeq: 5 }); }); + it.each([true, false])("starts progress appends without waiting only when the port pipelines them (pipelined=%s)", async pipelined => { + const progress = (sourceSeq: number) => runnerEvent(sourceSeq, "tool.execution.progressed", { name: "build", status: "running" }); + const f = batchingDeltaFixture(async function* () { + for (const sourceSeq of [1, 2]) yield progress(sourceSeq); + yield streamedDelta(3); + yield runnerEvent(4, "run.result.proposed", result); + yield runnerEvent(5, "turn.completed"); + }, async () => {}, pipelined ? new Set(["item.delta", "tool.execution.progressed"]) : undefined); + const execution = await executeNativeSession({ input: preparedInput(), backend: f.backend, controlPlane: f.port, + runnerInstanceId: "runner-recovery", controlPlaneInstanceId: "control-recovery" }); + expect(f.log.slice(0, 4)).toEqual(["append:1", "append:2", "append:3", "flush"]); + if (pipelined) { + expect(f.log.indexOf("append:2")).toBeLessThan(f.log.indexOf("committed:1")); + expect(f.log.indexOf("append:4")).toBeGreaterThan(Math.max(...[1, 2, 3].map(seq => f.log.indexOf(`committed:${seq}`)))); + } else { + expect(f.log).not.toContain("committed:1"); + } + expect(execution).toMatchObject({ highestContiguousSourceSeq: 5 }); + }); + it("joins pending delta appends before a failed turn settles", async () => { let releaseCommit = () => {}; const commitReleased = new Promise(resolve => { releaseCommit = resolve; }); diff --git a/packages/paperclip-runner/src/native-session-runtime.ts b/packages/paperclip-runner/src/native-session-runtime.ts index 218f2ab52dc..e5aa6c1a5f0 100644 --- a/packages/paperclip-runner/src/native-session-runtime.ts +++ b/packages/paperclip-runner/src/native-session-runtime.ts @@ -1265,6 +1265,7 @@ async function consumeTurn( // delta's receipt settles. Every other event, and every result, waits for // the receipts of the deltas before it. const pipelinesDeltas = controlPlane.pipelinesStreamingEvents === true; + const pipelinedEventTypes: ReadonlySet = controlPlane.pipelinedEventTypes ?? new Set(["item.delta"]); let pendingDeltas: Promise[] = []; let deltaFailure = null as { error: unknown } | null; const settlePendingDeltas = async () => { @@ -1450,7 +1451,7 @@ async function consumeTurn( // A failed delta stops the turn before any later event is appended. if (deltaFailure) throw deltaFailure.error; let receipt: AppendedEventReceipt | null = null; - if (pipelinesDeltas && event.eventType === "item.delta") { + if (pipelinesDeltas && pipelinedEventTypes.has(event.eventType)) { const pending = controlPlane.appendEvent(event, { signal: appendAbort.signal, streaming: true }); const settled = pending.then(() => undefined, (error: unknown) => { deltaFailure ??= { error }; }); outstandingDeltas.add(settled); diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index efab7ad18d8..825867d65bb 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2976,7 +2976,7 @@ export { TASK_IDENTITY_CHANGED_FIELD, issueActivityChangesTaskIdentity, } from "./issue-activity-identity.js"; -export { recognizeLinkPreview, type LinkPreviewTarget, type LinkPreviewState, type LinkPreview, type LinkPreviewResult } from "./link-preview.js"; +export { LINK_PREVIEW_BATCH_LIMIT, type LinkPreviewBatchResult, recognizeLinkPreview, type LinkPreviewTarget, type LinkPreviewState, type LinkPreview, type LinkPreviewResult } from "./link-preview.js"; export * from "./mcp-apps.js"; export * from "./tool-call-progress.js"; export * from "./mcp-skills.js"; diff --git a/packages/shared/src/link-preview.ts b/packages/shared/src/link-preview.ts index ffa5eb960a7..b7431d4c30a 100644 --- a/packages/shared/src/link-preview.ts +++ b/packages/shared/src/link-preview.ts @@ -18,10 +18,13 @@ export interface LinkPreview { export interface LinkPreviewResult { preview: LinkPreview | null; - /** Demand-driven cache lifetime; this does not schedule a refresh. */ + /** Remaining cache lifetime; zero means stale. This does not schedule a refresh. */ maxAgeMs: number; } +export const LINK_PREVIEW_BATCH_LIMIT = 50; +export interface LinkPreviewBatchResult { results: Record } + /** Recognition only. Never contacts a remote service or changes navigation. */ export function recognizeLinkPreview(href: string | null | undefined): LinkPreviewTarget | null { if (!href || href.length > 2048) return null; diff --git a/patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch b/patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch index df6f4c77e00..b7e7589c717 100644 --- a/patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch +++ b/patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch @@ -1,5 +1,5 @@ diff --git a/dist/acp-agent.js b/dist/acp-agent.js -index 0214a50..73f0c16 100644 +index 0214a50..a68121d 100644 --- a/dist/acp-agent.js +++ b/dist/acp-agent.js @@ -2490,11 +2490,88 @@ export class ClaudeAcpAgent { @@ -117,7 +117,18 @@ index 0214a50..73f0c16 100644 await subagents.finishTask(message.task_id, message.patch.status, sendUpdate); session.liveBackgroundTasks.delete(message.task_id); } -@@ -2922,9 +3002,19 @@ export class ClaudeAcpAgent { +@@ -2794,7 +2874,9 @@ export class ClaudeAcpAgent { + session.pendingGoalUpdate = undefined; + const goalCommandFailed = message.is_error || + message.stop_reason === "refusal" || +- ("result" in message && message.result.includes("Please run /login")); ++ ("result" in message && ++ message.is_error && ++ message.result.includes("Please run /login")); + if (goalCommandFailed) { + await this.publishGoal(params.sessionId, pendingGoalUpdate.previous ?? null); + } +@@ -2922,9 +3004,19 @@ export class ClaudeAcpAgent { amount: message.total_cost_usd, currency: "USD", }, @@ -140,7 +151,16 @@ index 0214a50..73f0c16 100644 }, }); } -@@ -4506,6 +4596,48 @@ export class ClaudeAcpAgent { +@@ -3081,7 +3173,7 @@ export class ClaudeAcpAgent { + } + switch (message.subtype) { + case "success": { +- if (message.result.includes("Please run /login")) { ++ if (message.is_error && message.result.includes("Please run /login")) { + await failActiveWithSessionFailure("auth_required", RequestError.authRequired(), message.result); + break; + } +@@ -4506,6 +4598,48 @@ export class ClaudeAcpAgent { * `$/cancel_request`, and our local abort race settles even if the client * ignores it. A `cancelled` outcome, request rejection, and local abort all * surface the same "Tool use aborted" the callers already expect. */ @@ -189,7 +209,7 @@ index 0214a50..73f0c16 100644 async requestPermissionFromClient(params, toolName, signal, parentToolUseId, ownerSessionId = params.sessionId) { if (signal.aborted) throw new Error("Tool use aborted"); -@@ -5311,14 +5443,24 @@ export class ClaudeAcpAgent { +@@ -5311,14 +5445,24 @@ export class ClaudeAcpAgent { settingSources: ["user", "project", "local"], ...(thinking !== undefined && { thinking }), ...userProvidedOptions, @@ -215,7 +235,7 @@ index 0214a50..73f0c16 100644 ...mcpServers, ...(fileChangeAuditSupport ? { [FILE_CHANGE_AUDIT_SERVER_NAME]: fileChangeAuditSupport.mcpServer } -@@ -5329,6 +5471,16 @@ export class ClaudeAcpAgent { +@@ -5329,6 +5473,16 @@ export class ClaudeAcpAgent { allowDangerouslySkipPermissions: ALLOW_BYPASS, permissionMode: initialPermissionMode, canUseTool: this.canUseTool(sessionId), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 05644099489..c533906b86f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -16,7 +16,7 @@ overrides: patchedDependencies: '@agentclientprotocol/claude-agent-acp@0.73.0': - hash: syoits7l7g3sthy3olttp2fv24 + hash: wnht4big7mwol7j2skbsa5mefq path: patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch '@agentclientprotocol/codex-acp@1.6.2': hash: 2iynuypg76nxmydiylgtffhr7e @@ -186,7 +186,7 @@ importers: dependencies: '@agentclientprotocol/claude-agent-acp': specifier: ^0.73.0 - version: 0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) + version: 0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) '@anthropic-ai/sdk': specifier: 0.129.0 version: 0.129.0(zod@4.6.7) @@ -511,7 +511,7 @@ importers: dependencies: '@agentclientprotocol/claude-agent-acp': specifier: 0.73.0 - version: 0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) + version: 0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) '@agentclientprotocol/codex-acp': specifier: 1.6.2 version: 1.6.2(patch_hash=2iynuypg76nxmydiylgtffhr7e) @@ -904,7 +904,7 @@ importers: version: 0.5.0 '@agentclientprotocol/claude-agent-acp': specifier: 0.73.0 - version: 0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) + version: 0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) '@agentclientprotocol/codex-acp': specifier: 1.6.2 version: 1.6.2(patch_hash=2iynuypg76nxmydiylgtffhr7e) @@ -9548,7 +9548,7 @@ snapshots: '@adobe/css-tools@4.5.0': {} - '@agentclientprotocol/claude-agent-acp@0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))': + '@agentclientprotocol/claude-agent-acp@0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))': dependencies: '@agentclientprotocol/sdk': 1.4.0(zod@4.4.3) '@anthropic-ai/claude-agent-sdk': 0.3.286(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(zod@4.4.3) diff --git a/scripts/confirm-canary-publication.sh b/scripts/confirm-canary-publication.sh index 47ace380829..9ab2d6ecc1f 100755 --- a/scripts/confirm-canary-publication.sh +++ b/scripts/confirm-canary-publication.sh @@ -60,6 +60,7 @@ else fi release_info "==> Installing paperclipai@${version} into a clean prefix..." -verify_npm_installable "paperclipai@${version}" "$version" || release_fail "paperclipai@${version} did not install cleanly" +wait_for_npm_installable "paperclipai@${version}" "$version" "${NPM_INSTALL_VERIFY_TIMEOUT_SECONDS:-1200}" "${NPM_INSTALL_VERIFY_DELAY_SECONDS:-30}" \ + || release_fail "paperclipai@${version} did not install cleanly" push_release_tag_at "$PUBLISH_REMOTE" "$tag_name" "$source_sha" diff --git a/scripts/release-lib.sh b/scripts/release-lib.sh index 798e34ba586..f2db11d0973 100644 --- a/scripts/release-lib.sh +++ b/scripts/release-lib.sh @@ -572,12 +572,18 @@ wait_for_npm_package_versions() { verify_npm_installable() { local package_spec="$1" local expected_version="$2" + local install_timeout_seconds="${3:-}" local install_dir local installed_version + local install=(npm install --prefix "" "$package_spec" --no-audit --no-fund) install_dir="$(mktemp -d "${TMPDIR:-/tmp}/paperclip-release-install.XXXXXX")" + install[3]="$install_dir" + if [ -n "$install_timeout_seconds" ] && command -v timeout >/dev/null 2>&1; then + install=(timeout --kill-after=10 "$install_timeout_seconds" "${install[@]}") + fi - if ! npm install --prefix "$install_dir" "$package_spec" --no-audit --no-fund; then + if ! "${install[@]}"; then rm -rf "$install_dir" return 1 fi @@ -588,6 +594,29 @@ verify_npm_installable() { [ "$installed_version" = "$expected_version" ] } +wait_for_npm_installable() { + local package_spec="$1" + local expected_version="$2" + local deadline_seconds="${3:-1200}" + local delay_seconds="${4:-30}" + local deadline=$(( $(date +%s) + deadline_seconds )) + local attempt=1 + local remaining + + while :; do + remaining=$(( deadline - $(date +%s) )) + [ "$remaining" -gt 0 ] || return 1 + if verify_npm_installable "$package_spec" "$expected_version" "$remaining"; then + return 0 + fi + remaining=$(( deadline - $(date +%s) )) + [ "$remaining" -gt 0 ] || return 1 + release_warn "${package_spec} did not install yet (attempt ${attempt}, ${remaining}s left); a large tarball can lag its metadata. Retrying in $(( delay_seconds < remaining ? delay_seconds : remaining ))s." + sleep $(( delay_seconds < remaining ? delay_seconds : remaining )) + attempt=$((attempt + 1)) + done +} + wait_for_release_registry_state() { local attempts="${1:-12}" local delay_seconds="${2:-5}" diff --git a/scripts/release-lib.test.mjs b/scripts/release-lib.test.mjs index c890ffee0ac..3e78f3e8826 100644 --- a/scripts/release-lib.test.mjs +++ b/scripts/release-lib.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -395,15 +395,22 @@ test("the workflow budget fails closed after the last registry check", () => { assert.equal(result.calls.match(/^sleep /gm)?.length, budget.verifyAttempts - 1); }); -test("every publish job budgets for build time and four delayed packages", () => { +test("every publish job budgets for build time, four delayed packages and the install deadline", () => { const { verifyAttempts, verifyDelaySeconds } = workflowVerifyBudget(); const pollingSeconds = (verifyAttempts - 1) * verifyDelaySeconds; - const requiredSeconds = 30 * 60 + 4 * pollingSeconds; + const releaseScript = readFileSync(new URL("./release.sh", import.meta.url), "utf8"); + const installDeadlineSeconds = Number(releaseScript.match(/NPM_INSTALL_VERIFY_TIMEOUT_SECONDS:-(\d+)/)?.[1]); + assert.ok(installDeadlineSeconds > 0); - for (const job of ["publish_canary", "publish_nightly", "publish_beta", "publish_stable"]) { + for (const [job, requiredSeconds] of [ + ["publish_canary", 30 * 60 + 4 * pollingSeconds], + ["publish_nightly", 30 * 60 + 4 * pollingSeconds + installDeadlineSeconds], + ["publish_beta", 30 * 60 + 4 * pollingSeconds + installDeadlineSeconds], + ["publish_stable", 30 * 60 + 4 * pollingSeconds + installDeadlineSeconds], + ]) { const body = releaseWorkflow.split(`\n ${job}:\n`)[1]?.split(/\n [a-z_]+:\n/)[0] ?? ""; const timeoutMinutes = Number(body.match(/^ timeout-minutes: (\d+)$/m)?.[1]); - assert.ok(timeoutMinutes * 60 > requiredSeconds, `${job} must leave time beyond build and polling`); + assert.ok(timeoutMinutes * 60 > requiredSeconds, `${job} must leave time beyond build, polling and the install deadline`); } }); @@ -497,3 +504,47 @@ test("a canary version is accepted only for the master commit whose position num const side = fixture.git(fixture.repo, "rev-parse", "HEAD").trim(); assert.throws(() => confirm("2026.1116.0-canary.2600", side), /is not on origin\/master/); }); + +function installRetryFixture({ failures = 0, hangSeconds = 0 }) { + const dir = mkdtempSync(join(tmpdir(), "paperclip-install-retry-")); + const bin = join(dir, "bin"); + mkdirSync(bin); + const counter = join(dir, "attempts"); + writeFileSync(counter, "0"); + writeExecutable(join(bin, "npm"), `#!/usr/bin/env bash +n=$(( $(cat "${counter}") + 1 )); echo "$n" > "${counter}" +if [ "${hangSeconds}" -gt 0 ]; then sleep "${hangSeconds}"; fi +if [ "$n" -le "${failures}" ]; then echo "npm error code E404" >&2; exit 1; fi +prefix="$3"; mkdir -p "$prefix/node_modules/paperclipai" +printf '{"version":"1.2.3"}' > "$prefix/node_modules/paperclipai/package.json" +`); + const run = (deadline, delay = 0) => { + const started = Date.now(); + const result = spawnSync("bash", ["-c", `source "${repoRoot}/scripts/release-lib.sh"; wait_for_npm_installable paperclipai@canary 1.2.3 ${deadline} ${delay}`], + { encoding: "utf8", env: { ...process.env, PATH: `${bin}:${process.env.PATH}` } }); + return { status: result.status, seconds: (Date.now() - started) / 1000, attempts: Number(readFileSync(counter, "utf8")), stderr: result.stderr }; + }; + return { run }; +} + +test("a release install is retried while its tarball lags the metadata", () => { + const recovered = installRetryFixture({ failures: 3 }).run(60); + assert.equal(recovered.status, 0); + assert.equal(recovered.attempts, 4); + assert.match(recovered.stderr, /attempt 3, \d+s left/); + assert.equal(installRetryFixture({}).run(60).attempts, 1); +}); + +const hasTimeoutCommand = spawnSync("bash", ["-c", "command -v timeout"], { encoding: "utf8" }).status === 0; + +test("install retries stop at the deadline", () => { + const exhausted = installRetryFixture({ failures: 1000 }).run(3, 1); + assert.notEqual(exhausted.status, 0); + assert.ok(exhausted.seconds < 8, `took ${exhausted.seconds}s`); +}); + +test("an install that hangs is stopped at the deadline", { skip: !hasTimeoutCommand && "needs the timeout command (GNU coreutils)" }, () => { + const hung = installRetryFixture({ hangSeconds: 120 }).run(3, 1); + assert.notEqual(hung.status, 0); + assert.ok(hung.seconds < 20, `a hung install outlived the deadline: ${hung.seconds}s`); +}); diff --git a/scripts/release.sh b/scripts/release.sh index 79b276844d8..6b7e71d8f87 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -485,7 +485,7 @@ else fi release_info " Installing paperclipai@$DIST_TAG into a clean prefix..." - if ! verify_npm_installable "paperclipai@$DIST_TAG" "$TARGET_PUBLISH_VERSION"; then + if ! wait_for_npm_installable "paperclipai@$DIST_TAG" "$TARGET_PUBLISH_VERSION" "${NPM_INSTALL_VERIFY_TIMEOUT_SECONDS:-1200}" "${NPM_INSTALL_VERIFY_DELAY_SECONDS:-30}"; then release_fail "paperclipai@$DIST_TAG did not install cleanly at expected version ${TARGET_PUBLISH_VERSION}" fi release_info " โœ“ Clean-prefix install resolved ${TARGET_PUBLISH_VERSION}" diff --git a/server/src/__tests__/attention-retention-work.test.ts b/server/src/__tests__/attention-retention-work.test.ts index e13d8a1931c..48a11fa94c9 100644 --- a/server/src/__tests__/attention-retention-work.test.ts +++ b/server/src/__tests__/attention-retention-work.test.ts @@ -626,7 +626,7 @@ const delay = DEFAULT_DECISION_ARCHIVE_DAYS * 86_400_000; expect(batch.deferredRootIds.size).toBe(0); expect(Boolean(batch.attention.get(root.id)?.blockingTreeLive)).toBe(kind !== "completed"); expect(parameterCounts.length).toBeLessThanOrEqual(100); - })); + }), 60_000); it("does not archive an unknown truncated blocker tree during its fresh check", async () => { const root = await insertIssue("blocked"); diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.ts index 0a662626ef2..62379bdc484 100644 --- a/server/src/__tests__/heartbeat-process-recovery.test.ts +++ b/server/src/__tests__/heartbeat-process-recovery.test.ts @@ -10536,7 +10536,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { expect(events[0]).toMatchObject({ eventType: "lifecycle", stream: "system", - level: "warn", + level: "info", message: "run interrupted by board comment", payload: expect.objectContaining({ issueId, diff --git a/server/src/__tests__/heartbeat-stop-queued-task.test.ts b/server/src/__tests__/heartbeat-stop-queued-task.test.ts index 56fcc97aa87..1de25a8cdff 100644 --- a/server/src/__tests__/heartbeat-stop-queued-task.test.ts +++ b/server/src/__tests__/heartbeat-stop-queued-task.test.ts @@ -1,4 +1,6 @@ import { randomUUID } from "node:crypto"; +import express from "express"; +import request from "supertest"; import { eq, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { @@ -12,6 +14,9 @@ import { createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, + heartbeatRunEvents, + environmentLeases, + issueRecoveryActions, issues, } from "@paperclipai/db"; import { @@ -23,10 +28,29 @@ import { drainHeartbeatRunsToQuiescence } from "./helpers/drain-heartbeat-runs.j import { truncateTablesWithDeadlockRetry } from "./helpers/truncate-with-deadlock-retry.js"; import { heartbeatService } from "../services/heartbeat.ts"; import { returnStoppedWaitingTaskToTodo } from "../services/heartbeat/stopped-waiting-task.ts"; +import { executionProjectionsForRuns } from "../services/execution-projection.ts"; +import { taskInterruptionPresentation } from "../services/task-interruption-presentation.ts"; +import { agentRoutes } from "../routes/agents.ts"; +import { issueRoutes } from "../routes/issues.ts"; +import { errorHandler } from "../middleware/index.ts"; +import { issueService } from "../services/issues.ts"; import type { AdapterExecutionContext, AdapterExecutionResult } from "../adapters/index.ts"; import { HttpError } from "../errors.ts"; +import { settleCancelledLegacyPreparation } from "../services/legacy-execution-recovery.ts"; +import { settleUnrecoverableExecutions } from "../services/execution-recovery-resolution.ts"; const gates = vi.hoisted(() => new Map void) | null>()); +const preparation = vi.hoisted(() => ({ + beforeSession: undefined as (() => Promise) | undefined, + onExecution: undefined as ((context: AdapterExecutionContext) => Promise) | undefined, +})); +vi.mock("../services/heartbeat/session-preparation.js", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, prepareHeartbeatSession: async (...args: Parameters) => { + await preparation.beforeSession?.(); + return actual.prepareHeartbeatSession(...args); + } }; +}); const mockAdapterExecute = vi.hoisted(() => vi.fn(async (context: AdapterExecutionContext): Promise => { const issueId = (context.context as Record | undefined)?.issueId; @@ -34,6 +58,7 @@ const mockAdapterExecute = vi.hoisted(() => if (typeof issueId === "string" && gates.get(issueId) === null) { await new Promise((resolve) => gates.set(issueId, resolve)); } + await preparation.onExecution?.(context); return { exitCode: 0, signal: null, timedOut: false, errorMessage: null, summary: "ok", provider: "test", model: "test" }; }), ); @@ -63,6 +88,8 @@ describeEmbeddedPostgres("Stop on a task whose run is still waiting in line", () }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); afterEach(async () => { + preparation.beforeSession = undefined; + preparation.onExecution = undefined; for (const release of gates.values()) release?.(); gates.clear(); await drainHeartbeatRunsToQuiescence(db, heartbeat); @@ -104,6 +131,167 @@ describeEmbeddedPostgres("Stop on a task whose run is still waiting in line", () return { issue, run: run! }; } + it("confirms Stop during preparation and continues once from a later message", async () => { + const { companyId, agentId } = await seed(); + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + req.actor = { type: "board", source: "session", userId: "responsible-user", companyIds: [companyId], + memberships: [{ companyId, membershipRole: "admin", status: "active" }], isInstanceAdmin: false }; + next(); + }); + app.use("/api", agentRoutes(db, {})); + const unusedStorage = async () => { throw new Error("Stop and comment routes must not access object storage"); }; + app.use("/api", issueRoutes(db, { provider: "local_disk", putFile: unusedStorage, + getObject: unusedStorage, headObject: unusedStorage, deleteObject: unusedStorage })); + app.use(errorHandler); + let entered = false; + let release!: () => void; + const released = new Promise(resolve => { release = resolve; }); + preparation.beforeSession = async () => { entered = true; await released; }; + try { + const { issue, run } = await assignAndWake(companyId, agentId, "Accidental submission"); + await vi.waitFor(() => expect(entered).toBe(true), { timeout: 10_000 }); + const stop = await request(app).post(`/api/heartbeat-runs/${run.id}/cancel`).send({}); + expect(stop.status).toBe(200); + expect(stop.body.status).toBe("cancelled"); + // Terminal status alone must not confirm a Stop while preparation owns it. + expect(stop.body.resultJson.executionCancellation).toMatchObject({ state: "requested" }); + release(); + await drainHeartbeatRunsToQuiescence(db, heartbeat); + const settled = await request(app).get(`/api/heartbeat-runs/${run.id}`); + expect(settled.status).toBe(200); + expect(settled.body.resultJson.executionCancellation).toMatchObject({ state: "acknowledged", proof: "preparation_settled", acknowledgedAt: expect.any(String) }); + expect(executedIssueIds()).not.toContain(issue.id); + expect((await executionProjectionsForRuns(db, companyId, [run.id])).get(run.id)).toMatchObject({ + phase: "completed", label: "Stopped", cause: null, + nextAction: "Send a new message to continue from saved work.", + }); + expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issue.id))) + .filter(action => action.status === "active" || action.status === "escalated")).toHaveLength(0); + const [task] = await db.select().from(issues).where(eq(issues.id, issue.id)); + expect(await taskInterruptionPresentation(db, task)).toMatchObject({ state: "resolved", canRetry: false }); + const events = await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, run.id)); + expect(events.find(event => event.message === "run cancelled")?.level).toBe("info"); + await heartbeat.reconcileStrandedAssignedIssues(); + await drainHeartbeatRunsToQuiescence(db, heartbeat); + expect(executedIssueIds()).not.toContain(issue.id); + + preparation.beforeSession = undefined; + // Simulate the agent's final reply and task completion. A raw adapter exit + // without a task disposition correctly triggers a separate follow-up. + preparation.onExecution = async context => { + await context.onEvent?.({ eventType: "item.completed", stream: "stdout", level: "info", payload: { + prpEvent: { sourceEventId: `fixture:${context.runId}:final`, payload: { kind: "agentMessage", channel: "final", text: "ok" } }, + } }); + await issueService(db).update(issue.id, { status: "done" }); + }; + const message = await request(app).post(`/api/issues/${issue.id}/comments`).send({ body: "Continue with the corrected request." }); + expect(message.status).toBe(201); + // Comment dispatch is asynchronous; wait for its wake to register before + // draining the process-wide executor set or tearing down its task rows. + await vi.waitFor(() => expect(executedIssueIds()).toContain(issue.id), { timeout: 10_000 }); + await drainHeartbeatRunsToQuiescence(db, heartbeat); + expect(executedIssueIds().filter(id => id === issue.id)).toHaveLength(1); + expect((await heartbeat.getRun(run.id))?.status).toBe("cancelled"); + } finally { release(); } + }, 60_000); + + it.each([false, true])("confirms Stop only after lease release, with prior automatic disposition: %s", async (disposeFirst) => { + const { companyId, agentId } = await seed(); + const [issue] = await db.insert(issues).values({ companyId, assigneeAgentId: agentId, title: "Retained preparation", status: "in_progress" }).returning(); + const requestedAt = new Date().toISOString(); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: issue.id, + status: "cancelled", runtimeMode: "legacy", startedAt: new Date(), finishedAt: new Date(), errorCode: "cancelled", + contextSnapshot: { issueId: issue.id }, resultJson: { + cancellation: { source: "operator", expected: true, initiator: { type: "user", id: "responsible-user" }, reason: "Stop", recordedAt: requestedAt }, + executionCancellation: { state: "requested", requestedAt }, + } }).returning(); + const [lease] = await db.insert(environmentLeases).values({ companyId, issueId: issue.id, heartbeatRunId: run.id, + provider: "local", status: "active" }).returning(); + expect(await settleCancelledLegacyPreparation(db, { run, providerDispatchStarted: false })).toBeNull(); + expect((await heartbeat.getRun(run.id))?.resultJson?.executionCancellation).toEqual({ state: "requested", requestedAt }); + expect((await executionProjectionsForRuns(db, companyId, [run.id])).get(run.id)?.phase).toBe("failed"); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true }); + + if (disposeFirst) { + await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issue.id, + kind: "active_run_watchdog", status: "active", ownerType: "system", returnOwnerAgentId: agentId, + cause: "legacy_execution_requires_reconciliation", fingerprint: `legacy-execution:${run.id}`, + nextAction: "Preserve this stopped execution until its outcome is known.", evidence: { runId: run.id } }); + await settleUnrecoverableExecutions(db); + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issue.id)); + expect(hold).toMatchObject({ status: "resolved", outcome: "blocked", + evidence: { automaticRecovery: { replay: "blocked" }, legacyCancellationBlock: { runId: run.id } } }); + expect((await executionProjectionsForRuns(db, companyId, [run.id])).get(run.id)?.phase).toBe("recovery_needed"); + } + + await db.update(environmentLeases).set({ status: "released", releasedAt: new Date(), cleanupStatus: "success" }).where(eq(environmentLeases.id, lease.id)); + const settled = await settleCancelledLegacyPreparation(db, { run, providerDispatchStarted: false }); + expect(settled?.resultJson?.executionCancellation).toMatchObject({ state: "acknowledged", proof: "preparation_settled", requestedAt }); + expect((await executionProjectionsForRuns(db, companyId, [run.id])).get(run.id)).toMatchObject({ phase: "completed", label: "Stopped" }); + const [settledIssue] = await db.select().from(issues).where(eq(issues.id, issue.id)); + expect(settledIssue.status).toBe("in_progress"); + expect(await taskInterruptionPresentation(db, settledIssue)).toMatchObject({ state: "resolved", canRetry: false }); + expect(executedIssueIds()).not.toContain(issue.id); + }); + + it.each(["2026-01-01T00:00:00.000Z", null])("retains the Stop hold after dispatch handoff without an invocation event: %s", async (handedOffAt) => { + const { companyId, agentId } = await seed(); + const [issue] = await db.insert(issues).values({ companyId, assigneeAgentId: agentId, + title: "Dispatch handoff before adapter entry", status: "in_progress" }).returning(); + const requestedAt = new Date().toISOString(); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: issue.id, + status: "cancelled", runtimeMode: "legacy", startedAt: new Date(), finishedAt: new Date(), errorCode: "cancelled", + contextSnapshot: { issueId: issue.id }, runnerProfileJson: { adapterDispatch: { adapterType: "codex_local" } }, + resultJson: { + cancellation: { source: "operator", expected: true, initiator: { type: "user", id: "responsible-user" }, + reason: "Stop", recordedAt: requestedAt }, + executionCancellation: { state: "requested", requestedAt }, + } }).returning(); + const [hold] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issue.id, + kind: "active_run_watchdog", status: "active", ownerType: "system", returnOwnerAgentId: agentId, + cause: "legacy_execution_requires_reconciliation", fingerprint: `legacy-execution:${run.id}`, + nextAction: "Preserve this stopped execution until its outcome is known.", evidence: { runId: run.id } }).returning(); + // The old owner has a stale snapshot. The replacement has passed the gate, + // but has not recorded adapter.invoke or a process identity yet. + await db.update(heartbeatRuns).set({ usageJson: { budgetDispatch: { handedOffAt } }, executionStage: "dispatching" }) + .where(eq(heartbeatRuns.id, run.id)); + expect(await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, run.id))).toEqual([]); + expect(await settleCancelledLegacyPreparation(db, { run, providerDispatchStarted: false })).toBeNull(); + const stopped = await heartbeat.getRun(run.id); + expect(stopped?.resultJson).toEqual(run.resultJson); + const [retained] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold.id)); + expect(retained).toMatchObject({ status: "active", outcome: null, evidence: hold.evidence }); + expect((await executionProjectionsForRuns(db, companyId, [run.id])).get(run.id)?.phase).not.toBe("completed"); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed" }); + expect(executedIssueIds()).not.toContain(issue.id); + }); + + it("preserves a system cancellation's recovery delivery when preparation settles", async () => { + const { companyId, agentId } = await seed(); + const [issue] = await db.insert(issues).values({ companyId, assigneeAgentId: agentId, + title: "Stale continuation", status: "in_progress" }).returning(); + const requestedAt = new Date().toISOString(); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: issue.id, + status: "cancelled", runtimeMode: "legacy", startedAt: new Date(), finishedAt: new Date(), + contextSnapshot: { issueId: issue.id }, resultJson: { + cancellation: { source: "control_plane", expected: true, initiator: { type: "system" }, + reason: "continuation_task_ownership_changed", recordedAt: requestedAt }, + executionCancellation: { state: "requested", requestedAt }, + } }).returning(); + const [hold] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issue.id, + kind: "active_run_watchdog", status: "resolved", outcome: "blocked", ownerType: "system", returnOwnerAgentId: agentId, + cause: "legacy_execution_requires_reconciliation", fingerprint: `legacy-execution:${run.id}`, + nextAction: "Continue saved input through recovery.", evidence: { runId: run.id, + automaticRecovery: { policy: "preserve_without_replay_v1", replay: "blocked", continuationDelivery: "pending" } } }).returning(); + const result = await settleCancelledLegacyPreparation(db, { run, providerDispatchStarted: false }); + expect(result?.resultJson?.executionCancellation).toEqual({ state: "requested", requestedAt }); + const [settled] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold.id)); + expect(settled.evidence.automaticRecovery).toEqual({ policy: "preserve_without_replay_v1", + replay: "allowed", continuationDelivery: "pending" }); + }); + it.each(["todo", "in_progress"] as const)("takes a %s task out of line in one Stop and still promotes the agent's next task", async (waitingStatus) => { const { companyId, agentId } = await seed(); const busy = randomUUID(); diff --git a/server/src/__tests__/helpers/recovery-population.ts b/server/src/__tests__/helpers/recovery-population.ts index 16947d39334..15d566d813b 100644 --- a/server/src/__tests__/helpers/recovery-population.ts +++ b/server/src/__tests__/helpers/recovery-population.ts @@ -15,9 +15,11 @@ export type RecoveryPopulation = { export async function seedRecoveryPopulation(db: Db, companyId: string, counts: { agents: number; inReview: number; inProgress?: number; todo?: number; recoveryActions?: number; terminated?: number; + /** False keeps every agent from starting a run, for suites that fake timers. */ + wakeOnDemand?: boolean; }): Promise { const config = { adapterType: "process", adapterConfig: { command: process.execPath, args: ["-e", "0"], cwd: process.cwd() }, - runtimeConfig: { heartbeat: { enabled: false, intervalSec: 0, wakeOnDemand: true } }, role: "engineer" }; + runtimeConfig: { heartbeat: { enabled: false, intervalSec: 0, wakeOnDemand: counts.wakeOnDemand ?? true } }, role: "engineer" }; const [ceo] = await db.insert(agents).values({ ...config, companyId, name: "Chief", status: "idle" }).returning({ id: agents.id }); const managers = await db.insert(agents).values(Array.from({ length: 6 }, (_, index) => ({ ...config, companyId, name: `Manager ${index}`, status: "idle", reportsTo: ceo!.id }))).returning({ id: agents.id }); diff --git a/server/src/__tests__/issue-recovery-idle-backstop.test.ts b/server/src/__tests__/issue-recovery-idle-backstop.test.ts index baf8fd03798..870459fa0d7 100644 --- a/server/src/__tests__/issue-recovery-idle-backstop.test.ts +++ b/server/src/__tests__/issue-recovery-idle-backstop.test.ts @@ -1,7 +1,7 @@ import { setImmediate as immediate } from "node:timers/promises"; import { and, eq, sql } from "drizzle-orm"; import { expect, it, vi } from "vitest"; -import { agents, heartbeatRuns, issues } from "@paperclipai/db"; +import { agentWakeupRequests, agents, heartbeatRuns, issues } from "@paperclipai/db"; import { workSignalDebug } from "@paperclipai/db/work-signal-debug"; import { ISSUE_RECOVERY_BACKSTOP_MS, ISSUE_RECOVERY_FULL_BACKSTOP_MS, notifyIssueGraphRecovery } from "../services/issue-recovery-notifications.js"; @@ -14,16 +14,32 @@ import { seedRecoveryPopulation } from "./helpers/recovery-population.js"; vi.hoisted(() => { process.env.PAPERCLIP_DEBUG_WORK_SIGNALS = "stranded-assignments:1"; }); const MINUTE = 60_000; +const STEP_TIMEOUT_MS = 20_000; +const TEST_TIMEOUT_MS = 120_000; +const realSetTimeout = globalThis.setTimeout; +const realClearTimeout = globalThis.clearTimeout; type Recorded = { at: number; name: string; fields: Record }; +/** Fails with a message naming what it waited for instead of hanging. */ +function bounded(work: Promise, waitingFor: () => string): Promise { + let timer: ReturnType | undefined; + const expired = new Promise((_, reject) => { + timer = realSetTimeout(() => reject(new Error(`Timed out after ${STEP_TIMEOUT_MS} ms waiting for ${waitingFor()}`)), STEP_TIMEOUT_MS); + }); + return Promise.race([work, expired]).finally(() => realClearTimeout(timer)); +} + describeIssueRecovery("stranded-task checks at idle for a staging-shaped company", () => { const state = issueRecoveryFixture({ meter: true }); async function advance(ms: number) { const until = Date.now() + ms; while (Date.now() < until) { - await vi.advanceTimersByTimeAsync(Math.min(1000, until - Date.now())); - await Promise.allSettled([...state.passes]); await immediate(); + const at = new Date(Date.now()).toISOString(); + await bounded(vi.advanceTimersByTimeAsync(Math.min(1000, until - Date.now())), () => `simulated time to advance past ${at}`); + await bounded(Promise.allSettled([...state.passes]), + () => `delivery passes started by simulated ${at} to settle: ${state.pendingPassQueues().join(", ") || "none"}`); + await immediate(); } } @@ -53,21 +69,29 @@ describeIssueRecovery("stranded-task checks at idle for a staging-shaped company const checkedAt = (events: Recorded[], issueId: string) => events.find(event => event.name === "check" && event.fields.issueId === issueId)?.at ?? null; + /** The wakes recovery asked for on a task. No fixture agent takes on-demand + * wakes, so each is recorded as skipped and no real run starts under the + * faked clock (a run there could wait forever on a frozen timer). */ + const wakesFor = (companyId: string, issueId: string) => bounded(state.db.select({ id: agentWakeupRequests.id }) + .from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId), + sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`)), () => `the wake requests of task ${issueId} to be read`); + async function seed() { - const f = await state.fixture(); + const f = await bounded(state.fixture(), () => "the company to be created"); const population = await seedRecoveryPopulation(state.db, f.companyId, { agents: 50, inReview: 780, inProgress: 40, todo: 30, - recoveryActions: 12, terminated: 3 }); + recoveryActions: 12, terminated: 3, wakeOnDemand: false }); const [side] = await state.db.insert(issues).values({ companyId: f.companyId, title: "Finished side task", status: "done" }) .returning({ id: issues.id }); - const activity = () => state.db.transaction(tx => notifyIssueGraphRecovery(tx, { companyId: f.companyId, issueId: side!.id })); + const activity = () => bounded(state.db.transaction(tx => notifyIssueGraphRecovery(tx, { companyId: f.companyId, issueId: side!.id })), + () => "the unrelated activity hint to commit"); return { ...f, population, activity }; } async function boot() { - const f = await seed(); + const f = await bounded(seed(), () => "the staging-shaped population to be seeded"); const events = record(); vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); - await state.start({}); + await bounded(state.start({}), () => "the recovery workers to start"); await advance(10 * MINUTE); return { ...f, events, boot: summarize(events.splice(0)) }; } @@ -77,7 +101,7 @@ describeIssueRecovery("stranded-task checks at idle for a staging-shaped company const [held] = await state.db.insert(agents).values({ companyId: f.companyId, name: "Held worker", role: "engineer", status: "paused", lifecycleHolds: ["manual"], adapterType: "process", reportsTo: f.population.agentIds[1], createdAt: old, updatedAt: old, adapterConfig: { command: process.execPath, args: ["-e", "0"], cwd: process.cwd() }, - runtimeConfig: { heartbeat: { enabled: false, intervalSec: 0, wakeOnDemand: true } } }).returning({ id: agents.id }); + runtimeConfig: { heartbeat: { enabled: false, intervalSec: 0, wakeOnDemand: false } } }).returning({ id: agents.id }); const [waiting] = await state.db.insert(issues).values({ companyId: f.companyId, title: "Waits for its agent", status: "todo", assigneeAgentId: held!.id, createdAt: old, updatedAt: old }).returning({ id: issues.id }); return { held: held!, waiting: waiting! }; @@ -103,37 +127,34 @@ describeIssueRecovery("stranded-task checks at idle for a staging-shaped company expect(between.totalChecks).toBe(0); expect(between.statements).toBeLessThan(2_000); expect(hour.checks.backstop ?? 0).toBeLessThanOrEqual(f.population.inReview.length + 100); - }, 1_800_000); + }, TEST_TIMEOUT_MS); it("recovers a task whose hint was never sent within the backstop bound", async () => { const f = await boot(); const worker = f.population.agentIds[7]!; const now = new Date(); - const [missed] = await state.db.insert(issues).values({ companyId: f.companyId, title: "Created without a hint", status: "todo", - assigneeAgentId: worker, createdAt: now, updatedAt: now }).returning({ id: issues.id }); + const [missed] = await bounded(state.db.insert(issues).values({ companyId: f.companyId, title: "Created without a hint", status: "todo", + assigneeAgentId: worker, createdAt: now, updatedAt: now }).returning({ id: issues.id }), () => "the task without a hint to be created"); const window = await trickle(f, Math.ceil((ISSUE_RECOVERY_BACKSTOP_MS + MINUTE) / MINUTE) + 1); const checked = checkedAt(window.raw, missed!.id); expect(checked).not.toBeNull(); expect(checked! - now.getTime()).toBeLessThanOrEqual(ISSUE_RECOVERY_BACKSTOP_MS + 2 * MINUTE); - const runs = await state.db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), - sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${missed!.id}`)); - expect(runs.length).toBeGreaterThan(0); - }, 1_800_000); + expect(await wakesFor(f.companyId, missed!.id), "recovery did not ask for a wake of the missed task").not.toHaveLength(0); + }, TEST_TIMEOUT_MS); it("re-checks a task whose only change is outside its own rows within the hourly full pass", async () => { const f = await boot(); - const { held, waiting } = await heldTask(f); - await state.db.execute(sql`update agents set status = 'idle', lifecycle_holds = '[]'::jsonb where id = ${held.id}`); + const { held, waiting } = await bounded(heldTask(f), () => "the held agent and its waiting task to be seeded"); + await bounded(state.db.execute(sql`update agents set status = 'idle', lifecycle_holds = '[]'::jsonb where id = ${held.id}`), + () => "the hold release without a hint to commit"); const changedAt = Date.now(); const window = await trickle(f, Math.ceil((ISSUE_RECOVERY_FULL_BACKSTOP_MS + 2 * MINUTE) / MINUTE)); const checks = window.raw.filter(event => event.name === "check" && event.fields.issueId === waiting.id); expect(checks.length).toBeGreaterThan(0); expect(checks[0]!.at - changedAt).toBeGreaterThan(2 * ISSUE_RECOVERY_BACKSTOP_MS); expect(checks[0]!.at - changedAt).toBeLessThanOrEqual(ISSUE_RECOVERY_FULL_BACKSTOP_MS + 2 * MINUTE); - const runs = await state.db.select({ id: heartbeatRuns.id }).from(heartbeatRuns) - .where(and(eq(heartbeatRuns.companyId, f.companyId), sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${waiting.id}`)); - expect(runs.length).toBeGreaterThan(0); - }, 1_800_000); + expect(await wakesFor(f.companyId, waiting.id), "recovery did not ask for a wake of the waiting task").not.toHaveLength(0); + }, TEST_TIMEOUT_MS); it("picks up a finished run, a user message, a raised budget and a resumed agent within a minute", async () => { const f = await boot(); @@ -142,25 +163,25 @@ describeIssueRecovery("stranded-task checks at idle for a staging-shaped company const within = async (issueId: string, act: () => Promise) => { f.events.length = 0; const at = Date.now(); - await act(); + await bounded(act(), () => `the change to task ${issueId} to commit`); await advance(60_000); const checked = checkedAt(f.events, issueId); expect(checked, issueId).not.toBeNull(); expect(checked! - at).toBeLessThanOrEqual(60_000); }; - const [run] = await state.db.select({ id: heartbeatRuns.id }).from(heartbeatRuns) - .where(sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${target!}`).limit(1); + const [run] = await bounded(state.db.select({ id: heartbeatRuns.id }).from(heartbeatRuns) + .where(sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${target!}`).limit(1), () => "the finished run to be read"); await within(target!, () => state.db.transaction(tx => notifyNativeStatusReassessment(tx, { companyId: f.companyId, runId: run!.id }))); await advance(31_000); await within(messaged!, () => issueService(state.db).addComment(messaged!, "Please look again", { userId: "recovery-user" })); await advance(31_000); await within(target!, () => state.db.transaction(tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, trigger: "pause_lifted" }))); await advance(31_000); - const { held, waiting } = await heldTask(f); + const { held, waiting } = await bounded(heldTask(f), () => "the held agent and its waiting task to be seeded"); await advance(31_000); await within(waiting.id, async () => { await state.db.update(agents).set({ status: "idle", lifecycleHolds: [], updatedAt: new Date() }).where(eq(agents.id, held.id)); await state.db.transaction(tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, trigger: "pause_lifted" })); }); - }, 1_800_000); + }, TEST_TIMEOUT_MS); }); diff --git a/server/src/__tests__/issue-recovery.test-fixture.ts b/server/src/__tests__/issue-recovery.test-fixture.ts index cba1a18d357..3657f9232bb 100644 --- a/server/src/__tests__/issue-recovery.test-fixture.ts +++ b/server/src/__tests__/issue-recovery.test-fixture.ts @@ -32,6 +32,9 @@ export function issueRecoveryFixture(options: { meter?: boolean } = {}) { const tasks = new Map number | null; hasPending: () => Promise }>(); const errors: unknown[] = []; const passes = new Set>(); + // The queue each pending pass belongs to, so a bounded wait can say which + // queue it was still waiting for. + const passQueues = new Map, string>(); const extraStops: Array<() => Promise> = []; const extraDeadlines: Array<() => number | null> = []; beforeAll(async () => { @@ -78,8 +81,9 @@ export function issueRecoveryFixture(options: { meter?: boolean } = {}) { coordinator.register = (queue, task) => { tasks.set(queue, task); return register(queue, { ...task, run: signal => { - const work = task.run(signal); passes.add(work); - void work.then(() => passes.delete(work), () => passes.delete(work)); + const work = task.run(signal); passes.add(work); passQueues.set(work, queue); + const done = () => { passes.delete(work); passQueues.delete(work); }; + void work.then(done, done); return work; } }); }; @@ -271,5 +275,7 @@ export function issueRecoveryFixture(options: { meter?: boolean } = {}) { set draining(value: typeof draining) { draining = value; }, get errors() { return errors; }, get passes() { return passes; }, + /** The queues of the passes still pending, for a bounded wait's message. */ + pendingPassQueues: () => [...passes].map(pass => passQueues.get(pass) ?? "?"), }; } diff --git a/server/src/__tests__/issue-runs-read-cost.test.ts b/server/src/__tests__/issue-runs-read-cost.test.ts new file mode 100644 index 00000000000..20ffdca4669 --- /dev/null +++ b/server/src/__tests__/issue-runs-read-cost.test.ts @@ -0,0 +1,81 @@ +import { randomUUID } from "node:crypto"; +import { sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { activityLog, agents, applyPendingMigrations, companies, createDb, heartbeatRuns, issues } from "@paperclipai/db"; +import { activityService } from "../services/activity.js"; +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const external = resolveExternalTestDatabaseUrl("PAPERCLIP_ISSUE_RUNS_COST_TEST_DATABASE_URL"); +const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); +type Plan = { "Relation Name"?: string; "Actual Rows": number; "Actual Loops": number; + "Rows Removed by Filter"?: number; "Rows Removed by Index Recheck"?: number; Plans?: Plan[] }; + +// The task chat reads a task's two latest runs before its first frame (the +// chat bootstrap and `/issues/:id/runs?view=recent`). That read must cost the +// task's own runs, not every run the company ever had. +describe.skipIf(!support.supported)("issue runs read cost", () => { + let temporary: Awaited> | undefined; + let db: ReturnType; + let capture = false; + const queries: Array<{ query: string; parameters: unknown[] }> = []; + beforeAll(async () => { + if (external) await applyPendingMigrations(external); + else temporary = await startEmbeddedPostgresTestDatabase("issue-runs-cost-"); + db = createDb(external ?? temporary!.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); + db.$client.options.onnotice = () => {}; + db.$client.options.debug = (_connection, query, parameters) => { + if (capture && /from "heartbeat_runs"/.test(query)) queries.push({ query, parameters: [...parameters] }); + }; + }, 30_000); + afterEach(async () => { capture = false; queries.length = 0; await db.execute(sql`truncate companies cascade`); }); + afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); }); + + it("reads a task's latest runs without walking the company's run history", async () => { + const companyId = randomUUID(), agentId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Busy", issuePrefix: `BR${companyId.slice(0, 6)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Worker", role: "engineer", status: "active", + adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {} }); + const [task, other] = await db.insert(issues).values([ + { companyId, title: "Opened task", status: "in_progress" }, + { companyId, title: "Other task", status: "in_progress" }, + ]).returning(); + // 20,000 runs of other work, newer than the task's own runs. + await db.execute(sql`insert into heartbeat_runs (company_id, agent_id, issue_id, status, created_at) + select ${companyId}::uuid, ${agentId}::uuid, ${other!.id}::uuid, 'succeeded', + '2026-06-01T00:00:00Z'::timestamptz + n * interval '1 second' from generate_series(1, 20000) n`); + // The task's runs: two linked directly, one only through its activity. + const [direct1, direct2, viaActivity] = await db.insert(heartbeatRuns).values([ + { companyId, agentId, issueId: task!.id, status: "succeeded", createdAt: new Date("2026-01-01T00:00:01Z") }, + { companyId, agentId, issueId: task!.id, status: "succeeded", createdAt: new Date("2026-01-01T00:00:02Z") }, + { companyId, agentId, status: "succeeded", createdAt: new Date("2026-01-01T00:00:03Z") }, + ]).returning(); + await db.insert(activityLog).values({ companyId, actorType: "agent", actorId: agentId, action: "issue.updated", + entityType: "issue", entityId: task!.id, runId: viaActivity!.id }); + await db.execute(sql`analyze heartbeat_runs`); + await db.execute(sql`analyze activity_log`); + + capture = true; + const recent = await activityService(db).runsForIssue(companyId, task!.id, null, 2, undefined, { skipLivenessBackfill: true }); + const all = await activityService(db).runsForIssue(companyId, task!.id, null, undefined, undefined, { skipLivenessBackfill: true }); + capture = false; + + expect(recent.map(run => run.runId)).toEqual([viaActivity!.id, direct2!.id]); + expect(all.map(run => run.runId)).toEqual([viaActivity!.id, direct2!.id, direct1!.id]); + + expect(queries.length).toBeGreaterThan(0); + let runRowsExamined = 0; + for (const statement of queries) { + const result = await db.$client.unsafe("EXPLAIN (ANALYZE, FORMAT JSON) " + statement.query, statement.parameters as never[]); + const visit = (node: Plan) => { + if (node["Relation Name"] === "heartbeat_runs") runRowsExamined += node["Actual Loops"] + * (node["Actual Rows"] + (node["Rows Removed by Filter"] ?? 0) + (node["Rows Removed by Index Recheck"] ?? 0)); + node.Plans?.forEach(visit); + }; + visit((result[0]!["QUERY PLAN"] as Array<{ Plan: Plan }>)[0]!.Plan); + } + process.stdout.write(JSON.stringify({ issueRunsReadCost: { companyRuns: 20003, runRowsExamined, queryCount: queries.length } }) + "\n"); + // Two reads of a three-run task. The other task's 20,000 runs must not be scanned. + expect(runRowsExamined).toBeLessThanOrEqual(100); + }, 120_000); +}); diff --git a/server/src/__tests__/link-preview-routes.test.ts b/server/src/__tests__/link-preview-routes.test.ts index a5026be77d8..41dc53a85a9 100644 --- a/server/src/__tests__/link-preview-routes.test.ts +++ b/server/src/__tests__/link-preview-routes.test.ts @@ -4,21 +4,44 @@ import { describe, expect, it, vi } from "vitest"; import type { Db } from "@paperclipai/db"; import { linkPreviewRoutes } from "../routes/link-previews.js"; import { HttpError } from "../errors.js"; +import { createInviteRateLimiter, type InviteRateLimiter } from "../services/invite-rate-limit.js"; -function app(actor: express.Request["actor"]) { +function app(actor: express.Request["actor"], limiter?: InviteRateLimiter) { const get = vi.fn(async () => ({ preview: null, maxAgeMs: 60_000 })); + const cached = vi.fn(async () => ({ results: {} })); const server = express(); + server.use(express.json()); server.use((req, _res, next) => { req.actor = actor; next(); }); - server.use(linkPreviewRoutes(null as unknown as Db, { get })); + server.use(linkPreviewRoutes(null as unknown as Db, { get, cached }, limiter)); server.use((error: HttpError, _req: express.Request, res: express.Response, _next: express.NextFunction) => { res.status(error.status ?? 500).json({ error: error.message }); }); - return { server, get }; + return { server, get, cached }; } const board = { type: "board", source: "session", userId: "alice", companyIds: ["company-a"] } as const; const path = "/companies/company-a/link-preview"; describe("link preview routes", () => { + it("limits lookups per viewer and company without blocking cached reads", async () => { + let now = 0; + const limiter = createInviteRateLimiter({ maxRequests: 2, windowMs: 1_000, now: () => now }); + const actor = { ...board, userId: "alice", companyIds: ["company-a", "company-b"] }; + const { server, get, cached } = app(actor, limiter); + const query = { url: "https://github.com/acme/web/pull/42" }; + for (let n = 0; n < 2; n++) expect((await request(server).get(path).query(query)).status).toBe(200); + const limited = await request(server).get(path).query(query); + expect(limited.status).toBe(429); + expect(limited.headers["retry-after"]).toBe("1"); + expect(get).toHaveBeenCalledTimes(2); + expect((await request(server).get("/companies/company-a/link-previews/cached").query(query)).status).toBe(200); + expect(cached).toHaveBeenCalledTimes(1); + expect((await request(server).get("/companies/company-b/link-preview").query(query)).status).toBe(200); + actor.userId = "bob"; + expect((await request(server).get(path).query(query)).status).toBe(200); + actor.userId = "alice"; + now = 1_001; + expect((await request(server).get(path).query(query)).status).toBe(200); + }); it("passes the authenticated viewer and disables shared HTTP caching", async () => { const { server, get } = app({ ...board, companyIds: [...board.companyIds] }); const response = await request(server).get(path).query({ url: "https://github.com/acme/web/pull/42" }); @@ -38,6 +61,25 @@ describe("link preview routes", () => { expect(get).not.toHaveBeenCalled(); } }); + it("reads a bounded batch only after viewer and company authorization", async () => { + const { server, cached, get } = app({ ...board, companyIds: [...board.companyIds] }); + const response = await request(server).get("/companies/company-a/link-previews/cached").query({ url: ["https://github.com/acme/web/pull/42"] }); + expect(response.status).toBe(200); + expect(response.headers["cache-control"]).toBe("private, no-store"); + expect(cached).toHaveBeenCalledWith({ companyId: "company-a", userId: "alice" }, ["https://github.com/acme/web/pull/42"]); + expect(get).not.toHaveBeenCalled(); + for (const body of [{}, { url: ["x".repeat(2049)] }, { url: Array(51).fill("a") }]) { + expect((await request(server).get("/companies/company-a/link-previews/cached").query(body)).status).toBe(400); + } + const denied = app({ ...board, companyIds: ["company-b"] }); + expect((await request(denied.server).get("/companies/company-a/link-previews/cached")).status).toBe(403); + expect(denied.cached).not.toHaveBeenCalled(); + }); + it("lets active viewer-role members read stored statuses", async () => { + const { server, cached } = app({ ...board, companyIds: [...board.companyIds], memberships: [{ companyId: "company-a", membershipRole: "viewer", status: "active" }] }); + expect((await request(server).get("/companies/company-a/link-previews/cached").query({ url: "https://github.com/acme/web/pull/42" })).status).toBe(200); + expect(cached).toHaveBeenCalledTimes(1); + }); it("bounds and validates the URL input", async () => { const { server, get } = app({ ...board, companyIds: [...board.companyIds] }); for (const query of [{}, { url: "x".repeat(2049) }, { url: ["a", "b"] }]) { diff --git a/server/src/__tests__/link-preview-store.integration.test.ts b/server/src/__tests__/link-preview-store.integration.test.ts new file mode 100644 index 00000000000..376ff11ac7a --- /dev/null +++ b/server/src/__tests__/link-preview-store.integration.test.ts @@ -0,0 +1,253 @@ +import { randomUUID } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { companies, linkPreviews } from "@paperclipai/db"; +import { recognizeLinkPreview } from "@paperclipai/shared"; +import { sql } from "drizzle-orm"; +import { expect, it, vi } from "vitest"; +import { describeEmbeddedPostgres, useEmbeddedPostgres } from "./helpers/route-test-harness.js"; +import { createLinkPreviewStore } from "../services/link-preview-store.js"; +import { createLinkPreviewService } from "../services/link-previews.js"; + +const url = "https://github.com/acme/web/pull/42"; +const target = recognizeLinkPreview(url)!; +const preview = { target, title: "Durable PR", state: "merged" as const, author: "alice", updatedAt: null }; + +describeEmbeddedPostgres("durable link preview cache", () => { + const context = useEmbeddedPostgres("link-previews-"); + async function fixture() { + const companyId = randomUUID(); + await context.db.insert(companies).values({ id: companyId, name: "Link cache", issuePrefix: companyId }); + return { companyId, userId: "alice" }; + } + it("bounds retained rows across concurrent store instances and isolates their quotas", async () => { + const scope = await fixture(); + const other = { ...scope, userId: "bob" }; + const now = Date.now(); + const seed = Array.from({ length: 1_000 }, (_, n) => ({ + companyId: scope.companyId, viewerId: scope.userId, channel: "github", resourceKind: "pull_request", + canonicalUrl: url + n, status: null, metadata: {}, checkedAt: new Date(now - 1_000 + n), expiresAt: new Date(now + 60_000), + })); + await context.db.insert(linkPreviews).values([...seed, { ...seed[0], viewerId: other.userId }]); + const first = createLinkPreviewStore(context.db); + const second = createLinkPreviewStore(context.db); + await Promise.all(Array.from({ length: 8 }, (_, n) => (n % 2 ? first : second).write(scope, + recognizeLinkPreview(url + (1_000 + n))!, { result: { preview: null, maxAgeMs: 60_000 }, expiresAt: now + 60_000 }, now + n))); + const rows = await context.db.select().from(linkPreviews).where(sql`${linkPreviews.companyId} = ${scope.companyId}`); + expect(rows.filter(row => row.viewerId === scope.userId)).toHaveLength(1_000); + expect(rows.filter(row => row.viewerId === other.userId)).toHaveLength(1); + const saved = await first.read(scope, [recognizeLinkPreview(url + "0")!, recognizeLinkPreview(url + "1007")!]); + expect(saved.has(url + "0")).toBe(false); + expect(saved.has(url + "1007")).toBe(true); + }); + it("removes long-expired rows on writes and preserves recent stale status", async () => { + const scope = await fixture(); + const now = Date.now(); + const expired = now - 31 * 24 * 60 * 60_000; + await context.db.insert(linkPreviews).values([ + { companyId: scope.companyId, viewerId: scope.userId, channel: "github", resourceKind: "pull_request", canonicalUrl: url, + status: "merged", metadata: { title: preview.title }, checkedAt: new Date(expired - 60_000), expiresAt: new Date(expired) }, + { companyId: scope.companyId, viewerId: scope.userId, channel: "github", resourceKind: "pull_request", canonicalUrl: url + "1", + status: "merged", metadata: { title: preview.title }, checkedAt: new Date(now - 120_000), expiresAt: new Date(now - 60_000) }, + ]); + const store = createLinkPreviewStore(context.db); + await store.write(scope, recognizeLinkPreview(url + "2")!, { result: { preview: null, maxAgeMs: 60_000 }, expiresAt: now + 60_000 }, now); + const saved = await store.read(scope, [target, recognizeLinkPreview(url + "1")!, recognizeLinkPreview(url + "2")!]); + expect(saved.has(url)).toBe(false); + expect(saved.get(url + "1")?.result.preview?.state).toBe("merged"); + expect(saved.has(url + "2")).toBe(true); + }); + it.each(["failure", "success", "timeout", "stale timeout"])("keeps another replica's concurrent hydration after provider %s", async (settlement) => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + let now = 1_000; + const oldPreview = { ...preview, state: "open" as const }; + await store.write(scope, target, { result: { preview: oldPreview, maxAgeMs: 1_000 }, expiresAt: 2_000 }, now); + let finish!: (value: { preview: typeof oldPreview | null; maxAgeMs: number }) => void; + let started!: () => void; + const providerStarted = new Promise(done => { started = done; }); + const resolve = vi.fn(() => new Promise<{ preview: typeof oldPreview | null; maxAgeMs: number }>(done => { finish = done; started(); })); + const write = vi.fn(store.write); + const first = createLinkPreviewService([{ key: "github", resolve }], { store: { ...store, write }, now: () => now, timeoutMs: 1_000 }); + await first.cached(scope, [url]); + now = 3_000; + const pending = first.get(scope, url); + await providerStarted; + now = 4_000; + const expiresAt = settlement === "stale timeout" ? 3_500 : 34_000; + await store.write(scope, target, { result: { preview, maxAgeMs: 30_000 }, expiresAt }, now); + expect((await first.cached(scope, [url])).results[url].preview).toEqual(preview); + if (!settlement.includes("timeout")) finish({ preview: settlement === "success" ? oldPreview : null, maxAgeMs: 60_000 }); + expect(await pending).toEqual({ preview, maxAgeMs: Math.max(0, expiresAt - now) }); + // A second batch checks that the process did not retain the older status. + expect((await first.cached(scope, [url])).results[url].preview).toEqual(preview); + const saved = (await store.read(scope, [target])).get(url)!; + expect(saved.result.preview).toEqual(preview); + expect(saved.checkedAt).toBe(4_000); + expect(saved.expiresAt).toBe(expiresAt); + expect(write).not.toHaveBeenCalled(); + finish({ preview: null, maxAgeMs: 60_000 }); + }); + it.each(["open", "negative"])("rechecks expired %s memory before calling the provider", async (initialState) => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + let now = 1_000; + const resolve = vi.fn(async () => ({ preview: initialState === "open" ? { ...preview, state: "open" as const } : null, maxAgeMs: 60_000 })); + const first = createLinkPreviewService([{ key: "github", resolve }], { store, now: () => now }); + await first.get(scope, url); + now = 62_000; + const other = createLinkPreviewService([{ key: "github", resolve: async () => ({ preview, maxAgeMs: 60_000 }) }], { store, now: () => now }); + await other.get(scope, url); + resolve.mockRejectedValue(new Error("provider unavailable")); + + expect((await first.get(scope, url)).preview).toEqual(preview); + expect(resolve).toHaveBeenCalledTimes(1); + const saved = (await store.read(scope, [target])).get(url)!; + expect(saved.result.preview).toEqual(preview); + expect(saved.expiresAt).toBe(122_000); + }); + it.each(["failure", "timeout"])("retains the newest stale stored preview on provider %s", async (failure) => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + let now = 1_000; + let requests = 0; + const resolve = async (_target: import("@paperclipai/shared").LinkPreviewTarget, _scope: import("../services/link-previews.js").LinkPreviewScope, signal: AbortSignal) => { + if (++requests === 1) return { preview: { ...preview, state: "open" as const }, maxAgeMs: 60_000 }; + if (failure === "failure") throw new Error("provider unavailable"); + return new Promise((_done, reject) => signal.addEventListener("abort", () => reject(new Error("timeout")))); + }; + const first = createLinkPreviewService([{ key: "github", resolve }], { store, now: () => now, timeoutMs: 100 }); + await first.get(scope, url); + now = 62_000; + await store.write(scope, target, { result: { preview, maxAgeMs: 1_000 }, expiresAt: 63_000 }, now); + now = 64_000; + expect((await first.get(scope, url)).preview).toEqual(preview); + await vi.waitFor(async () => expect((await store.read(scope, [target])).get(url)?.expiresAt).toBe(124_000)); + expect((await store.read(scope, [target])).get(url)?.result.preview).toEqual(preview); + }); + it("compares check times rather than cache lifetimes when hydrating", async () => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + let now = 1_000; + await store.write(scope, target, { result: { preview: { ...preview, state: "open" }, maxAgeMs: 60_000 }, expiresAt: 61_000 }, now); + const service = createLinkPreviewService([{ key: "github", resolve: async () => ({ preview: null, maxAgeMs: 60_000 }) }], { store, now: () => now }); + await service.cached(scope, [url]); + await store.write(scope, target, { result: { preview, maxAgeMs: 1_000 }, expiresAt: 4_000 }, 3_000); + now = 5_000; + expect((await service.cached(scope, [url])).results[url]).toEqual({ preview, maxAgeMs: 0 }); + }); + it("keeps a failed durable read's fallback local and accepts recovered stored status", async () => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + const read = vi.fn(store.read); + let now = 1_000; + const resolve = vi.fn(async () => ({ preview: { ...preview, state: "open" as const }, maxAgeMs: 60_000 })); + const first = createLinkPreviewService([{ key: "github", resolve }], { store: { ...store, read }, now: () => now }); + await first.get(scope, url); + now = 62_000; + await store.write(scope, target, { result: { preview, maxAgeMs: 60_000 }, expiresAt: 122_000 }, now); + now = 64_000; + read.mockRejectedValueOnce(new Error("temporary database outage")); + resolve.mockRejectedValueOnce(new Error("provider unavailable")); + expect((await first.get(scope, url)).preview?.state).toBe("open"); + const saved = (await store.read(scope, [target])).get(url)!; + expect(saved.result.preview).toEqual(preview); + expect(saved.expiresAt).toBe(122_000); + expect((await first.cached(scope, [url])).results[url].preview).toEqual(preview); + }); + it.each(["missing", "failed"])("reads another replica's saved status after a %s batch read", async (initialRead) => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + const read = vi.fn(store.read); + if (initialRead === "failed") read.mockRejectedValueOnce(new Error("temporary database outage")); + const write = vi.fn(store.write); + const resolve = vi.fn(async () => { throw new Error("provider unavailable"); }); + const first = createLinkPreviewService([{ key: "github", resolve }], { store: { read, write } }); + expect(await first.cached(scope, [url])).toEqual({ results: {} }); + + const other = createLinkPreviewService([{ key: "github", resolve: async () => ({ preview, maxAgeMs: 60_000 }) }], { store }); + await other.get(scope, url); + expect((await first.get(scope, url)).preview).toEqual(preview); + expect(read).toHaveBeenCalledTimes(2); + expect(resolve).not.toHaveBeenCalled(); + expect(write).not.toHaveBeenCalled(); + expect((await store.read(scope, [target])).get(url)?.result.preview).toEqual(preview); + }); + it("survives service recreation, reuses canonical URLs across tasks, and isolates viewers/companies", async () => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + const resolve = vi.fn(async () => ({ preview, maxAgeMs: 60_000 })); + const make = () => createLinkPreviewService([{ key: "github", resolve }], { store }); + await make().get(scope, url); + const restored = await make().cached(scope, [url, "https://www.github.com/ACME/WEB/pull/42/files#review"]); + expect(Object.keys(restored.results)).toEqual([url]); + expect(restored.results[url].preview).toMatchObject({ title: preview.title, state: "merged", target: { canonicalUrl: url } }); + expect(restored.results[url].maxAgeMs).toBeGreaterThan(0); + await make().get(scope, url); + expect(resolve).toHaveBeenCalledTimes(1); + expect(await make().cached({ ...scope, userId: "bob" }, [url])).toEqual({ results: {} }); + expect(await make().cached(await fixture(), [url])).toEqual({ results: {} }); + }); + it("returns stale status immediately, refreshes on demand, and persists negative freshness", async () => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + let now = 1_000; + const resolve = vi.fn(async () => ({ preview, maxAgeMs: 60_000 })); + const make = () => createLinkPreviewService([{ key: "github", resolve }], { store, now: () => now }); + await make().get(scope, url); + now += 61_000; + expect((await make().cached(scope, [url])).results[url]).toEqual({ preview, maxAgeMs: 0 }); + expect(resolve).toHaveBeenCalledTimes(1); + resolve.mockRejectedValueOnce(new Error("outage")); + expect((await make().get(scope, url)).preview).toEqual(preview); + await make().get(scope, url); + expect(resolve).toHaveBeenCalledTimes(2); + const missing = url + "1"; + resolve.mockRejectedValueOnce(new Error("private")); + await make().get(scope, missing); + await make().get(scope, missing); + expect(resolve).toHaveBeenCalledTimes(3); + expect((await make().cached(scope, [missing])).results[missing].preview).toBeNull(); + }); + it("persists provider timeout freshness across service restarts without extending the response", async () => { + const scope = await fixture(); + const database = createLinkPreviewStore(context.db); + let saved!: () => void; + const persisted = new Promise(done => { saved = done; }); + const store = { ...database, write: async (...args: Parameters) => { await database.write(...args); saved(); } }; + const resolve = vi.fn((_target: import("@paperclipai/shared").LinkPreviewTarget, _scope: import("../services/link-previews.js").LinkPreviewScope, signal: AbortSignal) => new Promise((_done, reject) => { + signal.addEventListener("abort", () => reject(new Error("timeout"))); + })); + const first = createLinkPreviewService([{ key: "github", resolve }], { store, timeoutMs: 100 }); + expect((await first.get(scope, url)).preview).toBeNull(); + await persisted; + const restarted = createLinkPreviewService([{ key: "github", resolve }], { store }); + expect((await restarted.get(scope, url)).preview).toBeNull(); + expect(resolve).toHaveBeenCalledTimes(1); + expect((await restarted.cached(scope, [url])).results[url].maxAgeMs).toBeGreaterThan(0); + }); + it("reads a 50-link page in one indexed select and does not require task relationships", async () => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + const targets = Array.from({ length: 50 }, (_, n) => recognizeLinkPreview(url + n)!); + await Promise.all(targets.map(t => store.write(scope, t, { result: { preview: { ...preview, target: t }, maxAgeMs: 60_000 }, expiresAt: 61_000 }, 1_000))); + const select = vi.spyOn(context.db, "select"); + expect((await store.read(scope, targets)).size).toBe(50); + expect(select).toHaveBeenCalledTimes(1); + select.mockRestore(); + const plan = await context.db.execute(sql`EXPLAIN SELECT * FROM link_previews WHERE company_id = ${scope.companyId} AND viewer_id = 'alice' AND canonical_url IN (${sql.join(targets.map(t => sql`${t.canonicalUrl}`), sql`, `)})`); + expect(JSON.stringify(plan)).toContain("link_previews_scope_url_uq"); + }); + it("supports other channels/statuses and older writers cannot replace newer results", async () => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + const deployment = { ...target, provider: "vercel", kind: "deployment", canonicalUrl: "https://vercel.com/acme/build/123" }; + await context.db.insert(linkPreviews).values({ companyId: scope.companyId, viewerId: scope.userId, channel: deployment.provider, + resourceKind: deployment.kind, canonicalUrl: deployment.canonicalUrl, status: "deployed", metadata: { deploymentId: "123", region: "iad1" }, checkedAt: new Date(), expiresAt: new Date() }); + await store.write(scope, target, { result: { preview, maxAgeMs: 60_000 }, expiresAt: 65_000 }, 5_000); + await store.write(scope, target, { result: { preview: { ...preview, state: "open" }, maxAgeMs: 60_000 }, expiresAt: 61_000 }, 1_000); + expect((await store.read(scope, [target])).get(url)?.result.preview?.state).toBe("merged"); + const migration = await readFile(new URL("../../../packages/db/src/migrations/0489_real_sage.sql", import.meta.url), "utf8"); + for (const statement of migration.split("--> statement-breakpoint")) if (statement.trim()) await context.db.execute(sql.raw(statement)); + expect((await store.read(scope, [target])).get(url)?.result.preview?.state).toBe("merged"); + }); +}); diff --git a/server/src/__tests__/link-previews.test.ts b/server/src/__tests__/link-previews.test.ts index 5ef63cd6aef..6e4bfccfcc2 100644 --- a/server/src/__tests__/link-previews.test.ts +++ b/server/src/__tests__/link-previews.test.ts @@ -2,6 +2,8 @@ import { createServer } from "node:http"; import { once } from "node:events"; import { afterEach, describe, expect, it, vi } from "vitest"; import { createLinkPreviewService, type LinkPreviewProvider } from "../services/link-previews.js"; +import type { StoredLinkPreview } from "../services/link-preview-store.js"; +import { recognizeLinkPreview } from "@paperclipai/shared"; const scope = { companyId: "company-a", userId: "alice" }; const url = "https://github.com/acme/web/pull/42"; @@ -10,6 +12,51 @@ const provider = (resolve = vi.fn(async () => unavailable)): LinkPreviewProvider afterEach(() => vi.useRealTimers()); describe("demand-driven link preview cache", () => { + it.each(["failure", "success", "timeout", "write"])("keeps concurrent hydration newer than a pending provider %s", async (settlement) => { + vi.useFakeTimers(); + let now = 1_000; + const target = recognizeLinkPreview(url)!; + const oldPreview = { target, title: "Old status", state: "open" as const, author: null, updatedAt: null }; + const newPreview = { ...oldPreview, title: "New status", state: "merged" as const }; + let stored: StoredLinkPreview = { result: { preview: oldPreview, maxAgeMs: 1_000 }, expiresAt: 2_000, checkedAt: now }; + let finish!: (value: typeof unavailable | { preview: typeof oldPreview; maxAgeMs: number }) => void; + let finishWrite!: () => void; + const write = vi.fn(async () => { + if (settlement === "write") await new Promise(done => { finishWrite = done; }); + }); + const resolve = vi.fn(() => new Promise(done => { finish = done; })); + const service = createLinkPreviewService([{ key: "github", resolve }], { + now: () => now, timeoutMs: 20, + store: { read: async () => new Map([[url, stored]]), write }, + }); + await service.cached(scope, [url]); + now = 3_000; + const pending = service.get(scope, url); + await vi.advanceTimersByTimeAsync(0); + if (settlement === "write") { + finish({ preview: oldPreview, maxAgeMs: 60_000 }); + await vi.advanceTimersByTimeAsync(0); + expect(write).toHaveBeenCalledTimes(1); + } + now = 4_000; + stored = { result: { preview: newPreview, maxAgeMs: 30_000 }, expiresAt: 34_000, checkedAt: now }; + expect((await service.cached(scope, [url])).results[url].preview).toEqual(newPreview); + if (settlement === "write") finishWrite(); + else if (settlement === "timeout") await vi.advanceTimersByTimeAsync(21); + else finish(settlement === "failure" ? unavailable : { preview: oldPreview, maxAgeMs: 60_000 }); + expect(await pending).toEqual({ preview: newPreview, maxAgeMs: 30_000 }); + expect(await service.get(scope, url)).toEqual({ preview: newPreview, maxAgeMs: 30_000 }); + expect(resolve).toHaveBeenCalledTimes(1); + expect(write).toHaveBeenCalledTimes(settlement === "write" ? 1 : 0); + if (settlement === "timeout") { finish(unavailable); await vi.advanceTimersByTimeAsync(0); } + }); + it("omits absent records on repeated batch reads", async () => { + const service = createLinkPreviewService([provider()], { + store: { read: async () => new Map(), write: async () => {} }, + }); + expect(await service.cached(scope, [url])).toEqual({ results: {} }); + expect(await service.cached(scope, [url])).toEqual({ results: {} }); + }); it("does no work until requested and coalesces equivalent URLs", async () => { const resolve = vi.fn(async () => unavailable); const service = createLinkPreviewService([provider(resolve)]); @@ -86,6 +133,36 @@ describe("demand-driven link preview cache", () => { expect(resolve).toHaveBeenCalledTimes(2); finish(unavailable); }); + it("bounds a stalled database write and holds its concurrency slot until settlement", async () => { + vi.useFakeTimers(); + let finish!: () => void; + const write = vi.fn(async () => {}).mockImplementationOnce(() => new Promise(done => { finish = done; })); + const resolve = vi.fn(async (target: import("@paperclipai/shared").LinkPreviewTarget) => ({ preview: { target, title: "Known", state: "open" as const, author: null, updatedAt: null }, maxAgeMs: 60_000 })); + const service = createLinkPreviewService([{ key: "github", resolve }], { + store: { read: async () => new Map(), write }, timeoutMs: 20, maxConcurrent: 1, + }); + const first = service.get(scope, url); + await vi.advanceTimersByTimeAsync(21); + expect((await first).preview?.state).toBe("open"); + expect(await service.get(scope, url + "1")).toEqual(unavailable); + expect(resolve).toHaveBeenCalledTimes(1); + finish(); await vi.advanceTimersByTimeAsync(1); + await service.get(scope, url + "1"); + expect(resolve).toHaveBeenCalledTimes(2); + }); + it("keeps timeout persistence inside the concurrency budget after the provider aborts", async () => { + vi.useFakeTimers(); + let finishWrite!: () => void; + const write = vi.fn(async () => {}).mockImplementationOnce(() => new Promise(done => { finishWrite = done; })); + const resolve = vi.fn(async (_target: import("@paperclipai/shared").LinkPreviewTarget, _scope: import("../services/link-previews.js").LinkPreviewScope, signal: AbortSignal) => unavailable) + .mockImplementationOnce((_target, _scope, signal) => new Promise((_done, reject) => signal.addEventListener("abort", () => reject(new Error("timeout"))))); + const service = createLinkPreviewService([{ key: "github", resolve }], { store: { read: async () => new Map(), write }, timeoutMs: 20, maxConcurrent: 1 }); + const first = service.get(scope, url); + await vi.advanceTimersByTimeAsync(21); expect(await first).toEqual(unavailable); + await service.get(scope, url + "1"); expect(resolve).toHaveBeenCalledTimes(1); + finishWrite(); await vi.advanceTimersByTimeAsync(1); + await service.get(scope, url + "1"); expect(resolve).toHaveBeenCalledTimes(2); + }); it("aborts a real stalled HTTP read while an unrelated lookup remains responsive", async () => { const server = createServer((_req, res) => { res.writeHead(200, { "content-type": "application/json" }); res.write("{"); }); server.listen(0, "127.0.0.1"); diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts index 399b53fc554..3a8e0157049 100644 --- a/server/src/__tests__/openapi-routes.test.ts +++ b/server/src/__tests__/openapi-routes.test.ts @@ -4,7 +4,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import request from "supertest"; import { describe, expect, it } from "vitest"; -import { MUSE_ASSET_VERSION, MUSE_PUBLIC_ROUTES } from "@paperclipai/shared"; +import { LINK_PREVIEW_BATCH_LIMIT, MUSE_ASSET_VERSION, MUSE_PUBLIC_ROUTES } from "@paperclipai/shared"; import { COMPANY_IMPORT_TRANSFERS_ROUTE_PATH } from "@paperclipai/shared/company-import-transfer"; import { errorHandler } from "../middleware/index.js"; import { buildOpenApiSpec, openApiRoutes, applyPluginSettingsVisibility, buildOpenApiDocument } from "../routes/openapi.js"; @@ -338,6 +338,15 @@ function loadSpecRoutes() { } describe("openapi routes", () => { + it("describes cached link results with the lookup shape and shared batch bound", () => { + const paths = buildOpenApiSpec().paths; + const batch = paths["/api/companies/{companyId}/link-previews/cached"].get; + expect(batch.description).toContain(`at most ${LINK_PREVIEW_BATCH_LIMIT} URLs`); + const lookupResult = paths["/api/companies/{companyId}/link-preview"].get.responses[200].content["application/json"].schema; + expect(batch.responses[200].content["application/json"].schema.properties.results.additionalProperties).toEqual(lookupResult); + expect(lookupResult.properties).toHaveProperty("preview"); + expect(lookupResult.properties).toHaveProperty("maxAgeMs"); + }); it("tells agents that unpriced usage in cost reports is unknown cost, not zero", () => { const paths = buildOpenApiSpec().paths; for (const segment of ["summary", "by-agent", "by-agent-model", "by-project"]) { diff --git a/server/src/__tests__/task-interruption-query.test.ts b/server/src/__tests__/task-interruption-query.test.ts index cf28f663f43..843b78e92a1 100644 --- a/server/src/__tests__/task-interruption-query.test.ts +++ b/server/src/__tests__/task-interruption-query.test.ts @@ -375,12 +375,12 @@ describe.skipIf(!support.supported)("task interruption latest run query", () => ? { state: "resolved", canRetry: false } : { state: "failed", canRetry: true }); const query = await captureInterruptionQuery(db, taskInterruptionPresentations, companyId, [issue]); const [projected] = await db.$client.unsafe(query.sql, query.params as never[]); - expect(projected.jsonb_build_object.nativeCancellation).toEqual({ ...nativeCancellation, + expect(projected.result_json.nativeCancellation).toEqual({ ...nativeCancellation, intentAuditId: variant === "numeric_audit" ? null : nativeCancellation.intentAuditId }); - expect(projected.jsonb_build_object.cancelledByUserId).toBe(variant === "numeric_user" ? null : "board"); + expect(projected.result_json.cancelledByUserId).toBe(variant === "numeric_user" ? null : "board"); expect(projected).toMatchObject({ company_id: companyId, native_issue_id: issue.id, runtime_mode: "native" }); - expect(projected.jsonb_build_object).not.toHaveProperty("unrelatedPayload"); - expect(JSON.stringify(projected.jsonb_build_object).length).toBeLessThan(4000); + expect(projected.result_json).not.toHaveProperty("unrelatedPayload"); + expect(JSON.stringify(projected.result_json).length).toBeLessThan(4000); }); it("redacts registered run secrets from both task detail and list provider explanations", async () => { diff --git a/server/src/routes/link-previews.ts b/server/src/routes/link-previews.ts index bd631855b2f..5236a55f516 100644 --- a/server/src/routes/link-previews.ts +++ b/server/src/routes/link-previews.ts @@ -1,11 +1,15 @@ import { Router } from "express"; import type { Db } from "@paperclipai/db"; -import { badRequest } from "../errors.js"; +import { LINK_PREVIEW_BATCH_LIMIT } from "@paperclipai/shared"; +import { createLinkPreviewStore } from "../services/link-preview-store.js"; +import { badRequest, tooManyRequests } from "../errors.js"; +import { createInviteRateLimiter, type InviteRateLimiter } from "../services/invite-rate-limit.js"; import { assertBoard, assertCompanyAccess } from "./authz.js"; import { createLinkPreviewService } from "../services/link-previews.js"; import { createGitHubLinkPreviewProvider } from "../services/github-link-preview.js"; -export function linkPreviewRoutes(db: Db, service = createLinkPreviewService([createGitHubLinkPreviewProvider(db)])) { +export function linkPreviewRoutes(db: Db, service = createLinkPreviewService([createGitHubLinkPreviewProvider(db)], { store: createLinkPreviewStore(db) }), + limiter: InviteRateLimiter = createInviteRateLimiter({ maxRequests: 600 })) { const router = Router(); router.get("/companies/:companyId/link-preview", async (req, res) => { const companyId = req.params.companyId as string; @@ -15,7 +19,25 @@ export function linkPreviewRoutes(db: Db, service = createLinkPreviewService([cr if (typeof href !== "string" || href.length > 2048) throw badRequest("A link URL is required"); // Personal repository metadata must never be stored by a proxy or shared browser cache. res.set("Cache-Control", "private, no-store"); + const limit = limiter.consume(JSON.stringify([companyId, req.actor.userId ?? null])); + res.set("X-RateLimit-Limit", String(limit.limit)); + res.set("X-RateLimit-Remaining", String(limit.remaining)); + if (!limit.allowed) { + res.set("Retry-After", String(limit.retryAfterSeconds)); + throw tooManyRequests("Link preview rate limit exceeded"); + } res.json(await service.get({ companyId, userId: req.actor.userId ?? null }, href)); }); + // Read-only batch: page hydration never waits for a remote provider. + router.get("/companies/:companyId/link-previews/cached", async (req, res) => { + const companyId = req.params.companyId as string; + assertCompanyAccess(req, companyId); + assertBoard(req); + const urls = typeof req.query.url === "string" ? [req.query.url] : req.query.url; + if (!Array.isArray(urls) || !urls.length || urls.length > LINK_PREVIEW_BATCH_LIMIT + || urls.some(url => typeof url !== "string" || url.length > 2048)) throw badRequest("A bounded list of link URLs is required"); + res.set("Cache-Control", "private, no-store"); + res.json(await service.cached({ companyId, userId: req.actor.userId ?? null }, urls as string[])); + }); return router; } diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 8762d89f512..101c9bf9d38 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -2,7 +2,7 @@ import { catalogTeamInstallSchema, catalogTeamPreviewSchema, updateWorkspacePref import { MUSE_ASSET_VERSION, museStopBoundarySchema, museDetectorCleanupAttestationSchema, createGrokInvitationSchema, configureGrokRoutineSchema, verifyGrokRoutineSchema, recoverGrokRoutineSchema, pairGrokBindingSchema, stopGrokWorkSchema, retryGrokDeliverySchema, updateFastResponseSchema } from "@paperclipai/shared"; import { slackTestMessageSchema, slackTestMessageResultSchema, slackManagerAuthorizationSchema, slackSetupOptionsSchema, slackManagedProvisionSchema, slackManagedResultSchema, slackRegistrationSchema, slackSetupActionSchema, slackInstallAuthorizationSchema, slackRegistrationStateSchema, slackAppConfigurationSchema, slackAvatarStateSchema, slackAccountStateSchema } from "@paperclipai/shared"; import { experimentalApiMetadata } from "./experimental-api-metadata.js"; -import { ATTENTION_SOURCE_KINDS } from "@paperclipai/shared"; +import { LINK_PREVIEW_BATCH_LIMIT, ATTENTION_SOURCE_KINDS } from "@paperclipai/shared"; import { agentCaseHandoffSchema, caseWorkflowDocumentTextSchema, doneCaseHandoffSchema, createWorkflowSchema, updateWorkflowSchema, listWorkflowsSchema, readWorkflowQuerySchema } from "@paperclipai/shared"; import { experimentalApiDocs, @@ -10459,26 +10459,41 @@ registry.registerPath({ responses: { 200: r.ok(), 401: r.unauthorized, 404: r.notFound }, }); +const linkPreviewResultSchema = z.object({ + preview: z.object({ + target: z.object({ provider: z.string(), kind: z.string(), canonicalUrl: z.string(), label: z.string() }), + title: z.string(), state: z.enum(["unknown", "open", "draft", "merged", "closed", "conflicts"]), + author: z.string().nullable(), updatedAt: z.string().nullable(), + }).nullable(), + maxAgeMs: z.number(), +}); + registry.registerPath({ method: "get", path: "/api/companies/{companyId}/link-preview", tags: ["companies"], summary: "Read optional link metadata for the current board user", - description: "Company access and board authentication are required. This read uses a viewer-scoped cache and returns a quiet null preview when provider access is unavailable. It does not change tasks or schedule background work.", + description: "Company access and board authentication are required. This read uses a viewer-scoped cache and returns a quiet null preview when provider access is unavailable. Each company/viewer can make 600 lookup requests per minute per server process. Excess requests return 429 with Retry-After; cached batch reads remain available. It does not change tasks or schedule background work.", request: { params: z.object({ companyId: z.string() }), query: z.object({ url: z.string().max(2048) }) }, responses: { - 200: r.ok(z.object({ - preview: z.object({ - target: z.object({ provider: z.string(), kind: z.string(), canonicalUrl: z.string(), label: z.string() }), - title: z.string(), state: z.enum(["unknown", "open", "draft", "merged", "closed", "conflicts"]), - author: z.string().nullable(), updatedAt: z.string().nullable(), - }).nullable(), - maxAgeMs: z.number(), - })), - 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, + 200: r.ok(linkPreviewResultSchema), + 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 429: r.tooManyRequests, }, }); +registry.registerPath({ + method: "get", + path: "/api/companies/{companyId}/link-previews/cached", + tags: ["companies"], + summary: "Read a batch of stored link statuses without contacting providers", + description: `Board-only and company/viewer scoped. Reads at most ${LINK_PREVIEW_BATCH_LIMIT} URLs. Canonical links are reused across tasks. Stale records have maxAgeMs zero; absent records are omitted. This is a read-only cache projection.`, + request: { + params: z.object({ companyId: z.string() }), + query: z.object({ url: z.union([z.string().max(2048), z.array(z.string().max(2048)).min(1).max(LINK_PREVIEW_BATCH_LIMIT)]) }), + }, + responses: { 200: r.ok(z.object({ results: z.record(z.string(), linkPreviewResultSchema) })), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden }, +}); + registry.registerPath({ method: "get", path: "/api/issues/{id}/external-objects", diff --git a/server/src/services/activity.ts b/server/src/services/activity.ts index 4fa79b84104..be5a8a7da75 100644 --- a/server/src/services/activity.ts +++ b/server/src/services/activity.ts @@ -575,17 +575,19 @@ export function activityService(db: Db) { or coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.issueId}::text, ${heartbeatRuns.contextSnapshot} ->> 'issueId', ${heartbeatRuns.contextSnapshot} ->> 'taskId') = ${issueId})`, ...(selectedRunIds ? [inArray(heartbeatRuns.id, selectedRunIds)] : []), - or( - eq(heartbeatRuns.issueId, issueId), - sql`exists ( - select 1 - from ${activityLog} - where ${activityLog.companyId} = ${companyId} - and ${activityLog.entityType} = 'issue' - and ${activityLog.entityId} = ${issueId} - and ${activityLog.runId} = ${heartbeatRuns.id} - )`, - ), + // The task's runs: linked directly, or through the task's activity. + // Collect the candidate ids first, each half by its own index. An + // OR with a per-run EXISTS walks every run of the company instead. + sql`${heartbeatRuns.id} in ( + select hr.id from ${heartbeatRuns} hr + where hr.company_id = ${companyId} and hr.issue_id = ${issueId} + union + select al.run_id from ${activityLog} al + where al.company_id = ${companyId} + and al.entity_type = 'issue' + and al.entity_id = ${issueId} + and al.run_id is not null + )`, ), ) .orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)); diff --git a/server/src/services/execution-projection.test.ts b/server/src/services/execution-projection.test.ts index 5b144c51fcf..32cba2bc59b 100644 --- a/server/src/services/execution-projection.test.ts +++ b/server/src/services/execution-projection.test.ts @@ -39,6 +39,27 @@ const project = ( ) => projectExecution(r, c, pending, undefined, now); describe("execution truth projection", () => { + it.each(["requested", "acknowledged"])("shows a %s operator Stop without calling it a failed attempt", state => { + const stopped = run({ status: "cancelled", runtimeMode: "legacy", finishedAt: now, errorCode: "cancelled", + resultJson: { cancellation: { source: "operator", expected: true, initiator: { type: "user", id: "board" }, + reason: "Cancelled by a board operator", recordedAt: now.toISOString() }, executionCancellation: { state, proof: "preparation_settled" } } }); + if (state === "acknowledged") { + expect(project(stopped, undefined)).toMatchObject({ phase: "completed", label: "Stopped", cause: null, + nextAction: "Send a new message to continue from saved work." }); + } else { + expect(project(stopped, undefined).phase).not.toBe("completed"); + } + // Unrelated provider failures and recovery holds remain visible. + expect(project(run({ ...stopped, resultJson: {} }), undefined).phase).toBe("failed"); + expect(projectExecution(stopped, undefined, [], { cause: "workspace_restore_failed", nextAction: "Save files" }, now).phase) + .toBe("recovery_needed"); + }); + it.each([undefined, "unknown", "provider_api_stop_receipt"])("retains failure presentation for an unqualified legacy Stop proof: %s", proof => { + const stopped = run({ status: "cancelled", runtimeMode: "legacy", finishedAt: now, + resultJson: { cancellation: { source: "operator", expected: true, initiator: { type: "user" }, + reason: "Stop", recordedAt: now.toISOString() }, executionCancellation: { state: "acknowledged", proof } } }); + expect(project(stopped, undefined).phase).toBe("failed"); + }); it.each(["contained", "ordinary", "wrong-source", "continued"] as const)("projects controller containment without inventing queued work: %s", state => { const stopped = run({ id: "old", status: "failed" }); const action = { status: "resolved" as const, cause: "native_restart_recovery_blocked", nextAction: "Inspect the original owner", diff --git a/server/src/services/execution-projection.ts b/server/src/services/execution-projection.ts index 0954d4dcf44..3b990bbf3c4 100644 --- a/server/src/services/execution-projection.ts +++ b/server/src/services/execution-projection.ts @@ -23,6 +23,7 @@ import { hasPendingRunCleanup } from "./execution-blocker.js"; import { isAgentAwaitingSetup } from "../modules/agent-lifecycle/index.js"; import { NATIVE_RESPONSE_WAKE_WAITING_REASON } from "./native-runtime/status-arbiter.js"; import { agentQueueLinesForRuns } from "./heartbeat/queued-run-line.js"; +import { isAcknowledgedLegacyUserStop, runStopPresentationJson } from "./run-cancellation.js"; const MAX_PREDECESSOR_CLEANUP_CHECKS = 16; const ANOTHER_ROUTINE_TASK = "another task in this routine"; const text = (v: unknown) => (typeof v === "string" ? v : null); @@ -51,7 +52,7 @@ const executionRunColumns = { 'failureRetriesBeforeAiConnectionWait', ${heartbeatRuns.contextSnapshot}->'failureRetriesBeforeAiConnectionWait', 'failureRetriesBeforeWorkspaceWait', ${heartbeatRuns.contextSnapshot}->'failureRetriesBeforeWorkspaceWait', 'executionRetryAccounting', ${heartbeatRuns.contextSnapshot}->'executionRetryAccounting')`, - resultJson: sql>`jsonb_build_object( + resultJson: sql>`${runStopPresentationJson(heartbeatRuns.resultJson)} || jsonb_build_object( 'finalizationPhase', ${heartbeatRuns.resultJson}->'finalizationPhase', 'finalizationReasonCode', ${heartbeatRuns.resultJson}->'finalizationReasonCode')`, }; @@ -538,6 +539,11 @@ export function projectExecution( } return set("completed", "Completed"); } + if (isAcknowledgedLegacyUserStop(run)) { + projection.cause = null; + projection.nextAction = "Send a new message to continue from saved work."; + return set("completed", "Stopped"); + } if (["failed", "cancelled", "timed_out", "interrupted"].includes(run.status)) return set("failed", run.status === "cancelled" ? "Cancelled" : "Failed"); if (run.status === "running") { diff --git a/server/src/services/fresh-continuation-fallback.test.ts b/server/src/services/fresh-continuation-fallback.test.ts index 33a1dab5320..6deeed02562 100644 --- a/server/src/services/fresh-continuation-fallback.test.ts +++ b/server/src/services/fresh-continuation-fallback.test.ts @@ -3,7 +3,7 @@ import { and, eq, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { activityLog, agentWakeupRequests, agents, approvals, authUsers, companies, createDb, environmentLeases, environments, executionWorkspaces, heartbeatRuns, issueApprovals, issueRecoveryActions, issueThreadInteractions, - heartbeatRunEvents, issueComments, issues, nativeRunFinalizations, toolInvocations, + heartbeatRunEvents, issueComments, issues, nativeRunFinalizations, toolInvocations, companyMemberships, } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; import { deliverReconciledExecutions, settleUnrecoverableExecutions } from "./execution-recovery-resolution.js"; @@ -65,6 +65,8 @@ suite("fresh-continuation fallback", () => { afterEach(async () => { resetBacklogContinuationPacingForTests(db); await heartbeatService(db).drainActiveRunExecutions(); + await db.delete(companyMemberships).where(and(eq(companyMemberships.companyId, companyId), + eq(companyMemberships.principalId, userId), eq(companyMemberships.principalType, "user"))); // The drain covers every background run, wake and resume dispatch, so // nothing still holds these tables. A deadlock here is a leak to fix. await db.execute(sql`truncate table issue_recovery_actions, native_run_finalizations, tool_invocations, @@ -388,6 +390,8 @@ suite("fresh-continuation fallback", () => { }, 60_000); it("never folds a Retry for the admitted continuation's own failure into that ended continuation", async () => { + await db.insert(companyMemberships).values({ companyId, principalId: userId, principalType: "user", + status: "active", membershipRole: "member" }); const f = await unfinishedRun({ runtime: "legacy", errorCode: "controller_lease_lost", error: "Legacy controller lease lost" }); await db.update(heartbeatRuns).set({ processPid: 4242, processHostHash: "replaced-server", processStartedAt: new Date(Date.now() - 600_000) }) .where(eq(heartbeatRuns.id, f.runId)); diff --git a/server/src/services/heartbeat/run-control.ts b/server/src/services/heartbeat/run-control.ts index 3b26f4f01cc..3584d55ff43 100644 --- a/server/src/services/heartbeat/run-control.ts +++ b/server/src/services/heartbeat/run-control.ts @@ -1780,7 +1780,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont await appendRunEvent(cancelled, { eventType: "lifecycle", stream: "system", - level: "warn", + level: readRunCancellation(cancelled.resultJson)?.expected ? "info" : "warn", message: options.eventMessage ?? "run cancelled", payload: { ...options.eventPayload, cancellation: readRunCancellation(cancelled.resultJson) }, }).catch((eventErr) => { diff --git a/server/src/services/legacy-execution-recovery.ts b/server/src/services/legacy-execution-recovery.ts index 8026aed31fb..fb96f70a23b 100644 --- a/server/src/services/legacy-execution-recovery.ts +++ b/server/src/services/legacy-execution-recovery.ts @@ -481,8 +481,11 @@ export async function settleCancelledLegacyPreparation( return db.transaction(async tx => { const [task] = await tx.select().from(issues) .where(and(eq(issues.id, issueId), eq(issues.companyId, input.run.companyId))).for("update"); + // The dispatch gate writes this marker under the same run lock before + // calling the adapter. A prior owner's local flag cannot disprove handoff. const [run] = await tx.select().from(heartbeatRuns) - .where(and(eq(heartbeatRuns.id, input.run.id), eq(heartbeatRuns.companyId, input.run.companyId))).for("update"); + .where(and(eq(heartbeatRuns.id, input.run.id), eq(heartbeatRuns.companyId, input.run.companyId), + sql`${heartbeatRuns.usageJson}#>'{budgetDispatch,handedOffAt}' is null`)).for("update"); const recovery = run?.resultJson?.executionRecovery as Record | undefined; // Only a requested Stop qualifies, and only while it is still classified as // an unknown outcome: existing wait or bootstrap receipts already decide it. @@ -504,8 +507,16 @@ export async function settleCancelledLegacyPreparation( ? !lease.releasedAt || lease.status === "pending_cleanup" || lease.cleanupStatus === "failed" : !hasRemoteTerminationReceipt(lease))) return null; const now = new Date(); + const cancellation = readRunCancellation(run.resultJson); + const operatorStop = cancellation?.source === "operator" && cancellation.initiator.type === "user"; const [settled] = await tx.update(heartbeatRuns).set({ resultJson: { ...run.resultJson, executionRecovery: { kind: "bootstrap", providerWorkStarted: false, preparationSettledAt: now.toISOString() }, + // The preparation owner has unwound and every execution reference agrees. + // Confirm the user's Stop; system cancellations keep their delivery path. + ...(operatorStop ? { executionCancellation: { + ...(run.resultJson?.executionCancellation as Record | undefined), + state: "acknowledged", proof: "preparation_settled", acknowledgedAt: now.toISOString(), + } } : {}), }, updatedAt: now }).where(eq(heartbeatRuns.id, run.id)).returning(); // The automatic disposition may already have closed the incident with // replay blocked, and moved the task to blocked. Correct both verdicts. @@ -531,9 +542,12 @@ export async function settleCancelledLegacyPreparation( const resolved = holds.length ? await tx.update(issueRecoveryActions).set({ status: "resolved", outcome: "false_positive", resolutionNote: "The run was stopped before its adapter started; there are no provider actions to reconcile.", resolvedAt: now, updatedAt: now, - evidence: sql`case when ${issueRecoveryActions.evidence} ? 'automaticRecovery' - then jsonb_set(${issueRecoveryActions.evidence}, '{automaticRecovery,replay}', '"allowed"'::jsonb, false) - else ${issueRecoveryActions.evidence} end`, + // A verified operator Stop no longer needs a recovery notice. System + // cancellations still use this metadata to deliver pending saved input. + evidence: operatorStop ? sql`${issueRecoveryActions.evidence} - 'automaticRecovery'` + : sql`case when ${issueRecoveryActions.evidence} ? 'automaticRecovery' + then jsonb_set(${issueRecoveryActions.evidence}, '{automaticRecovery,replay}', '"allowed"'::jsonb, false) + else ${issueRecoveryActions.evidence} end`, }).where(inArray(issueRecoveryActions.id, holds.map(hold => hold.id))).returning({ id: issueRecoveryActions.id }) : []; if (resolved.length) { await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: run.companyId, issueId: task.id }); diff --git a/server/src/services/link-preview-store.ts b/server/src/services/link-preview-store.ts new file mode 100644 index 00000000000..3bbe508f7f0 --- /dev/null +++ b/server/src/services/link-preview-store.ts @@ -0,0 +1,65 @@ +import { and, desc, eq, inArray, lt, lte, or, sql } from "drizzle-orm"; +import { linkPreviews, type Db } from "@paperclipai/db"; +import type { LinkPreviewResult, LinkPreviewTarget } from "@paperclipai/shared"; +import type { LinkPreviewScope } from "./link-previews.js"; + +export interface StoredLinkPreview { result: LinkPreviewResult; expiresAt: number; checkedAt: number } +export interface LinkPreviewStore { + read(scope: LinkPreviewScope, targets: readonly LinkPreviewTarget[]): Promise>; + write(scope: LinkPreviewScope, target: LinkPreviewTarget, entry: Omit, checkedAt: number): Promise; +} + +const MAX_ROWS_PER_VIEWER = 1_000; +const EXPIRED_RETENTION_MS = 30 * 24 * 60 * 60_000; + +export function createLinkPreviewStore(db: Db): LinkPreviewStore { + return { + async read(scope, targets) { + if (!targets.length) return new Map(); + // One covering identity-index lookup for the page, never a task join or a provider call. + const rows = await db.select().from(linkPreviews).where(and( + eq(linkPreviews.companyId, scope.companyId), eq(linkPreviews.viewerId, scope.userId ?? ""), + inArray(linkPreviews.canonicalUrl, targets.map(target => target.canonicalUrl)), + )); + const byUrl = new Map(targets.map(target => [target.canonicalUrl, target])); + return new Map(rows.flatMap(row => { + const target = byUrl.get(row.canonicalUrl); + if (!target || target.provider !== row.channel || target.kind !== row.resourceKind) return []; + const data = row.metadata; + const preview = row.status !== null && typeof data.title === "string" ? { + target, title: data.title, state: row.status as NonNullable["state"], + author: typeof data.author === "string" ? data.author : null, + updatedAt: typeof data.updatedAt === "string" ? data.updatedAt : null, + } : null; + return [[row.canonicalUrl, { result: { preview, maxAgeMs: 0 }, expiresAt: row.expiresAt.getTime(), checkedAt: row.checkedAt.getTime() }] as const]; + })); + }, + async write(scope, target, entry, checkedAt) { + const preview = entry.result.preview; + const values = { + companyId: scope.companyId, viewerId: scope.userId ?? "", channel: target.provider, + resourceKind: target.kind, canonicalUrl: target.canonicalUrl, status: preview?.state ?? null, + metadata: preview ? { title: preview.title, author: preview.author, updatedAt: preview.updatedAt } : {}, + checkedAt: new Date(checkedAt), expiresAt: new Date(entry.expiresAt), + }; + await db.transaction(async tx => { + // Serialize only this cache scope, including across server replicas. + // The row cap must hold when several distinct URLs are saved together. + const lockKey = JSON.stringify(["link-previews", values.companyId, values.viewerId]); + await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))`); + await tx.insert(linkPreviews).values(values).onConflictDoUpdate({ + target: [linkPreviews.companyId, linkPreviews.viewerId, linkPreviews.canonicalUrl], + set: values, setWhere: lte(linkPreviews.checkedAt, values.checkedAt), + }); + const scopeCondition = and(eq(linkPreviews.companyId, values.companyId), eq(linkPreviews.viewerId, values.viewerId)); + // Cleanup runs on writes, without a worker or extra page-read queries. + // The identity index covers this scope, whose retained size is bounded. + await tx.delete(linkPreviews).where(and(scopeCondition, or( + lt(linkPreviews.expiresAt, new Date(checkedAt - EXPIRED_RETENTION_MS)), + inArray(linkPreviews.id, tx.select({ id: linkPreviews.id }).from(linkPreviews).where(scopeCondition) + .orderBy(desc(linkPreviews.checkedAt), desc(linkPreviews.id)).offset(MAX_ROWS_PER_VIEWER)), + ))); + }); + }, + }; +} diff --git a/server/src/services/link-previews.ts b/server/src/services/link-previews.ts index 29041b51ce9..ae8bf43300d 100644 --- a/server/src/services/link-previews.ts +++ b/server/src/services/link-previews.ts @@ -1,4 +1,5 @@ import type { LinkPreviewResult, LinkPreviewTarget } from "@paperclipai/shared"; +import type { LinkPreviewStore, StoredLinkPreview } from "./link-preview-store.js"; import { recognizeLinkPreview } from "@paperclipai/shared"; export interface LinkPreviewScope { companyId: string; userId: string | null } @@ -9,22 +10,49 @@ export interface LinkPreviewProvider { const UNAVAILABLE: LinkPreviewResult = { preview: null, maxAgeMs: 60_000 }; -/** Request-driven and process-local. No DB writes, sweep, timers while idle, or cross-viewer reuse. */ +/** Request-driven cache: durable across restarts, isolated by viewer, with no idle worker. */ export function createLinkPreviewService(providers: readonly LinkPreviewProvider[], options: { - now?: () => number; timeoutMs?: number; maxEntries?: number; maxConcurrent?: number; + store?: LinkPreviewStore; now?: () => number; timeoutMs?: number; maxEntries?: number; maxConcurrent?: number; } = {}) { const now = options.now ?? Date.now; - const cache = new Map(); + const cache = new Map(); const inFlight = new Map>(); let activeOperations = 0; const byKey = new Map(providers.map(provider => [provider.key, provider])); + function remember(key: string, entry: StoredLinkPreview) { + if ((cache.get(key)?.checkedAt ?? -Infinity) > entry.checkedAt) return; + cache.delete(key); + while (cache.size >= (options.maxEntries ?? 1_000)) cache.delete(cache.keys().next().value!); + cache.set(key, entry); + } + const keyOf = (scope: LinkPreviewScope, url: string) => JSON.stringify([scope.companyId, scope.userId, url]); + const remaining = (entry: StoredLinkPreview) => ({ ...entry.result, maxAgeMs: Math.max(0, entry.expiresAt - now()) }); + const newest = (memory: StoredLinkPreview | undefined, stored: StoredLinkPreview | undefined) => + stored && (!memory || stored.checkedAt >= memory.checkedAt) ? stored : memory; + return { + async cached(scope: LinkPreviewScope, hrefs: readonly string[]) { + const targets = [...new Map(hrefs.map(recognizeLinkPreview).filter(target => target && byKey.has(target.provider)) + .map(target => [target!.canonicalUrl, target!])).values()]; + const stored = await options.store?.read(scope, targets).catch(() => new Map()); + const results: Record = {}; + for (const target of targets) { + const key = keyOf(scope, target.canonicalUrl); + const memory = cache.get(key); + const entry = newest(memory, stored?.get(target.canonicalUrl)); + if (entry) { remember(key, entry); results[target.canonicalUrl] = remaining(entry); } + // A batch miss is not a provider result. A later lookup must still + // check durable storage, which another replica may have populated. + else cache.delete(key); + } + return { results }; + }, async get(scope: LinkPreviewScope, href: string): Promise { const target = recognizeLinkPreview(href); const provider = target && byKey.get(target.provider); if (!target || !provider) return UNAVAILABLE; - const key = JSON.stringify([scope.companyId, scope.userId, target.canonicalUrl]); + const key = keyOf(scope, target.canonicalUrl); const cached = cache.get(key); if (cached && cached.expiresAt > now()) { return { ...cached.result, maxAgeMs: cached.expiresAt - now() }; @@ -35,20 +63,74 @@ export function createLinkPreviewService(providers: readonly LinkPreviewProvider const controller = new AbortController(); let timer: ReturnType; + let previous = cached; + const checkedAt = now(); + let providerStarted = false; + let storeWriteStarted = false; + let durableReadSucceeded = !options.store; + let timeoutWrite: Promise | undefined; + const fallback = (): LinkPreviewResult => ({ preview: newest(previous, cache.get(key))?.result.preview ?? null, maxAgeMs: 60_000 }); const deadline = new Promise(resolve => { - timer = setTimeout(() => { controller.abort(); resolve(UNAVAILABLE); }, options.timeoutMs ?? 5_000); + timer = setTimeout(() => { + const current = cache.get(key); + if (current && current.checkedAt > checkedAt) { + controller.abort(); + resolve(remaining(current)); + return; + } + const result = current && current.expiresAt > now() ? remaining(current) : fallback(); + const entry = { result, expiresAt: now() + result.maxAgeMs, + checkedAt: durableReadSucceeded || storeWriteStarted ? checkedAt : previous?.checkedAt ?? 0 }; + remember(key, entry); + // Publish timeout freshness without delaying the caller. The lookup + // keeps its slot until both the provider and this write settle. + if (options.store && durableReadSucceeded && providerStarted && !storeWriteStarted) { + timeoutWrite = Promise.resolve().then(() => options.store!.write(scope, target, entry, checkedAt)).catch(() => {}); + } + controller.abort(); + resolve(result); + }, options.timeoutMs ?? 5_000); }); - // Keep an underlying operation in the concurrency budget until it settles, - // even if a credential backend ignores cancellation after our deadline. + // All underlying work, including uncancellable SQL, retains its slot until + // settlement. The caller's deadline does not release the resource budget. activeOperations++; - const operation = Promise.resolve().then(() => provider.resolve(target, scope, controller.signal)) - .catch(() => UNAVAILABLE).finally(() => { activeOperations--; }); - const request = Promise.race([operation, deadline]).then(result => { + const operation = Promise.resolve().then(async () => { + if (options.store) { + // Fresh memory returned above. Expired memory is only a fallback: + // another replica may have saved a newer result, even with a shorter TTL. + const stored = await options.store.read(scope, [target]).catch(() => null); + durableReadSucceeded = stored !== null; + previous = newest(newest(previous, cache.get(key)), stored?.get(target.canonicalUrl)); + if (!controller.signal.aborted && previous) remember(key, previous); + } + if (controller.signal.aborted) return fallback(); + if (previous && previous.expiresAt > now()) { remember(key, previous); return remaining(previous); } + providerStarted = true; + const result = await provider.resolve(target, scope, controller.signal).catch(() => UNAVAILABLE); + if (controller.signal.aborted) return fallback(); + // A page batch can hydrate another replica's newer status while the + // provider is pending. That result wins over this older lookup. + previous = newest(previous, cache.get(key)); + if (previous && previous.checkedAt > checkedAt) return remaining(previous); const bounded = { ...result, maxAgeMs: Math.max(1_000, Math.min(result.maxAgeMs, 60 * 60_000)) }; - cache.delete(key); - while (cache.size >= (options.maxEntries ?? 1_000)) cache.delete(cache.keys().next().value!); - cache.set(key, { result: bounded, expiresAt: now() + bounded.maxAgeMs }); - return bounded; + if (!bounded.preview && previous?.result.preview) bounded.preview = previous.result.preview; + const entry = { result: bounded, expiresAt: now() + bounded.maxAgeMs, + checkedAt: durableReadSucceeded || result.preview ? checkedAt : previous?.checkedAt ?? 0 }; + remember(key, entry); + // A failed durable read cannot establish which saved status a provider + // failure would replace. Keep that backoff local until storage recovers. + if (options.store && (durableReadSucceeded || result.preview)) { + storeWriteStarted = true; + await options.store.write(scope, target, entry, checkedAt).catch(() => {}); + } + return remaining(entry); + }).catch(fallback).finally(async () => { await timeoutWrite; activeOperations--; }); + const request = Promise.race([operation, deadline]).then(result => { + const current = cache.get(key); + // Hydration can also finish while the operation awaits its SQL write. + if (current && current.checkedAt > checkedAt) return remaining(current); + if (!current || current.expiresAt <= now()) remember(key, { result, expiresAt: now() + result.maxAgeMs, checkedAt }); + return result; }).finally(() => { clearTimeout(timer!); if (inFlight.get(key) === request) inFlight.delete(key); diff --git a/server/src/services/native-runtime/native-github-access.test.ts b/server/src/services/native-runtime/native-github-access.test.ts index c979240c15f..847434bf850 100644 --- a/server/src/services/native-runtime/native-github-access.test.ts +++ b/server/src/services/native-runtime/native-github-access.test.ts @@ -1,6 +1,6 @@ import { afterEach, expect, it, vi } from "vitest"; import { spawn, execFile } from "node:child_process"; -import { mkdtemp, mkdir, readFile, rm, writeFile, access } from "node:fs/promises"; +import { mkdtemp, mkdir, readdir, readFile, rm, stat, writeFile, access } from "node:fs/promises"; import { promisify } from "node:util"; import type { CommandManagedDuplexChannel, CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; import type { DuplexObservabilityRecorder } from "@paperclipai/adapter-utils/duplex-observability"; @@ -40,11 +40,12 @@ function localDuplexChannel(command: readonly string[], cwd: string): CommandMan async function broker(resolveCredentials = vi.fn(async (binding: ReturnType) => ({ status: "available", env: { GH_TOKEN: `fixture-${binding.runId}` }, })), remote = false, bridgeUnavailable = false, onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise, -duplex?: { enabled?: boolean; capability: boolean; unavailable?: boolean; startupFailure?: "lost" | "unreachable"; fallbackUnavailable?: boolean; fileProbeFails?: boolean; recorder?: DuplexObservabilityRecorder }) { - const root = await mkdtemp(path.join(tmpdir(), "native-github-reuse-")); - cleanups.push(() => rm(root, { recursive: true, force: true })); +duplex?: { enabled?: boolean; capability: boolean; unavailable?: boolean; startupFailure?: "lost" | "unreachable"; fallbackUnavailable?: boolean; fileProbeFails?: boolean; recorder?: DuplexObservabilityRecorder }, +placement: { root?: string; launcherKey?: string } = {}) { + const root = placement.root ?? await mkdtemp(path.join(tmpdir(), "native-github-reuse-")); + if (!placement.root) cleanups.push(() => rm(root, { recursive: true, force: true })); const bin = path.join(root, "real-bin"); - await mkdir(bin); + await mkdir(bin, { recursive: true }); await writeFile(path.join(bin, "gh"), `#!${process.execPath}\nprocess.stdout.write(process.env.GH_TOKEN || 'anonymous');`, { mode: 0o700 }); const execute = vi.fn(async (input) => { const startedAt = new Date().toISOString(); @@ -70,7 +71,8 @@ duplex?: { enabled?: boolean; capability: boolean; unavailable?: boolean; startu const bridgeModes: (string | undefined)[] = []; const bridges: NonNullable>>[] = []; const result = await createNativeGitHubAccess({ scope, target, cwd: root, - env: { PATH: `${bin}:${path.dirname(process.execPath)}:/usr/bin:/bin`, PAPERCLIP_API_KEY: "old-run-api-key" }, resolveCredentials, onLog }, + env: { PATH: `${bin}:${path.dirname(process.execPath)}:/usr/bin:/bin`, PAPERCLIP_API_KEY: "old-run-api-key" }, resolveCredentials, onLog, + launcherKey: placement.launcherKey }, bridgeUnavailable ? async () => { throw new Error("fixture bridge unavailable"); } : async input => { if (duplex?.fallbackUnavailable && input.enableSandboxDuplexBridge === false) throw new Error("fixture fallback unavailable"); const bridge = await startAdapterExecutionTargetPaperclipBridge(input); @@ -273,6 +275,103 @@ it.each([false, true])("keeps one live parent and its original launcher environm releaseB(); await b.stop(); await expect(access(b.env.PAPERCLIP_GITHUB_LAUNCHER_DIR)).rejects.toThrow(); }, 45_000); +function liveParent(env: Record) { + const parent = spawn(process.execPath, ["-e", ` + const {execFile}=require('node:child_process'); + require('node:readline').createInterface({input:process.stdin}).on('line', () => { + execFile('gh', [], (error, stdout, stderr) => console.log(JSON.stringify({pid:process.pid, value:stdout, error:error?.message, stderr}))); + }); + `], { env: { ...process.env, ...env }, stdio: ["pipe", "pipe", "pipe"] }); + cleanups.push(async () => { const exited = new Promise(resolve => parent.once("exit", () => resolve())); parent.kill(); await exited; }); + const lines = createInterface({ input: parent.stdout }); + return () => new Promise<{ pid: number; value: string; stderr: string }>(resolve => { + lines.once("line", line => resolve(JSON.parse(line))); parent.stdin.write("run\n"); + }); +} +it("re-arms a live sandbox provider's launchers after its controller restarts", async () => { + const remote = true; + const root = await mkdtemp(path.join(tmpdir(), "native-github-restart-")); + cleanups.push(() => rm(root, { recursive: true, force: true })); + const before = await broker(undefined, remote, false, undefined, undefined, { root, launcherKey: "session-a" }); + const operation = liveParent(before.env); + const releaseBefore = before.activate(run("run-a")); + const first = await operation(); + expect(first.value).toBe("fixture-run-a"); + releaseBefore(); + await before.stop({ preserveLaunchers: true }); + const launchers = before.env.PAPERCLIP_GITHUB_LAUNCHER_DIR; + await access(path.join(launchers, "gh")); + const after = await broker(vi.fn(async (binding: ReturnType) => ({ + status: "available", env: { GH_TOKEN: `adopted-${binding.runId}` }, + })), remote, false, undefined, undefined, { root, launcherKey: "session-a" }); + expect(after.env.PAPERCLIP_GITHUB_LAUNCHER_DIR).toBe(launchers); + expect(after.env.PAPERCLIP_GITHUB_BROKER_TOKEN).not.toBe(before.env.PAPERCLIP_GITHUB_BROKER_TOKEN); + const releaseAfter = after.activate(run("run-a")); + const adopted = await operation(); + expect(adopted).toMatchObject({ pid: first.pid, value: "adopted-run-a", stderr: "" }); + expect(await readFile(path.join(launchers, "gh"), "utf8")).not.toContain(after.env.PAPERCLIP_GITHUB_BROKER_TOKEN); + expect((await stat(path.join(launchers, "broker.json"))).mode & 0o777).toBe(0o600); + releaseAfter(); + await after.stop(); + await expect(access(launchers)).rejects.toThrow(); +}, 45_000); +it("keeps launchers a successor re-armed when a superseded access stops", async () => { + const root = await mkdtemp(path.join(tmpdir(), "native-github-successor-")); + cleanups.push(() => rm(root, { recursive: true, force: true })); + const superseded = await broker(undefined, true, false, undefined, undefined, { root, launcherKey: "session-a" }); + const successor = await broker(vi.fn(async () => ({ status: "available", env: { GH_TOKEN: "successor" } })), + true, false, undefined, undefined, { root, launcherKey: "session-a" }); + const operation = liveParent(superseded.env); + await superseded.stop(); + successor.activate(run("run-b")); + expect(await operation()).toMatchObject({ value: "successor", stderr: "" }); + const other = await broker(undefined, true, false, undefined, undefined, { root, launcherKey: "session-b" }); + expect(other.env.PAPERCLIP_GITHUB_LAUNCHER_DIR).not.toBe(successor.env.PAPERCLIP_GITHUB_LAUNCHER_DIR); +}); +it("keeps a previous-release provider running without managed GitHub after the cutover restart", async () => { + const root = await mkdtemp(path.join(tmpdir(), "native-github-cutover-")); + cleanups.push(() => rm(root, { recursive: true, force: true })); + const previous = await broker(undefined, true, false, undefined, undefined, { root }); + const operation = liveParent(previous.env); + const releasePrevious = previous.activate(run("run-a")); + expect((await operation()).value).toBe("fixture-run-a"); + releasePrevious(); + await previous.stop(); + await expect(access(previous.env.PAPERCLIP_GITHUB_LAUNCHER_DIR)).rejects.toThrow(); + const current = await broker(undefined, true, false, undefined, undefined, { root, launcherKey: "session-a" }); + expect(current.env.PAPERCLIP_GITHUB_LAUNCHER_DIR).not.toBe(previous.env.PAPERCLIP_GITHUB_LAUNCHER_DIR); + current.activate(run("run-a")); + expect(await operation()).toMatchObject({ value: "anonymous", stderr: "" }); + expect(current.resolveCredentials).not.toHaveBeenCalled(); + await expect(liveParent(current.env)()).resolves.toMatchObject({ value: "fixture-run-a" }); +}, 45_000); +it("tells a local provider adopted after a restart that managed GitHub is unavailable", async () => { + const root = await mkdtemp(path.join(tmpdir(), "native-github-local-restart-")); + cleanups.push(() => rm(root, { recursive: true, force: true })); + const before = await broker(undefined, false, false, undefined, undefined, { root, launcherKey: "session-a" }); + const operation = liveParent(before.env); + const releaseBefore = before.activate(run("run-a")); + expect((await operation()).value).toBe("fixture-run-a"); + releaseBefore(); + await before.stop({ preserveLaunchers: true }); + const after = await broker(undefined, false, false, undefined, undefined, { root, launcherKey: "session-a" }); + after.activate(run("run-a")); + const adopted = await operation(); + expect(adopted.value).toBe("anonymous"); + expect(adopted.stderr).toMatch(/^Paperclip: GitHub (broker_transport_unavailable|capability_rejected|broker_response_unavailable); continuing without managed credentials\.\n$/); + expect(after.resolveCredentials).not.toHaveBeenCalled(); +}, 45_000); +it("keeps the broker capability out of local launcher files", async () => { + const b = await broker(undefined, false, false, undefined, undefined, { launcherKey: "session-a" }); + const files = await readdir(b.env.PAPERCLIP_GITHUB_LAUNCHER_DIR, { recursive: true }); + expect(files).not.toContain("broker.json"); + for (const file of files) { + const target = path.join(b.env.PAPERCLIP_GITHUB_LAUNCHER_DIR, file); + if ((await stat(target)).isFile()) expect(await readFile(target, "utf8")).not.toContain(b.env.PAPERCLIP_GITHUB_BROKER_TOKEN); + } + b.activate(run("local")); + expect(await liveParent(b.env)()).toMatchObject({ value: "fixture-local", stderr: "" }); +}); it("rejects other scopes, concurrent bindings, browser requests and forged authority", async () => { const b = await broker(); for (const field of ["companyId", "agentId", "issueId"] as const) { diff --git a/server/src/services/native-runtime/native-github-access.ts b/server/src/services/native-runtime/native-github-access.ts index dccdf8fc7d6..f33d37b9a53 100644 --- a/server/src/services/native-runtime/native-github-access.ts +++ b/server/src/services/native-runtime/native-github-access.ts @@ -1,4 +1,4 @@ -import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; +import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; import { createServer } from "node:http"; import { cleanupGitHubOperationLaunchers, @@ -15,6 +15,8 @@ type Binding = { companyId: string; agentId: string; issueId: string; runId: str type LauncherInput = Parameters[0]; export type NativeGitHubAccess = Awaited>; +const launcherOwners = new Map(); + /** A process-lifetime transport, with authority only while its controller owns a run. * No run token or GitHub credential is stored in the provider's environment/files. * The resolver still checks the active run and current identity/grants per operation. @@ -26,10 +28,17 @@ export async function createNativeGitHubAccess(input: { env: NodeJS.ProcessEnv; resolveCredentials: (binding: Binding) => Promise; onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise; + launcherKey?: string; }, startBridge = startAdapterExecutionTargetPaperclipBridge) { const duplexRequested = adapterExecutionTargetEnablesSandboxDuplexBridge(input.target); const token = randomBytes(32).toString("hex"); const location = { runId: `native-session-${randomUUID()}`, target: input.target }; + const launcherLocation = input.launcherKey === undefined ? location : { + runId: `native-github-${createHash("sha256").update(input.launcherKey).digest("hex").slice(0, 32)}`, + target: input.target, + }; + const launcherDirectory = githubOperationLauncherDirectory(launcherLocation); + const launcherOwner = Symbol("GitHub launcher owner"); let active: Binding | null = null; let stopped = false; let ready = true; @@ -82,14 +91,17 @@ export async function createNativeGitHubAccess(input: { }); server.requestTimeout = 15_000; server.headersTimeout = 10_000; - const stop = () => stopping ??= (async () => { + const stop = (options: { preserveLaunchers?: boolean } = {}) => stopping ??= (async () => { stopped = true; active = null; server.closeAllConnections(); + const removeLaunchers = !options.preserveLaunchers && launcherOwners.get(launcherDirectory) === launcherOwner; + if (removeLaunchers) launcherOwners.delete(launcherDirectory); const results = await Promise.allSettled([ stopBridge(), new Promise(resolve => server.close(() => resolve())), - cleanupGitHubOperationLaunchers(location), + ...(launcherLocation !== location ? [cleanupGitHubOperationLaunchers(location)] : []), + ...(removeLaunchers ? [cleanupGitHubOperationLaunchers(launcherLocation)] : []), ]); if (results.some(result => result.status === "rejected")) { await input.onLog?.("stderr", "[paperclip] GitHub session cleanup incomplete.\n").catch(() => undefined); @@ -161,15 +173,17 @@ export async function createNativeGitHubAccess(input: { await new Promise(resolve => server.close(() => resolve())); await input.onLog?.("stderr", "[paperclip] GitHub runtime transport unavailable; continuing without managed GitHub access.\n").catch(() => undefined); } + const broker = { + url: ready ? bridge?.env.PAPERCLIP_API_URL ?? url : "", + token: ready ? bridge?.env.PAPERCLIP_API_KEY ?? token : "", + }; + launcherOwners.set(launcherDirectory, launcherOwner); const env = await prepareGitHubOperationLaunchers({ - ...location, cwd: input.cwd, + ...launcherLocation, cwd: input.cwd, ...(input.target?.kind === "remote" ? { broker } : {}), env: { - ...githubBrokerEnvironment({ PATH: input.env.PATH }, { - url: ready ? bridge?.env.PAPERCLIP_API_URL ?? url : "", - token: ready ? bridge?.env.PAPERCLIP_API_KEY ?? token : "", - }), + ...githubBrokerEnvironment({ PATH: input.env.PATH }, broker), // Never retain an old run's bridge authentication override. - PAPERCLIP_GITHUB_BRIDGE_TOKEN: ready ? bridge?.env.PAPERCLIP_API_KEY ?? token : "", + PAPERCLIP_GITHUB_BRIDGE_TOKEN: broker.token, }, }); return { diff --git a/server/src/services/native-runtime/native-provider-capacity-retry.ts b/server/src/services/native-runtime/native-provider-capacity-retry.ts index a472054ee17..79952d5869b 100644 --- a/server/src/services/native-runtime/native-provider-capacity-retry.ts +++ b/server/src/services/native-runtime/native-provider-capacity-retry.ts @@ -5,29 +5,74 @@ import { and, eq } from "drizzle-orm"; import { agentWakeupRequests, heartbeatRuns, type Db } from "@paperclipai/db"; import { accountingForScheduledRetry, executionFailureRetryCount } from "../execution-recovery-attempt.js"; import { NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, NATIVE_PROVIDER_OVERLOADED_CODE, NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js"; +import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_CONTINUATION_DELAY_MS, NATIVE_TOOL_RECEIPT_LIMIT_HINT, + NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS, NATIVE_TOOL_RECEIPT_LIMIT_MESSAGE, nativeRunHasStopRequest } from "./native-tool-receipt-limit.js"; +import { NativeStatusRaceError } from "./status-decision-committer.js"; -/** Called under the finalizer's issue/coordinator locks, in the status-effect transaction. */ -export async function materializeNativeProviderCapacityRetry(input: { +type NativeRetryTarget = { tx: Db; companyId: string; issueId: string; runId: string; agentId: string; -}) { +}; + +type NativeRetryLane = { + reason: string; + maxRetries: number; + delayMs: (attempt: number) => number; + message: string; + idempotencyPrefix: string; + exhaustedError: string; + context?: (run: typeof heartbeatRuns.$inferSelect) => Record; + refuseStopped?: boolean; +}; + +/** Called under the finalizer's issue/coordinator locks, in the status-effect transaction. */ +export async function materializeNativeProviderCapacityRetry(input: NativeRetryTarget) { + return materializeNativeFreshSessionRetry(input, { + reason: NATIVE_PROVIDER_OVERLOADED_CODE, + maxRetries: NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, + delayMs: attempt => 60_000 * 2 ** (attempt - 1), + message: NATIVE_PROVIDER_OVERLOADED_MESSAGE, + idempotencyPrefix: "native-capacity", + exhaustedError: "native_capacity_retry_exhausted", + }); +} + +export async function materializeNativeToolReceiptLimitContinuation(input: NativeRetryTarget) { + return materializeNativeFreshSessionRetry(input, { + reason: NATIVE_TOOL_RECEIPT_LIMIT_CODE, + maxRetries: NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS, + delayMs: () => NATIVE_TOOL_RECEIPT_LIMIT_CONTINUATION_DELAY_MS, + message: NATIVE_TOOL_RECEIPT_LIMIT_MESSAGE, + idempotencyPrefix: "native-tool-receipt-limit", + exhaustedError: "native_tool_receipt_limit_continuation_exhausted", + refuseStopped: true, + context: run => ({ + livenessContinuationSourceRunId: run.id, + livenessContinuationReason: NATIVE_TOOL_RECEIPT_LIMIT_CODE, + livenessContinuationInstruction: NATIVE_TOOL_RECEIPT_LIMIT_HINT, + }), + }); +} + +async function materializeNativeFreshSessionRetry(input: NativeRetryTarget, lane: NativeRetryLane) { const [run] = await input.tx.select().from(heartbeatRuns).where(and( eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.agentId, input.agentId), eq(heartbeatRuns.nativeIssueId, input.issueId), )).for("update"); if (!run || run.runtimeMode !== "native") throw new Error("native_capacity_retry_run_binding_mismatch"); + if (lane.refuseStopped && nativeRunHasStopRequest(run.resultJson)) throw new NativeStatusRaceError(); // Share the predecessor claim with every other failure-retry lane. const [existing] = await input.tx.select().from(heartbeatRuns).where(and( eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.retryOfRunId, run.id), )).limit(1); if (existing) return existing.id; const attempt = executionFailureRetryCount(run) + 1; - if (attempt > NATIVE_PROVIDER_CAPACITY_MAX_RETRIES) throw new Error("native_capacity_retry_exhausted"); + if (attempt > lane.maxRetries) throw new Error(lane.exhaustedError); const now = new Date(); - const dueAt = new Date(now.getTime() + 60_000 * 2 ** (attempt - 1)); + const dueAt = new Date(now.getTime() + lane.delayMs(attempt)); const retryId = randomUUID(); const predecessorContext = { ...run.contextSnapshot }; // Resume receipts and delivered wake input belong to the failed run. The @@ -45,18 +90,19 @@ export async function materializeNativeProviderCapacityRetry(input: { taskId: input.issueId, forceFreshSession: true, retryOfRunId: run.id, - retryReason: NATIVE_PROVIDER_OVERLOADED_CODE, - wakeReason: NATIVE_PROVIDER_OVERLOADED_CODE, + retryReason: lane.reason, + wakeReason: lane.reason, scheduledRetryAttempt: attempt, scheduledRetryAt: dueAt.toISOString(), - executionRetryAccounting: accountingForScheduledRetry(run, NATIVE_PROVIDER_OVERLOADED_CODE, attempt), + executionRetryAccounting: accountingForScheduledRetry(run, lane.reason, attempt), + ...lane.context?.(run), }; await notifyIssueAttentionRetentionWork(input.tx, { companyId: input.companyId, issueId: input.issueId, runId: run.id }); await notifyScheduledRetryDispatch(input.tx, { companyId: run.companyId, runId: run.id }); const [wake] = await input.tx.insert(agentWakeupRequests).values({ companyId: run.companyId, agentId: run.agentId, source: "automation", triggerDetail: "system", - reason: NATIVE_PROVIDER_OVERLOADED_CODE, status: "queued", runId: retryId, - idempotencyKey: `native-capacity:${run.companyId}:${run.id}`, + reason: lane.reason, status: "queued", runId: retryId, + idempotencyKey: `${lane.idempotencyPrefix}:${run.companyId}:${run.id}`, requestedByActorType: "system", requestedByActorId: "native_finalizer", payload: contextSnapshot, }).returning({ id: agentWakeupRequests.id }); @@ -64,9 +110,9 @@ export async function materializeNativeProviderCapacityRetry(input: { id: retryId, companyId: run.companyId, agentId: run.agentId, invocationSource: "automation", triggerDetail: "system", status: "scheduled_retry", responsibleUserId: run.responsibleUserId, wakeupRequestId: wake.id, - retryOfRunId: run.id, scheduledRetryReason: NATIVE_PROVIDER_OVERLOADED_CODE, + retryOfRunId: run.id, scheduledRetryReason: lane.reason, scheduledRetryAttempt: attempt, scheduledRetryAt: dueAt, - error: NATIVE_PROVIDER_OVERLOADED_MESSAGE, errorCode: NATIVE_PROVIDER_OVERLOADED_CODE, + error: lane.message, errorCode: lane.reason, contextSnapshot, }); return retryId; diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index df6232eb978..eb5dd3977eb 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -32,6 +32,7 @@ import { settleExternalConversation } from "../slack-conversation-lifecycle.js"; import { executionFailureRetryCount } from "../execution-recovery-attempt.js"; import { isFailedTurnContinuationRun } from "./native-failed-turn-continuation.js"; import { readPersistedNativeFailureEvidence } from "./native-provider-failure-evidence.js"; +import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, cancelStoppedRunContinuation, nativeRunHasStopRequest, readPersistedNativeToolReceiptLimitStop } from "./native-tool-receipt-limit.js"; import { explainFailedRun, explainNativeTurnFailure, NATIVE_RUN_FAILED_UNEXPLAINED } from "./native-run-failure-explanation.js"; import { dismissAutomaticCompletionReviews } from "./automatic-completion-reviews.js"; import { findSupersededExternalReviewRequests } from "./superseded-external-review-requests.js"; @@ -1607,6 +1608,10 @@ export async function finalizeNativeRun(input: { const allowIncompleteContinuation = record(sourceWake?.payload).continuationIdempotencyKey !== "native-completion-incomplete"; let supersedesAssessmentId: string | null = coordinator.assessmentId; for (let attempt = 0; attempt < 3; attempt += 1) { + const savedStop = attempt === 0 ? run.resultJson : await input.db.select({ resultJson: heartbeatRuns.resultJson }) + .from(heartbeatRuns).where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId))) + .then(rows => rows[0]?.resultJson ?? run.resultJson); + const stopRequested = nativeRunHasStopRequest(savedStop); const authoritativeIssue = await input.db .select() .from(issues) @@ -1747,6 +1752,7 @@ export async function finalizeNativeRun(input: { // issue route decides `status: "done"`. Review runs keep their own path. const reviewStage = isConversation(authoritativeIssue) || reviewContext ? { kind: "none" as const } : completionReviewStageEntry(authoritativeIssue, run.agentId); + await cancelStoppedRunContinuation(input.db, { companyId: run.companyId, resultJson: savedStop }, toolCallLoopContinuationKey(run.id)); const statusInput: Parameters[0] = { requiredQualityReviewSatisfied: qualityReview.satisfied, executionStageApprovedByRun: await executionStageApprovedByRun(input.db, run, authoritativeIssue), @@ -1761,13 +1767,16 @@ export async function finalizeNativeRun(input: { providerModelRejected: providerFailure?.errorCode === "native_provider_model_rejected" && ownsProviderFailureDecision, providerOverloaded: providerFailure?.errorCode === "native_provider_overloaded" && ownsProviderFailureDecision, providerFailureSuperseded: providerFailure?.errorCode === "native_provider_overloaded" && !ownsProviderFailureDecision, + toolReceiptLimitStopped: terminalState !== "succeeded" && ownsProviderFailureDecision && !reviewContext + && !stopRequested && await readPersistedNativeToolReceiptLimitStop(input.db, run, resultRow.turnId), failureRetryCount: executionFailureRetryCount(run), // Only the task's current owner may turn its own failed continuation // into a blocker; the committer rechecks that under the issue lock. failedTurnContinuationUsed: terminalState === "failed" && ownsProviderFailureDecision && !reviewContext && await isFailedTurnContinuationRun(input.db, run, authoritativeIssue.id), toolCallLoopContinuation: assessment.reportedDisposition === "yielded" - && assessment.continuation?.idempotencyKey === toolCallLoopContinuationKey(run.id), + && assessment.continuation?.idempotencyKey === toolCallLoopContinuationKey(run.id) + && !stopRequested, ...(reviewContext ? { nativeReviewOutcome: nativeReview ? nativeReview.interaction.status === "pending" ? "pending" as const : "resolved" as const : "stale" as const } : {}), @@ -1922,6 +1931,7 @@ export async function finalizeNativeRun(input: { : undefined, requireProviderFailureOwner: decision.reasonCode?.startsWith("native_provider_overloaded") || decision.reasonCode === "native_run_failed_continuation_exhausted" + || decision.reasonCode === NATIVE_TOOL_RECEIPT_LIMIT_CODE ? { agentId: run.agentId, reviewContext } : undefined, requireBoardResponseWaitSource: decision.reasonCode === "board_response_waiting" || repairBoardResponseWait diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 142e0c6e7e7..13fb4614f48 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -8692,6 +8692,49 @@ describe("native startup restart detachment", () => { } finally { await newerDetach; issueService.mockRestore(); } }); + it("keeps managed GitHub launchers for a provider that outlives its restart detach", async () => { + const root = await mkdtemp(join(tmpdir(), "native-github-detach-")); + const previous = process.env.PAPERCLIP_RUNNER_STATE_DIR; + process.env.PAPERCLIP_RUNNER_STATE_DIR = root; + const restarting = structuredClone(execution); + restarting.binding.runId = "restart-managed-github"; + restarting.session.normalizedSessionId = "restart-managed-github-session"; + let open!: () => void, started!: () => void; + const opening = new Promise(resolve => { open = resolve; }); + const admitted = new Promise(resolve => { started = resolve; }); + const stop = vi.fn(async (_options?: { preserveLaunchers?: boolean }) => undefined); + githubAccess.create.mockImplementationOnce(async () => ({ env: {}, ready: true, duplexRequested: false, + activate: vi.fn(() => vi.fn()), stop })); + state.execute.mockReset().mockImplementationOnce(async (options) => { + started(); + await opening; + await options.onSession({ detachControllerForRestart: async () => undefined }); + await options.onSession(null); + throw new Error("detachment closed the old event stream"); + }); + const outcome = executePaperclipNativeSession({ db: leaseDb(restarting), execution: restarting, + runnerInstanceId: "runner", useRunnerd: true, managedGitHub: true }).catch(error => error); + let detaching: Promise | undefined; + try { + await admitted; + detaching = detachNativeSessionsForRestart([restarting.binding.runId]); + open(); + expect(await detaching).toMatchObject({ detachedRunIds: [restarting.binding.runId] }); + expect(await outcome).toBeInstanceOf(NativeControllerDetachedForRestartError); + expect(githubAccess.create).toHaveBeenLastCalledWith(expect.objectContaining({ + launcherKey: expect.stringContaining(restarting.binding.issueId), + })); + expect(stop).toHaveBeenCalledExactlyOnceWith({ preserveLaunchers: true }); + } finally { + open(); + await outcome; + await detaching; + if (previous === undefined) delete process.env.PAPERCLIP_RUNNER_STATE_DIR; + else process.env.PAPERCLIP_RUNNER_STATE_DIR = previous; + await rm(root, { recursive: true, force: true }); + } + }); + it("uses one admission deadline for the whole restart sweep", async () => { const inputs = ["first", "second"].map(label => { const input = structuredClone(execution); @@ -18483,7 +18526,7 @@ describe("runnerd provider runtime wiring", () => { if (failure === "assigned") { expect(activate).toHaveBeenCalledWith(current.binding); expect(deactivate).toHaveBeenCalledOnce(); - expect(stop).toHaveBeenCalledOnce(); + expect(stop).toHaveBeenCalledExactlyOnceWith({ preserveLaunchers: false }); } } finally { releaseGitHub(); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index c48e91d92e4..c4a80912ee2 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -922,7 +922,7 @@ async function detachReleasedWarmNativeSession(entry: WarmNativeSession) { entry.controllerDetachedForRestart = true; if (!entry.session.detachControllerForRestart) throw new Error("native_session_released_detach_unavailable"); await entry.session.detachControllerForRestart(); - await entry.githubAccess?.stop(); + await entry.githubAccess?.stop({ preserveLaunchers: true }); } const warmNativeSessions = new Map(); @@ -2559,6 +2559,14 @@ function nativeSessionScopeKey(execution: NativeExecutionInput): string { }); } +function nativeGitHubLauncherKey(execution: NativeExecutionInput): string { + return canonicalJson({ + schema: "paperclip.native-github-launcher.v1", + session: nativeSessionScopeKey(execution), + issueId: execution.binding.issueId, + }); +} + // A plan acceptance or explicit reset can rotate the provider/session identity // while retaining the same task sandbox and its fixed ingress port. function nativeSessionOwnerScope( @@ -12456,6 +12464,7 @@ async function executePaperclipNativeSessionAttempt( env: resolveNativeProviderEnvironment(input.execution.provider, input.runnerEnvironment), resolveCredentials: (binding) => resolveGitHubOperationCredentials(input.db, binding), onLog: input.onLog, + launcherKey: nativeGitHubLauncherKey(input.execution), })); executionContext?.assertOpen(); releaseGitHubRun = githubAccess.activate(input.execution.binding); @@ -13878,7 +13887,8 @@ async function executePaperclipNativeSessionAttempt( settlingNativeSessionScopes.set(nativeSessionScopeKey(input.execution), input.execution.binding.runId); releaseGitHubRun?.(); if (githubAccess && (!warmSessionId || warmNativeSessions.get(warmSessionId)?.githubAccess !== githubAccess)) { - await timeController("github_stop", () => githubAccess!.stop()); + const preserveLaunchers = nativeRunsDetachingForRestart.has(input.execution.binding.runId); + await timeController("github_stop", () => githubAccess!.stop({ preserveLaunchers })); } } let postExecutionFailed = false; diff --git a/server/src/services/native-runtime/native-tool-receipt-limit.integration.test.ts b/server/src/services/native-runtime/native-tool-receipt-limit.integration.test.ts new file mode 100644 index 00000000000..594a1ee0262 --- /dev/null +++ b/server/src/services/native-runtime/native-tool-receipt-limit.integration.test.ts @@ -0,0 +1,196 @@ +import { randomUUID } from "node:crypto"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, agentWakeupRequests, companies, completionContracts, createDb, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, statusDecisionEffects, statusDecisions } from "@paperclipai/db"; +import type { ControlPlanePort, NativeExecutionInputV1, PrpEvent, PrpTerminalState } from "@paperclipai/paperclip-runner"; +import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { CONTROL_PLANE_CONFORMANCE_RESULT } from "../../vendor/paperclip-runner/testing.js"; + +const provider = vi.hoisted(() => ({ execute: vi.fn() })); +const receiptLimitRead = vi.hoisted(() => ({ after: null as null | (() => Promise) })); +vi.mock("./native-tool-receipt-limit.js", async (importOriginal) => { + const original = await importOriginal(); + return { ...original, readPersistedNativeToolReceiptLimitStop: async (...args: Parameters) => { + const stopped = await original.readPersistedNativeToolReceiptLimitStop(...args); + const after = receiptLimitRead.after; + receiptLimitRead.after = null; + await after?.(); + return stopped; + } }; +}); +vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({ + ...(await importOriginal()), executeNativeSession: provider.execute, +})); +import { executePaperclipNativeSession } from "./native-session-executor.js"; +import { buildNativeCompletionContract } from "./completion-contracts.js"; +import { prepareNativeHeartbeatRun } from "./prepare-native-run.js"; +import { finalizeNativeRun } from "./native-run-finalizer.js"; +import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_CONTINUATION_DELAY_MS, NATIVE_TOOL_RECEIPT_LIMIT_HINT, + readPersistedNativeToolReceiptLimitStop } from "./native-tool-receipt-limit.js"; +import { heartbeatService } from "../heartbeat.js"; +import { createPostgresWakeQueueAdapter } from "../../modules/wake-queue/adapters/postgres.js"; +import { createReleaseIssueExecution } from "../../modules/wake-queue/application/use-cases.js"; +import { taskInterruptionPresentation } from "../task-interruption-presentation.js"; +import { materializeNativeToolReceiptLimitContinuation } from "./native-provider-capacity-retry.js"; +import { NativeStatusRaceError } from "./status-decision-committer.js"; + +describe("native turn stopped at its tool receipt limit", () => { + let temporary: Awaited>; + let db: ReturnType; + const companyId = randomUUID(), agentId = randomUUID(); + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("native-tool-receipt-limit-"); + db = createDb(temporary.connectionString); + await db.insert(companies).values({ id: companyId, name: "Receipt limit regression", issuePrefix: "RCL" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Receipt worker", status: "active", adapterType: "paperclip_runner", adapterConfig: { provider: "opencode", model: "test-model" } }); + }); + afterAll(async () => { await temporary?.cleanup(); }); + + let finalTurnId: string | null = null; + async function stopAtReceiptLimit(runId: string, issueId: string, diagnosticCode: string, beforeFinalize?: () => Promise, + diagnosticTurnId?: string) { + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + const [run] = await db.update(heartbeatRuns).set({ status: "running", runtimeMode: "native", nativeIssueId: issueId, error: null, errorCode: null }).where(eq(heartbeatRuns.id, runId)).returning(); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + const native = await prepareNativeHeartbeatRun({ db, run, issue, environmentLeaseId: randomUUID() }); + const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId)); + const contractInput = buildNativeCompletionContract(issue, { revision: contract.revision }); + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed" }); + const execution: NativeExecutionInputV1 = { + schema: "paperclip.native-execution-input.v1", binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId }, + provider: { kind: "codex", model: "test-model" }, + task: { identifier: issueId, title: issue.title, description: null, prompt: "Continue the task using its history.", workMode: "standard" }, + workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null }, + session: { normalizedSessionId: native.normalizedSessionId, driverKind: "codex_app_server", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } }, + completionContract: { id: contract.id, sha256: contract.canonicalSha256, schemaVersion: "paperclip.completion-contract.v1", contract: contractInput }, + interactionResponses: [], credentialBindings: [], + }; + await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, runId)); + const event: PrpEvent = { + schema: "paperclip.prp.event.v1", runId, normalizedSessionId: native.normalizedSessionId, turnId: diagnosticTurnId ?? native.turnId, + sourceInstanceId: native.runnerInstanceId, sourceEventId: "receipt-limit", sourceSeq: 1, sourceKind: "runner", eventType: "harness.diagnostic", schemaVersion: 1, priority: 0, emittedAt: new Date().toISOString(), + payload: { provider: "opencode", code: diagnosticCode, operationId: "get_task", callId: "call-80", + message: "The active provider turn reached its durable semantic-tool receipt limit and was interrupted", paperclipExecuted: false }, + }; + const terminal: PrpTerminalState = { schema: "paperclip.prp.terminal.v1", turnTerminalState: "interrupted", runTerminalState: "cancelled", reportedWorkDisposition: "needs_review" }; + const result = { ...CONTROL_PLANE_CONFORMANCE_RESULT, reportedWorkDisposition: "needs_review" as const, + summary: "The OpenCode run stopped before it completed.", + completionClaim: { ...CONTROL_PLANE_CONFORMANCE_RESULT.completionClaim, contractRevision: contractInput.revision }, + attentionRequests: [{ kind: "review" as const, summary: "Review the stopped OpenCode run before continuing.", ownerClass: "human" as const }] }; + provider.execute.mockReset().mockImplementation(async (options: { controlPlane: ControlPlanePort }) => { + await options.controlPlane.openRun({ identity: { companyId, issueId, runId, agentId, sessionId: native.normalizedSessionId }, backendKind: "mock", sourceInstanceId: native.runnerInstanceId }); + await options.controlPlane.appendEvent(event); + await options.controlPlane.completeRun({ result, terminal, turnId: native.turnId }); + return { result, terminal, turnId: native.turnId, normalizedSessionId: native.normalizedSessionId, providerSessionId: "fixture-session", driverKind: "codex_app_server", driverVersion: "fixture", nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null }; + }); + const unexpected = async () => { throw new Error("Unexpected provider call"); }; + await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: { descriptor: unexpected, openSession: unexpected } }); + await beforeFinalize?.(); + for (let replay = 0; replay < 2; replay++) await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + expect(provider.execute).toHaveBeenCalledTimes(1); + finalTurnId = native.turnId; + return (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]!; + } + + function release() { + const unexpected = vi.fn(async () => { throw new Error("Unexpected recovery"); }); + return createReleaseIssueExecution({ + issueLock: createPostgresWakeQueueAdapter(db, { resolveResponsibleUserId: unexpected, getRoutineEnv: unexpected, resolveSessionBeforeForWakeup: unexpected }), + recovery: { escalateStrandedAssignedIssue: unexpected, escalateStrandedRecoveryIssueInPlace: unexpected }, + }); + } + + it("continues the task at once in a fresh session and shows no Retry", async () => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Parallel reads task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "receipt-owner" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "receipt-owner", contextSnapshot: { issueId, wakeCommentId: "original-message" } }); + const stopped = await stopAtReceiptLimit(runId, issueId, NATIVE_TOOL_RECEIPT_LIMIT_CODE); + expect(stopped.status).toBe("cancelled"); + expect(await readPersistedNativeToolReceiptLimitStop(db, stopped, finalTurnId)).toBe(true); + expect(await readPersistedNativeToolReceiptLimitStop(db, stopped, "another-turn")).toBe(false); + + const [retry, ...others] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId))); + expect(others).toHaveLength(0); + expect(retry).toMatchObject({ status: "scheduled_retry", scheduledRetryReason: NATIVE_TOOL_RECEIPT_LIMIT_CODE, scheduledRetryAttempt: 1, + contextSnapshot: { issueId, forceFreshSession: true, livenessContinuationSourceRunId: runId, + livenessContinuationReason: NATIVE_TOOL_RECEIPT_LIMIT_CODE, livenessContinuationInstruction: NATIVE_TOOL_RECEIPT_LIMIT_HINT } }); + expect(retry!.contextSnapshot).not.toHaveProperty("wakeCommentId"); + expect(retry!.scheduledRetryAt!.getTime() - Date.now()).toBeLessThanOrEqual(NATIVE_TOOL_RECEIPT_LIMIT_CONTINUATION_DELAY_MS); + const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId)); + expect(decision).toMatchObject({ reasonCode: NATIVE_TOOL_RECEIPT_LIMIT_CODE }); + expect(await db.select().from(statusDecisionEffects).where(eq(statusDecisionEffects.decisionId, decision!.id))) + .toEqual(expect.arrayContaining([expect.objectContaining({ effectKind: "schedule_retry", targetType: "heartbeat_run", targetId: retry!.id })])); + + expect((await release()({ companyId, runId, now: new Date() })).outcome.kind).toBe("released"); + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId))).toHaveLength(0); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(issue).toMatchObject({ status: "in_progress", assigneeAgentId: agentId }); + expect(await taskInterruptionPresentation(db, issue!)).toMatchObject({ state: "retry_scheduled", canRetry: false, userAction: null }); + const scheduler = heartbeatService(db, { runtimeEnv: {} }); + expect(await scheduler.promoteDueScheduledRetries(new Date())).toMatchObject({ promoted: 0 }); + expect(await scheduler.promoteDueScheduledRetries(retry!.scheduledRetryAt!)).toMatchObject({ promoted: 1, runIds: [retry!.id] }); + expect(await taskInterruptionPresentation(db, issue!)).toMatchObject({ state: "working", canRetry: false, userAction: null }); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.runId, retry!.id))).toHaveLength(1); + await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, retry!.id)); + }); + + it("does not continue a turn a person stopped while it settled", async () => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Stopped task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "receipt-owner" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "receipt-owner", contextSnapshot: { issueId } }); + await stopAtReceiptLimit(runId, issueId, NATIVE_TOOL_RECEIPT_LIMIT_CODE, () => db.update(heartbeatRuns) + .set({ resultJson: { cancelledByActorType: "user", cancelledByUserId: "receipt-owner" } }).where(eq(heartbeatRuns.id, runId))); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0); + const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId)); + expect(decision?.reasonCode).not.toBe(NATIVE_TOOL_RECEIPT_LIMIT_CODE); + }); + + it("settles the cancellation when a person stops the run after finalization first read it", async () => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Late stop task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "receipt-owner" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "receipt-owner", contextSnapshot: { issueId } }); + await stopAtReceiptLimit(runId, issueId, NATIVE_TOOL_RECEIPT_LIMIT_CODE, async () => { + receiptLimitRead.after = () => db.update(heartbeatRuns) + .set({ resultJson: { cancelledByActorType: "user", cancelledByUserId: "receipt-owner" } }).where(eq(heartbeatRuns.id, runId)); + }); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)); + expect(coordinator).toMatchObject({ phase: "committed", failureCode: null }); + const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId)); + expect(decision).toMatchObject({ reasonCode: "cancellation_run_only" }); + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId))).toHaveLength(0); + }); + + it("does not continue when only an earlier turn hit the receipt limit", async () => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Earlier turn task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "receipt-owner" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "receipt-owner", contextSnapshot: { issueId } }); + const stopped = await stopAtReceiptLimit(runId, issueId, NATIVE_TOOL_RECEIPT_LIMIT_CODE, undefined, "earlier-provider-turn"); + expect(await readPersistedNativeToolReceiptLimitStop(db, stopped, finalTurnId)).toBe(false); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0); + const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId)); + expect(decision).toMatchObject({ reasonCode: "cancellation_run_only" }); + }); + + it("refuses to create the continuation under the run lock once a person's Stop is saved", async () => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Locked stop task", status: "in_progress", assigneeAgentId: agentId }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "cancelled", runtimeMode: "native", nativeIssueId: issueId, + contextSnapshot: { issueId }, resultJson: { cancelledByActorType: "user", cancelledByUserId: "receipt-owner" } }); + await expect(db.transaction(tx => materializeNativeToolReceiptLimitContinuation({ tx: tx as never, companyId, issueId, runId, agentId }))) + .rejects.toBeInstanceOf(NativeStatusRaceError); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, `native-tool-receipt-limit:${companyId}:${runId}`))).toHaveLength(0); + }); + + it("leaves another cancelled turn to its existing recovery", async () => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Other diagnostic task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "receipt-owner" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "receipt-owner", contextSnapshot: { issueId } }); + const stopped = await stopAtReceiptLimit(runId, issueId, "semantic_tool_denied"); + expect(await readPersistedNativeToolReceiptLimitStop(db, stopped, finalTurnId)).toBe(false); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0); + const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId)); + expect(decision).toMatchObject({ reasonCode: "cancellation_run_only" }); + }); +}); diff --git a/server/src/services/native-runtime/native-tool-receipt-limit.ts b/server/src/services/native-runtime/native-tool-receipt-limit.ts new file mode 100644 index 00000000000..a4228c169c2 --- /dev/null +++ b/server/src/services/native-runtime/native-tool-receipt-limit.ts @@ -0,0 +1,60 @@ +import { and, eq, inArray, isNull, sql } from "drizzle-orm"; +import { agentWakeupRequests, heartbeatRunEvents, type heartbeatRuns, type Db } from "@paperclipai/db"; +import { validatePrpEvent } from "../../vendor/paperclip-runner/index.js"; +import { nativeSha256 } from "./canonical.js"; +import { readRunCancellation } from "../run-cancellation.js"; + +export const NATIVE_TOOL_RECEIPT_LIMIT_CODE = "semantic_tool_turn_receipt_limit"; +export const NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS = 2; +export const NATIVE_TOOL_RECEIPT_LIMIT_CONTINUATION_DELAY_MS = 5_000; +export const NATIVE_TOOL_RECEIPT_LIMIT_MESSAGE = "The agent's turn held too many tool results at once. Paperclip continues the task in a fresh session."; +export const NATIVE_TOOL_RECEIPT_LIMIT_HINT = "The previous turn stopped because it held too many tool results at once. " + + "Continue the task from its saved work. Make fewer tool calls in parallel, and do not re-read data you already have."; + +export function nativeRunHasStopRequest(resultJson: Record | null | undefined): boolean { + if (!resultJson) return false; + const cancellation = readRunCancellation(resultJson); + return Boolean(resultJson.nativeCancellation || resultJson.executionCancellation || resultJson.cancelledByActorType + || resultJson.cancelledByUserId || resultJson.interruptedByActorType || resultJson.queuedCommentInterruptQueueId + || resultJson.issueMutationStopId || resultJson.operatorInterrupted === true + || (cancellation && cancellation.initiator.type !== "system" && cancellation.initiator.type !== "provider")); +} + +export async function cancelStoppedRunContinuation( + db: Pick, + run: Pick, + idempotencyKey: string, +): Promise { + if (!nativeRunHasStopRequest(run.resultJson)) return 0; + const now = new Date(); + const cancelled = await db.update(agentWakeupRequests).set({ + status: "cancelled", finishedAt: now, updatedAt: now, error: "The run that asked for this continuation was stopped", + }).where(and( + eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.idempotencyKey, idempotencyKey), + inArray(agentWakeupRequests.status, ["queued", "claimed", "deferred_issue_execution"]), isNull(agentWakeupRequests.runId), + )).returning({ id: agentWakeupRequests.id }); + return cancelled.length; +} + +export async function readPersistedNativeToolReceiptLimitStop( + db: Pick, + run: Pick, + turnId: string | null, +): Promise { + if (run.runtimeMode !== "native" || !run.runnerInstanceId || !run.nativeSessionId || !turnId) return false; + const rows = await db.select().from(heartbeatRunEvents).where(and( + eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id), + eq(heartbeatRunEvents.sourceInstanceId, run.runnerInstanceId), eq(heartbeatRunEvents.eventType, "harness.diagnostic"), + sql`${heartbeatRunEvents.payload}->'prpEvent'->'payload'->>'code' = ${NATIVE_TOOL_RECEIPT_LIMIT_CODE}`, + sql`${heartbeatRunEvents.payload}->'prpEvent'->>'turnId' = ${turnId}`, + )).limit(4); + return rows.some(row => { + const prpEvent = (row.payload as Record | null)?.prpEvent; + const parsed = validatePrpEvent(prpEvent); + return parsed.ok && parsed.event.runId === run.id && parsed.event.sourceKind === "runner" + && parsed.event.turnId === turnId && parsed.event.normalizedSessionId === run.nativeSessionId + && parsed.event.sourceInstanceId === run.runnerInstanceId && parsed.event.eventType === row.eventType + && parsed.event.sourceEventId === row.sourceEventId && parsed.event.sourceSeq === row.sourceSeq + && row.sourcePayloadSha256 === nativeSha256(parsed.event); + }); +} diff --git a/server/src/services/native-runtime/paperclip-control-plane-port.test.ts b/server/src/services/native-runtime/paperclip-control-plane-port.test.ts index 2975c229823..406070043ad 100644 --- a/server/src/services/native-runtime/paperclip-control-plane-port.test.ts +++ b/server/src/services/native-runtime/paperclip-control-plane-port.test.ts @@ -3,7 +3,7 @@ import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external import { plugins } from "@paperclipai/db"; import { readTaskPanelActivations } from "../plugin-task-panels.js"; import { startServerMetrics, stopServerMetrics } from "../server-metrics.js"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { and, asc, eq, sql } from "drizzle-orm"; import { createHash, generateKeyPairSync, randomUUID } from "node:crypto"; import { mkdtemp, rm } from "node:fs/promises"; @@ -1096,6 +1096,31 @@ describe("PaperclipControlPlanePort conformance", () => { await expect(f.port.appendEvent(f.event(12), f.streamed)).resolves.toMatchObject({ cursor: 12 }); }); + it("commits progress events that arrive while a batch commits in the next single batch", async () => { + let release!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const f = await streamingFixture({ streamingBatchMs: 600_000, onCommittedEvent: async (event) => { + if (event.sourceSeq === 1) await gate; + } }); + const first = f.port.appendEvent(f.event(1, "tool.execution.progressed"), f.streamed); + await vi.waitFor(async () => expect(await f.stored()).toHaveLength(1)); + const options = db.$client.options as { debug?: unknown }; + const statements: string[] = []; + options.debug = (_connection: number, text: string) => { statements.push(text.trim().replace(/\s+/g, " ")); }; + try { + const later = [2, 3, 4].map(sourceSeq => f.port.appendEvent(f.event(sourceSeq, "tool.execution.progressed"), f.streamed)); + await new Promise(resolve => setTimeout(resolve, 50)); + expect(statements.filter(text => /^begin/i.test(text))).toHaveLength(0); + release(); + await expect(first).resolves.toMatchObject({ cursor: 1, disposition: "committed" }); + expect((await Promise.all(later)).map(receipt => receipt.cursor)).toEqual([2, 3, 4]); + expect(statements.filter(text => /^begin/i.test(text))).toHaveLength(1); + } finally { options.debug = undefined; } + const boundary = await f.port.appendEvent(f.event(5, "tool.execution.started")); + expect(boundary).toMatchObject({ cursor: 5, disposition: "committed" }); + expect(await f.stored()).toEqual([1, 2, 3, 4, 5].map(seq => ({ seq, sourceSeq: seq }))); + }); + it("observes every committed delta of a batch when one observer fails", async () => { const observed: number[] = []; const f = await streamingFixture({ streamingBatchMs: 600_000, onCommittedEvent: async (event) => { diff --git a/server/src/services/native-runtime/paperclip-control-plane-port.ts b/server/src/services/native-runtime/paperclip-control-plane-port.ts index 7afee85af21..578b82bd420 100644 --- a/server/src/services/native-runtime/paperclip-control-plane-port.ts +++ b/server/src/services/native-runtime/paperclip-control-plane-port.ts @@ -125,6 +125,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort { * a delta's receipt settles; the receipt settles after its batch commits. */ readonly pipelinesStreamingEvents = true; + readonly pipelinedEventTypes: ReadonlySet = new Set(["item.delta", "tool.execution.progressed"]); readonly #streamingBatchMs: number; #streamingBatch: PendingStreamingEvent[] = []; #streamingTimer: ReturnType | null = null; @@ -133,7 +134,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort { /** Deltas queued or committing. Other operations wait only when some are; otherwise they start at once. */ #streamingEventsPending = 0; /** - * False until a delta with text commits after the latest other event. Until + * False until a delta with text is appended after the latest other event. Until * then each delta commits at once, so the first text of an item, and the * time to first token, never wait for the batch timer. */ @@ -467,7 +468,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort { }, assertWritable: () => this.#assertActive(options), }; - if (event.eventType === "item.delta" && !options?.deferPostCommitObservers) { + if (this.pipelinedEventTypes.has(event.eventType) && !options?.deferPostCommitObservers) { return this.#appendStreamingEvent({ event, input, options, startedAtMs: persistenceStartedAt, startedClock: persistenceClock }, options?.streaming === true); } @@ -547,7 +548,12 @@ export class PaperclipControlPlanePort implements ControlPlanePort { return new Promise((resolve, reject) => { this.#streamingBatch.push({ ...pending, resolve, reject }); this.#streamingEventsPending += 1; - if (!streaming || !this.#streamedSinceBoundary || this.#streamingBatch.length >= STREAMING_EVENT_BATCH_MAX) { + if (pending.event.eventType !== "item.delta") this.#streamedSinceBoundary = false; + const flushNow = !streaming || !this.#streamedSinceBoundary || this.#streamingBatch.length >= STREAMING_EVENT_BATCH_MAX; + if (typeof pending.event.payload.text === "string" && pending.event.payload.text.length > 0) { + this.#streamedSinceBoundary = true; + } + if (flushNow) { void this.#flushStreamingEvents(); } else { this.#streamingTimer ??= setTimeout(() => { void this.#flushStreamingEvents(); }, this.#streamingBatchMs); @@ -569,9 +575,6 @@ export class PaperclipControlPlanePort implements ControlPlanePort { this.#streamingFlushQueued = false; const batch = this.#streamingBatch; this.#streamingBatch = []; - if (batch.some(pending => typeof pending.event.payload.text === "string" && pending.event.payload.text.length > 0)) { - this.#streamedSinceBoundary = true; - } try { await this.#commitStreamingEvents(batch); } finally { this.#streamingEventsPending -= batch.length; } }); diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts index c1f69eb2620..4fbc48db02d 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts @@ -32,6 +32,7 @@ import { documentService } from "../documents.js"; import { issueService } from "../issues.js"; import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js"; import { TOOL_CALL_LOOP_HINT, ToolCallLoopError } from "./repeated-tool-failure-guard.js"; +import { cancelStoppedRunContinuation } from "./native-tool-receipt-limit.js"; import { PaperclipRunnerSemanticAuthority } from "./runner-semantic-authority.js"; import { createAssignedMcpTools } from "./assigned-mcp-tools.js"; import type { ToolGatewayService } from "../tool-gateway.js"; @@ -1638,6 +1639,53 @@ describe("PaperclipRunnerToolAuthority", () => { await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key)); }); + it("queues no tool-call loop continuation for a run a person stopped, and cancels one queued before the Stop", async () => { + const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId, workMode: "standard" }); + const key = `agent_tool_call_loop:${runId}`; + const loop = new ToolCallLoopError("call_api", 6, 6, ["operationId"], 400, "refused"); + await expect(authority.scheduleToolCallLoopContinuation(loop)).resolves.toBe(true); + const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + const stopped = { ...before!, resultJson: { ...before!.resultJson, cancelledByActorType: "user", cancelledByUserId: "board-user" } }; + await db.update(heartbeatRuns).set({ resultJson: stopped.resultJson }).where(eq(heartbeatRuns.id, runId)); + try { + await expect(cancelStoppedRunContinuation(db, stopped, key)).resolves.toBe(1); + expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key))) + .map(row => row.status)).toEqual(["cancelled"]); + await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key)); + await expect(authority.scheduleToolCallLoopContinuation(loop)).resolves.toBe(false); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key))).toHaveLength(0); + } finally { + await db.update(heartbeatRuns).set({ resultJson: before!.resultJson }).where(eq(heartbeatRuns.id, runId)); + await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key)); + } + }); + + it("orders the loop continuation's locks task first, like Stop, so a concurrent Stop wins without a deadlock", async () => { + const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId, workMode: "standard" }); + const key = `agent_tool_call_loop:${runId}`; + const loop = new ToolCallLoopError("call_api", 6, 6, ["operationId"], 400, "refused"); + const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + let holdingTask!: () => void; + const taskLocked = new Promise(resolve => { holdingTask = resolve; }); + try { + const stop = db.transaction(async tx => { + await tx.select({ id: issues.id }).from(issues).where(eq(issues.id, issueId)).for("update"); + holdingTask(); + await new Promise(resolve => setTimeout(resolve, 300)); + await tx.update(heartbeatRuns).set({ resultJson: { ...before!.resultJson, cancelledByActorType: "user", cancelledByUserId: "board-user" } }) + .where(eq(heartbeatRuns.id, runId)); + }); + await taskLocked; + const scheduled = authority.scheduleToolCallLoopContinuation(loop); + await expect(stop).resolves.toBeUndefined(); + await expect(scheduled).resolves.toBe(false); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key))).toHaveLength(0); + } finally { + await db.update(heartbeatRuns).set({ resultJson: before!.resultJson }).where(eq(heartbeatRuns.id, runId)); + await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key)); + } + }); + it("creates ordinary children, preserves blockers, and deduplicates across runs", async () => { const wakes: Array<{ agentId: string; options: Record }> = []; diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index 77406c5b089..4df41025bf0 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -80,6 +80,7 @@ import { finishPendingRunnerApiCaptureDeletes, markRunnerApiCaptureEvictions, RU import { acquireRunnerApiResponseSlot, RUNNER_API_RESPONSE_DEADLINE_MS, RunnerApiCaptureReservationReclaimedError, runnerApiCompanyCaptureMaxBytes, RUNNER_API_RESPONSE_MAX_BYTES, RUNNER_API_RESPONSE_RUN_MAX_BYTES, RunnerApiResponseLimitError } from "./runner-api-response-limits.js"; import { and, desc, eq, inArray, isNull, notInArray, sql } from "drizzle-orm"; import { AGENT_TOOL_CALL_LOOP, TOOL_CALL_LOOP_HINT, toolCallLoopContinuationKey, type ToolCallLoopError } from "./repeated-tool-failure-guard.js"; +import { nativeRunHasStopRequest } from "./native-tool-receipt-limit.js"; import { enqueueWake } from "./status-decision-committer.js"; import type { Db } from "@paperclipai/db"; import { @@ -357,7 +358,13 @@ export class PaperclipRunnerToolAuthority { const review = this.binding.nativeReview; const loopContext = { sourceRunId: this.binding.runId, continuationCause: AGENT_TOOL_CALL_LOOP, tool: loop.tool, refusals: loop.refusals, runRefusals: loop.runRefusals, argumentNames: loop.argumentNames }; - await this.db.transaction(tx => enqueueWake({ + return this.db.transaction(async tx => { + await tx.select({ id: issues.id }).from(issues).where(and( + eq(issues.id, this.binding.issueId), eq(issues.companyId, this.binding.companyId))).for("update"); + const [run] = await tx.select({ resultJson: heartbeatRuns.resultJson }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.id, this.binding.runId), eq(heartbeatRuns.companyId, this.binding.companyId))).for("share"); + if (!run || nativeRunHasStopRequest(run.resultJson)) return false; + await enqueueWake({ tx: tx as unknown as Db, originRunId: this.binding.runId, companyId: this.binding.companyId, @@ -368,8 +375,9 @@ export class PaperclipRunnerToolAuthority { payload: { ...(review ?? {}), ...loopContext }, contextSnapshot: { ...(review ?? {}), forceFreshSession: true, livenessContinuationSourceRunId: this.binding.runId, livenessContinuationReason: AGENT_TOOL_CALL_LOOP, livenessContinuationInstruction: TOOL_CALL_LOOP_HINT }, - })); - return true; + }); + return true; + }); } constructor(readonly db: Db, readonly binding: Binding) {} diff --git a/server/src/services/native-runtime/status-arbiter.test.ts b/server/src/services/native-runtime/status-arbiter.test.ts index 579ddd39eaf..2a90adef678 100644 --- a/server/src/services/native-runtime/status-arbiter.test.ts +++ b/server/src/services/native-runtime/status-arbiter.test.ts @@ -157,6 +157,20 @@ describe("native status authority", () => { expect(decision.effects).toEqual([{ kind: "release_checkout" }]); }); + it("continues a turn stopped at its tool receipt limit in a fresh session, within its bound", () => { + const stopped = arbitrate({ terminalState: "cancelled", toolReceiptLimitStopped: true }); + expect(stopped).toMatchObject({ statusAction: "preserve", toStatus: "in_progress", reasonCode: "semantic_tool_turn_receipt_limit" }); + expect(stopped.effects).toEqual([ + { kind: "schedule_retry", cause: "semantic_tool_turn_receipt_limit", summary: "Continue the task in a fresh session.", agentId: expect.any(String) }, + { kind: "release_run_resources" }, + ]); + expect(arbitrate({ terminalState: "failed", toolReceiptLimitStopped: true }).effects) + .toEqual([expect.objectContaining({ kind: "schedule_retry", cause: "semantic_tool_turn_receipt_limit" })]); + expect(arbitrate({ terminalState: "cancelled", toolReceiptLimitStopped: true, failureRetryCount: 2 }).reasonCode).toBe("cancellation_run_only"); + expect(arbitrate({ terminalState: "cancelled", toolReceiptLimitStopped: true, priorIssueStatus: "blocked" }).reasonCode).toBe("cancellation_run_only"); + expect(arbitrate({ terminalState: "cancelled" }).reasonCode).toBe("cancellation_run_only"); + }); + it("treats only the authorized Board response_wake as passive and preserves governance", () => { const passive = assessment({ reportedDisposition: "yielded", diff --git a/server/src/services/native-runtime/status-arbiter.ts b/server/src/services/native-runtime/status-arbiter.ts index 26e3643e5e2..594f3011fef 100644 --- a/server/src/services/native-runtime/status-arbiter.ts +++ b/server/src/services/native-runtime/status-arbiter.ts @@ -1,6 +1,7 @@ import { COMPLETION_REVIEW_STAGE_REASON, COMPLETION_REVIEW_STAGE_REJECTED_REASON, type CompletionReviewStageEntry } from "../issue-execution-policy.js"; import type { NativeEvidenceAssessment } from "./evidence-classifier.js"; import { NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, NATIVE_PROVIDER_OVERLOADED_CODE, NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js"; +import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS } from "./native-tool-receipt-limit.js"; export const NATIVE_STATUS_ARBITER_POLICY_VERSION = "phase6-v14"; @@ -256,6 +257,7 @@ export function arbitrateNativeStatus(input: { providerModelRejected?: boolean; providerOverloaded?: boolean; providerFailureSuperseded?: boolean; + toolReceiptLimitStopped?: boolean; failureRetryCount?: number; /** * This run was itself the automatic continuation of an earlier failed turn. @@ -368,6 +370,20 @@ export function arbitrateNativeStatus(input: { ], }; } + if (input.toolReceiptLimitStopped && input.terminalState !== "succeeded" && !input.nativeReviewOutcome && + !input.governanceGate && !input.hasUnresolvedIssueBlockers && !input.hasActivePauseHold && + input.priorIssueStatus !== "blocked" && + (input.failureRetryCount ?? 0) < NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS) { + return { + policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, + statusAction: "preserve", toStatus: input.priorIssueStatus, + reasonCode: NATIVE_TOOL_RECEIPT_LIMIT_CODE, unblockDescriptor: null, + effects: [ + { kind: "schedule_retry", cause: NATIVE_TOOL_RECEIPT_LIMIT_CODE, summary: "Continue the task in a fresh session.", agentId: input.agentId }, + ...(input.terminalState === "cancelled" ? [{ kind: "release_run_resources" as const }] : []), + ], + }; + } if (input.nativeReviewOutcome) { return { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, diff --git a/server/src/services/native-runtime/status-decision-committer.ts b/server/src/services/native-runtime/status-decision-committer.ts index 80da7787b0e..d64421cecc5 100644 --- a/server/src/services/native-runtime/status-decision-committer.ts +++ b/server/src/services/native-runtime/status-decision-committer.ts @@ -87,8 +87,9 @@ import { type ActivityPublication, } from "../activity-log.js"; import { emitAgentTaskRun } from "../agent-task-run-telemetry.js"; -import { materializeNativeProviderCapacityRetry } from "./native-provider-capacity-retry.js"; +import { materializeNativeProviderCapacityRetry, materializeNativeToolReceiptLimitContinuation } from "./native-provider-capacity-retry.js"; import { NATIVE_PROVIDER_OVERLOADED_CODE } from "./native-provider-failure.js"; +import { NATIVE_TOOL_RECEIPT_LIMIT_CODE } from "./native-tool-receipt-limit.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js"; export class NativeStatusRaceError extends Error { @@ -824,6 +825,19 @@ async function materializeDecisionEffect(input: { summary: effect.summary, }, }; + const [stopped] = effect.idempotencyKey === toolCallLoopContinuationKey(input.runId) + ? await input.tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.agentId, effect.agentId), + eq(agentWakeupRequests.idempotencyKey, effect.idempotencyKey), eq(agentWakeupRequests.status, "cancelled"), + )).limit(1) + : []; + if (stopped) + return { + effectKind: effect.kind, + targetType: "agent_wakeup_request", + targetId: stopped.id, + payload: { continuationKind: effect.continuationKind, summary: effect.summary, cancelled: true }, + }; } if (effect.continuationKind === "monitor") throw new Error("Monitor delivery belongs to the issue monitor scheduler"); const wakeId = await enqueueWake({ @@ -895,8 +909,10 @@ async function materializeDecisionEffect(input: { } if (effect.kind === "schedule_retry") { failAt("continuation_materialization", input.failpoint); - if (effect.cause === NATIVE_PROVIDER_OVERLOADED_CODE) { - const retryId = await materializeNativeProviderCapacityRetry({ + if (effect.cause === NATIVE_PROVIDER_OVERLOADED_CODE || effect.cause === NATIVE_TOOL_RECEIPT_LIMIT_CODE) { + const materialize = effect.cause === NATIVE_PROVIDER_OVERLOADED_CODE + ? materializeNativeProviderCapacityRetry : materializeNativeToolReceiptLimitContinuation; + const retryId = await materialize({ tx: input.tx as unknown as Db, companyId: input.companyId, issueId: input.issue.id, runId: input.runId, agentId: effect.agentId, }); @@ -1699,8 +1715,8 @@ export async function commitNativeStatusDecision(input: { if (reasonCode === "native_provider_model_rejected" && !input.requireModelRejectionOwner) { throw new Error("native_model_rejection_owner_required"); } - if ((reasonCode.startsWith("native_provider_overloaded") || reasonCode === "native_run_failed_continuation_exhausted") - && !input.requireProviderFailureOwner) { + if ((reasonCode.startsWith("native_provider_overloaded") || reasonCode === "native_run_failed_continuation_exhausted" + || reasonCode === NATIVE_TOOL_RECEIPT_LIMIT_CODE) && !input.requireProviderFailureOwner) { throw new Error("native_provider_failure_owner_required"); } const publications: ActivityPublication[] = []; diff --git a/server/src/services/run-cancellation.ts b/server/src/services/run-cancellation.ts index 9ebe8e4032b..00ae73b242b 100644 --- a/server/src/services/run-cancellation.ts +++ b/server/src/services/run-cancellation.ts @@ -1,4 +1,5 @@ import type { heartbeatRuns } from "@paperclipai/db"; +import { sql, type SQLWrapper } from "drizzle-orm"; type Run = Pick; const SOURCES = ["operator", "queued_message", "shutdown", "provider", "transport", "control_plane", "controller_lease", "unknown"] as const; @@ -145,6 +146,29 @@ export function recordedUserStop(run: Pick) { ["operator", "queued_message"].includes(cancellation.source) ? cancellation : null; } +/** Presentation of a settled operator Stop; this does not grant replay authority. */ +export function isAcknowledgedLegacyUserStop(run: Pick & Partial>): boolean { + const cancellation = recordedUserStop(run); + const receipt = run.resultJson?.executionCancellation as Record | undefined; + return run.status === "cancelled" && run.runtimeMode === "legacy" && Boolean(run.finishedAt) + && cancellation?.source === "operator" && cancellation.expected + && receipt?.state === "acknowledged" && receipt.proof === "preparation_settled"; +} + +/** The same bounded Stop evidence for both task-page projections. */ +export function runStopPresentationJson(result: SQLWrapper) { + return sql>`jsonb_build_object( + 'cancellation', jsonb_build_object( + 'source', left(${result}->'cancellation'->>'source', 32), + 'expected', ${result}->'cancellation'->'expected', + 'initiator', jsonb_build_object('type', left(${result}->'cancellation'->'initiator'->>'type', 32)), + 'reason', left(${result}->'cancellation'->>'reason', 512), + 'recordedAt', left(${result}->'cancellation'->>'recordedAt', 64)), + 'executionCancellation', jsonb_build_object( + 'state', left(${result}->'executionCancellation'->>'state', 32), + 'proof', left(${result}->'executionCancellation'->>'proof', 64)))`; +} + /** When a user's Stop or interrupt took effect for message ordering. A native * run finishes only after its provider stop and workspace save settle, which * can take many seconds. A message written after the Stop request is a new diff --git a/server/src/services/task-interruption-presentation.test.ts b/server/src/services/task-interruption-presentation.test.ts index 4a8bd737803..579cc7c9ae4 100644 --- a/server/src/services/task-interruption-presentation.test.ts +++ b/server/src/services/task-interruption-presentation.test.ts @@ -308,6 +308,21 @@ describe("intentional native Stop presentation", () => { }); }); +describe("intentional legacy Stop presentation", () => { + it("clears the failed-attempt notice only after the requested Stop is acknowledged", () => { + const stopped = { ...run, runtimeMode: "legacy" as const, status: "cancelled", finishedAt: new Date(), resultJson: { + cancellation: { source: "operator", expected: true, initiator: { type: "user" }, reason: "Stop", recordedAt: new Date().toISOString() }, + executionCancellation: { state: "acknowledged", proof: "preparation_settled" }, + } }; + const input = { run: stopped, agent, paused: false, approval: false }; + expect(projectTaskInterruption(issue, input)).toMatchObject({ state: "resolved", canRetry: false }); + expect(projectTaskInterruption(issue, { ...input, run: { ...stopped, resultJson: { ...stopped.resultJson, + executionCancellation: { state: "requested" } } } })).toMatchObject({ state: "failed", canRetry: true }); + expect(projectTaskInterruption(issue, { ...input, paused: true })).toMatchObject({ userAction: "resume" }); + expect(projectTaskInterruption(issue, { ...input, approval: true })).toMatchObject({ userAction: "approval" }); + }); +}); + it("preserves a provider explanation on a failed task without changing retry authority", () => { const providerFailure = { schema: "paperclip.provider-failure.v1", provider: "anthropic", phase: "startup", category: "rate_limit", message: "API error: 429 This request would exceed your account's rate limit.", diff --git a/server/src/services/task-interruption-presentation.ts b/server/src/services/task-interruption-presentation.ts index 87b18917f83..052174fadae 100644 --- a/server/src/services/task-interruption-presentation.ts +++ b/server/src/services/task-interruption-presentation.ts @@ -22,7 +22,7 @@ import { logger } from "../middleware/logger.js"; import { canonicalExecutionUuid } from "./execution-identity.js"; import { chatActionDeadline } from "./chat-action-work.js"; import { NATIVE_CLEANUP_SETTLING_MESSAGE, NATIVE_SESSION_CLEANUP_QUARANTINED } from "./native-runtime/completed-turn-cleanup.js"; -import { isQueuedDependencyWait } from "./run-cancellation.js"; +import { isAcknowledgedLegacyUserStop, isQueuedDependencyWait, runStopPresentationJson } from "./run-cancellation.js"; import { heldRetryOffersRetry } from "./task-retry-eligibility.js"; import { exhaustedNativeFinalizationCondition, savedResultRetryPendingCondition } from "./native-runtime/exhausted-finalization-retry.js"; import { AI_CONNECTION_BUSY_RETRY_REASON, AI_CONNECTION_POOL_WAIT_RETRY_REASON, RUNNER_REVISION_WAIT_RETRY_REASON, @@ -278,6 +278,7 @@ function projectTaskInterruptionState(issue: ProjectionIssue, input: ProjectionS // The task's existing dependency UI owns this wait. Keep actual recovery and // Retry preparation failures authoritative; this does not change admission. if (!action && !retryWait?.preparationStatus && isQueuedDependencyWait(run)) return base; + if (!wait && !action && isAcknowledgedLegacyUserStop(run)) return base; // Intentional Stop is not an unsuccessful attempt. This is presentation only; // physical containment and pending cleanup keep their execution-side gates. if (!wait && run.runtimeMode === "native" && run.companyId === issue.companyId && run.nativeIssueId === issue.id @@ -510,7 +511,7 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i setupFailureRunId: sql`case when ${heartbeatRuns.resultJson}->'setupCommandFailure' is null and ${heartbeatRuns.status} = 'scheduled_retry' and ${heartbeatRuns.retryOfRunId} is not null then ${heartbeatRuns.retryOfRunId} else ${heartbeatRuns.id} end`, - resultJson: sql>`jsonb_build_object('configurationIncomplete', ${heartbeatRuns.resultJson}->'configurationIncomplete', + resultJson: sql>`${runStopPresentationJson(heartbeatRuns.resultJson)} || jsonb_build_object('configurationIncomplete', ${heartbeatRuns.resultJson}->'configurationIncomplete', 'stopReason', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'stopReason'`, 80)}, 'timeoutSource', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'timeoutSource'`, 80)}, 'timeoutFired', coalesce(${heartbeatRuns.resultJson}->'timeoutFired' = 'true'::jsonb, false), @@ -535,7 +536,7 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i 'setupCommandFailure', coalesce(${heartbeatRuns.resultJson}->'setupCommandFailure', case when ${heartbeatRuns.status} = 'scheduled_retry' then (select predecessor.result_json->'setupCommandFailure' from ${heartbeatRuns} predecessor where predecessor.company_id = ${heartbeatRuns.companyId} and predecessor.id = ${heartbeatRuns.retryOfRunId} - and predecessor.error_code = 'setup_failed') end))`, + and predecessor.error_code = 'setup_failed') end))`.as("result_json"), }).from(requested).innerJoinLateral(latestRuns, sql`true`).innerJoin(heartbeatRuns, and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, latestRuns.id))) .leftJoin(agents, and(eq(agents.companyId, heartbeatRuns.companyId), eq(agents.id, heartbeatRuns.agentId))) .orderBy(requestedIssueId), diff --git a/tests/runner-e2e/report-lock.json b/tests/runner-e2e/report-lock.json index 33962ba7299..cda5ff85976 100644 --- a/tests/runner-e2e/report-lock.json +++ b/tests/runner-e2e/report-lock.json @@ -1,6 +1,6 @@ { - "inputSha256": "a56b6acc8743f6163d4af60b072d66c694c1061f4242f499c361d85fce318f3a", - "outputSha256": "a09e9ae44a5f4244431837b158607621b6fa276148bec3078aae2d2e5f2443f9", - "patchSha256": "325e0a90b5cb215a361ab3c3d59935161367b09b59f361080fa292a96566c95a", + "inputSha256": "a09e9ae44a5f4244431837b158607621b6fa276148bec3078aae2d2e5f2443f9", + "outputSha256": "163e7562adefa9924ee96d8b8aa45fa45e7ebe16297315c5b51040803773b9e1", + "patchSha256": "704ba0b17db951602e8aad0eabd73d2be4d788442ffbcb8fc3fd862ac64e23ac", "basis": "Generated with the trusted master lockfile refresh. Review this offline correction and its hashes with the dependency changes." } diff --git a/tests/runner-e2e/report-lock.patch b/tests/runner-e2e/report-lock.patch index 98e9fc14c63..14c35b26200 100644 --- a/tests/runner-e2e/report-lock.patch +++ b/tests/runner-e2e/report-lock.patch @@ -1,143 +1,49 @@ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml -index 48c18aed..05644099 100644 +index 05644099..c533906b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml -@@ -46,7 +46,7 @@ patchedDependencies: - hash: 55uhvnotpqyiy37rn3pqpukhei - path: patches/embedded-postgres@18.1.0-beta.16.patch - postgres@3.4.9: -- hash: eq2va53hqrnbmnygljtudtaoge -+ hash: 7s673zkrux4f7d7y4kyzk7opyu - path: patches/postgres@3.4.9.patch +@@ -16,7 +16,7 @@ overrides: - importers: -@@ -139,7 +139,7 @@ importers: - version: 17.4.2 - drizzle-orm: - specifier: 0.45.2 -- version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) -+ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) - embedded-postgres: - specifier: ^18.1.0-beta.16 - version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) -@@ -411,13 +411,13 @@ importers: - version: link:../shared - drizzle-orm: - specifier: ^0.45.2 -- version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) -+ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) - embedded-postgres: - specifier: ^18.1.0-beta.16 - version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) - postgres: - specifier: ^3.4.9 -- version: 3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge) -+ version: 3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu) - devDependencies: - '@types/node': - specifier: ^24.0.0 -@@ -1018,7 +1018,7 @@ importers: - version: 2.2.0(@grpc/grpc-js@1.14.5)(nice-grpc-common@2.0.4)(nice-grpc@2.1.17) - '@vercel/connect': - specifier: 2.3.3 -- version: 2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))) -+ version: 2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))) - acorn: - specifier: 8.18.0 - version: 8.18.0 -@@ -1036,7 +1036,7 @@ importers: - version: 3.0.1(ajv@8.20.0) - better-auth: - specifier: 1.7.16 -- version: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) -+ version: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) - chat: - specifier: 4.39.0 - version: 4.39.0(ai@7.0.130(zod@4.6.7))(zod@4.6.7) -@@ -1057,7 +1057,7 @@ importers: - version: 17.4.2 - drizzle-orm: - specifier: ^0.45.2 -- version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) -+ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) - embedded-postgres: - specifier: ^18.1.0-beta.16 - version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) -@@ -10089,12 +10089,12 @@ snapshots: - optionalDependencies: - '@opentelemetry/api': 1.9.1 - -- '@better-auth/drizzle-adapter@1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))': -+ '@better-auth/drizzle-adapter@1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))': + patchedDependencies: + '@agentclientprotocol/claude-agent-acp@0.73.0': +- hash: syoits7l7g3sthy3olttp2fv24 ++ hash: wnht4big7mwol7j2skbsa5mefq + path: patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch + '@agentclientprotocol/codex-acp@1.6.2': + hash: 2iynuypg76nxmydiylgtffhr7e +@@ -186,7 +186,7 @@ importers: dependencies: - '@better-auth/core': 1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3) - '@better-auth/utils': 0.5.1 - optionalDependencies: -- drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) -+ drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) - - '@better-auth/kysely-adapter@1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(kysely@0.29.5)': + '@agentclientprotocol/claude-agent-acp': + specifier: ^0.73.0 +- version: 0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) ++ version: 0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) + '@anthropic-ai/sdk': + specifier: 0.129.0 + version: 0.129.0(zod@4.6.7) +@@ -511,7 +511,7 @@ importers: dependencies: -@@ -14013,14 +14013,14 @@ snapshots: + '@agentclientprotocol/claude-agent-acp': + specifier: 0.73.0 +- version: 0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) ++ version: 0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) + '@agentclientprotocol/codex-acp': + specifier: 1.6.2 + version: 1.6.2(patch_hash=2iynuypg76nxmydiylgtffhr7e) +@@ -904,7 +904,7 @@ importers: + version: 0.5.0 + '@agentclientprotocol/claude-agent-acp': + specifier: 0.73.0 +- version: 0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) ++ version: 0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) + '@agentclientprotocol/codex-acp': + specifier: 1.6.2 + version: 1.6.2(patch_hash=2iynuypg76nxmydiylgtffhr7e) +@@ -9548,7 +9548,7 @@ snapshots: + + '@adobe/css-tools@4.5.0': {} + +- '@agentclientprotocol/claude-agent-acp@0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))': ++ '@agentclientprotocol/claude-agent-acp@0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))': dependencies: - execa: 5.1.1 - -- '@vercel/connect@2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))))': -+ '@vercel/connect@2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))))': - dependencies: - '@vercel/oidc': 3.8.9 - optionalDependencies: - '@chat-adapter/slack': 4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7) - '@modelcontextprotocol/sdk': 1.31.0(zod@4.6.7) - ai: 7.0.130(zod@4.6.7) -- better-auth: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) -+ better-auth: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) - - '@vercel/oidc@3.2.0': {} - -@@ -14279,10 +14279,10 @@ snapshots: - - before-after-hook@4.0.0: {} - -- better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))): -+ better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))): - dependencies: - '@better-auth/core': 1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3) -- '@better-auth/drizzle-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge))) -+ '@better-auth/drizzle-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu))) - '@better-auth/kysely-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(kysely@0.29.5) - '@better-auth/memory-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1) - '@better-auth/mongo-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1) -@@ -14300,7 +14300,7 @@ snapshots: - zod: 4.6.7 - optionalDependencies: - drizzle-kit: 0.31.11 -- drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) -+ drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) - pg: 8.18.0 - react: 19.2.8 - react-dom: 19.2.8(react@19.2.8) -@@ -14895,12 +14895,12 @@ snapshots: - esbuild: 0.25.12 - tsx: 4.23.15 - -- drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)): -+ drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)): - optionalDependencies: - '@opentelemetry/api': 1.9.1 - kysely: 0.29.5 - pg: 8.18.0 -- postgres: 3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge) -+ postgres: 3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu) - - dunder-proto@1.0.1: - dependencies: -@@ -16813,7 +16813,7 @@ snapshots: - dependencies: - xtend: 4.0.2 - -- postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge): {} -+ postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu): {} - - powershell-utils@0.1.0: {} - + '@agentclientprotocol/sdk': 1.4.0(zod@4.4.3) + '@anthropic-ai/claude-agent-sdk': 0.3.286(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(zod@4.4.3) diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 9b98cab7e90..161eebf262c 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -268,7 +268,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "efab7ad18d89a60ddd3f961e35060b68424ef40b", + "packages/shared/src/index.ts": "825867d65bbb0783a2294e1838231e68669a8fc3", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -282,7 +282,7 @@ "packages/shared/src/issue-write-denial.test.ts": "e21b93aa79e6635c019ac338eff954ec618a98ed", "packages/shared/src/issue-write-denial.ts": "e6b4d72a83f6e4e76e85e34a80f88d1d69b7dfe4", "packages/shared/src/link-preview.test.ts": "136041c928343ad6272f43701b39cf95be255f3e", - "packages/shared/src/link-preview.ts": "ffa5eb960a7e4bcfa914b4d6029c9fc50f17e027", + "packages/shared/src/link-preview.ts": "b7431d4c30a12067e80e6806728b3ae7c7541f8f", "packages/shared/src/markdown-work-products.test.ts": "7293d14ad45ec2b11b5deaab4ce070c36f7c9010", "packages/shared/src/markdown-work-products.ts": "16a88cfb717f325c247a516e78b47d53871b52ed", "packages/shared/src/mcp-apps.test.ts": "848f3247bdc98af398daa144b0e44991a3f352b3", @@ -541,12 +541,12 @@ "packages/shared/src/worktree-seed-source.test.ts": "852856b1b5b8f4d0d3dada6501886fe50a2c2dde", "packages/shared/src/worktree-seed-source.ts": "3d1a09bed2d969feabef3400ff84fd499c1408f4", "packages/shared/tsconfig.json": "5a24989cd30dcf3749ca7e60d4e83d6ddbb14714", - "pnpm-lock.yaml": "05644099489b569367f982b14bb412439ba1b207", + "pnpm-lock.yaml": "c533906b86fb101285c5dd2d5b269ec17008a796", "scripts/ensure-plugin-build-deps.mjs": "356e0e0f80e50890067027da3003485cf5d2ccbe", "tsconfig.base.json": "2d0e41f723add0c678936eb9ae1c60eab710f8e0", "tsconfig.json": "994ee490fb97be7cc0954f4dfd88cf0723290e6c" }, - "lockSha256": "a09e9ae44a5f4244431837b158607621b6fa276148bec3078aae2d2e5f2443f9", + "lockSha256": "163e7562adefa9924ee96d8b8aa45fa45e7ebe16297315c5b51040803773b9e1", "compilerPackageSha256": "3722b30210616a13a3213ded11575ba6b2dbab10c32a5ef67afca8513e27017e", "parserPackageSha256": "6d6a65b879cd7cd249a4367c0b57cce00e78c728de45056ac2a5ca1d1f528d1a", "parserEntrySha256": "6969920ae0610df927b6b3e675d1309372c268e36d391652af8e3e0183cbe8f8", diff --git a/tests/storybook-visual/link-previews.spec.ts b/tests/storybook-visual/link-previews.spec.ts index 7d21fb31252..4e70349f802 100644 --- a/tests/storybook-visual/link-previews.spec.ts +++ b/tests/storybook-visual/link-previews.spec.ts @@ -167,3 +167,54 @@ for (const available of [true, false]) { await expect(links.nth(1)).toHaveAttribute("data-link-state", available ? "open" : "unknown"); }); } + +test("page load restores stored status and refreshes stale data on idle without hover", async ({ page }, testInfo) => { + const errors: string[] = []; + page.on("pageerror", error => errors.push(error.message)); + await page.addInitScript(() => { + const realFetch = window.fetch.bind(window); + let activeFetch = realFetch; + Object.defineProperty(window, "fetch", { + configurable: true, get: () => activeFetch, + set: (fixtureFetch: typeof fetch) => { + activeFetch = (input, init) => { + const url = input instanceof Request ? input.url : String(input); + return url.includes("/link-preview?") || url.includes("/link-previews/cached") ? realFetch(input, init) : fixtureFetch(input, init); + }; + }, + }); + }); + const canonicalUrl = "https://github.com/acme/web/pull/241"; + const preview = { target: { provider: "github", kind: "pull_request", canonicalUrl, label: "acme/web#241" }, + title: "Status from the database", state: "merged", author: "octocat", updatedAt: null }; + let cached = 0, resolved = 0; + let release!: () => void; + const refresh = new Promise(done => { release = done; }); + await page.route("**/api/companies/company-storybook/link-previews/cached?*", async route => { + cached++; + expect(new URL(route.request().url()).searchParams.getAll("url")).toEqual([canonicalUrl]); + await route.fulfill({ json: { results: { [canonicalUrl]: { preview, maxAgeMs: 0 } } } }); + }); + await page.route("**/api/companies/company-storybook/link-preview?*", async route => { + resolved++; + await refresh; + await route.fulfill({ json: { preview: { ...preview, state: "closed" }, maxAgeMs: 60_000 } }); + }); + await page.goto("/iframe.html?id=tasks-link-previews--page-load&viewMode=story&globals=theme:dark"); + await finished(page); + const links = page.locator("a[data-link-state]"); + await expect(links).toHaveCount(2); + await expect(links.first()).toHaveAttribute("data-link-state", "merged"); + await expect(links.last()).toHaveAttribute("data-link-state", "merged"); + await expect(page.getByRole("tooltip")).toHaveCount(0); + await expect.poll(() => resolved).toBe(1); + expect(cached).toBe(1); + release(); + await expect(links.first()).toHaveAttribute("data-link-state", "closed"); + await expect(links.last()).toHaveAttribute("data-link-state", "closed"); + await links.first().focus(); + await expect(page.getByRole("tooltip")).toBeVisible(); + expect(resolved).toBe(1); + await page.screenshot({ path: testInfo.outputPath("pr-status-from-database-after-idle.png"), fullPage: true }); + expect(errors).toEqual([]); +}); diff --git a/ui/src/components/CoordinatorSidebar.tsx b/ui/src/components/CoordinatorSidebar.tsx index 6529af2ba2c..8895ac8150c 100644 --- a/ui/src/components/CoordinatorSidebar.tsx +++ b/ui/src/components/CoordinatorSidebar.tsx @@ -127,9 +127,9 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) { const { collapsed, peeking, isMobile, setSidebarOpen } = useSidebar(); const rail = collapsed && !peeking; // Warm opens only while the Recents list is on screen. - useRecentTaskOpenWarmup({ companyId, userId, tasks: !rail && session.isSuccess ? recentTasks : NO_RECENT_TASKS }); - const { openNewIssue } = useDialogActions(); const location = useLocation(); + useRecentTaskOpenWarmup({ companyId, userId, tasks: !rail && session.isSuccess ? recentTasks : NO_RECENT_TASKS, navigationKey: location.pathname }); + const { openNewIssue } = useDialogActions(); const hierarchy = useMemo(() => recentTaskHierarchy(recentTasks, location.pathname), [recentTasks, location.pathname]); const attentionCount = useCoordinatorAttentionCount(companyId); const { data: projects } = useQuery({ ...companyProjectsQuery(companyId!), enabled: !!companyId }); diff --git a/ui/src/components/LinkPreview.tsx b/ui/src/components/LinkPreview.tsx index e2c12e40c5f..d505edc10b7 100644 --- a/ui/src/components/LinkPreview.tsx +++ b/ui/src/components/LinkPreview.tsx @@ -1,12 +1,11 @@ -import { useId, useMemo, useRef, useState, type ReactElement } from "react"; +import { useEffect, useId, useMemo, useRef, useState, type ReactElement } from "react"; import { useQuery } from "@tanstack/react-query"; import { PreviewCard } from "@base-ui/react/preview-card"; import { GitMerge, GitPullRequest, GitPullRequestClosed, GitPullRequestDraft, TriangleAlert } from "lucide-react"; import type { LinkPreview as Preview, LinkPreviewResult, LinkPreviewState, LinkPreviewTarget } from "@paperclipai/shared"; import { useLinkPreviewContext, type LinkPreviewContextValue } from "@/context/LinkPreviewContext"; import { timeAgo } from "@/lib/timeAgo"; -import { retryTransientOnly } from "@/lib/query-client"; -import { queryKeys } from "@/lib/queryKeys"; +import { linkPreviewQueryOptions } from "@/lib/link-preview-query"; export const linkPreviewStateLabel: Record = { unknown: "Status unknown", open: "Open", merged: "Merged", conflicts: "Merge conflicts", draft: "Draft", closed: "Closed", @@ -18,13 +17,13 @@ export const linkPreviewStateIcon = { function PreviewCardContents({ target, preview, loading }: { target: LinkPreviewTarget; preview?: Preview | null; loading: boolean }) { const state = preview?.state ?? "unknown"; - const Icon = linkPreviewStateIcon[state]; + const Icon = linkPreviewStateIcon[state] ?? linkPreviewStateIcon.unknown; const updated = preview?.updatedAt && Number.isFinite(Date.parse(preview.updatedAt)) ? preview.updatedAt : null; return
{preview ? <>

{preview.title}

@@ -50,17 +49,8 @@ function ConnectedLinkPreview({ context, target, children }: { getBoundingClientRect: () => triggerRef.current?.getClientRects()[0] ?? new DOMRect(), get contextElement() { return triggerRef.current ?? undefined; }, }), []); - const query = useQuery({ - queryKey: queryKeys.linkPreview(context.companyId, context.userId, target.canonicalUrl), - // Optional enrichment: a failed read is a cached absence, not a global error. - queryFn: async (): Promise => { - try { return await context.load(target); } catch { return { preview: null, maxAgeMs: 60_000 }; } - }, - enabled: open, - staleTime: query => query.state.data?.maxAgeMs ?? 60_000, - gcTime: 5 * 60_000, - retry: retryTransientOnly(0), refetchOnMount: false, refetchOnWindowFocus: false, refetchOnReconnect: false, - }); + useEffect(() => context.register?.(target), [context, target.canonicalUrl]); + const query = useQuery({ ...linkPreviewQueryOptions(context, target), enabled: open }); return setOpen(true)} onBlur={() => setOpen(false)} diff --git a/ui/src/components/MarkdownUrlLink.tsx b/ui/src/components/MarkdownUrlLink.tsx index 43316bb1d80..e8787de22bf 100644 --- a/ui/src/components/MarkdownUrlLink.tsx +++ b/ui/src/components/MarkdownUrlLink.tsx @@ -57,7 +57,7 @@ export function MarkdownUrlLink({ href, children, title, style, knownState, exte const label = github?.label ? compactUrlLabel(children, href, github.label) : children; const target = recognizeLinkPreview(href); const render = (state: LinkPreviewState = knownState ?? "unknown", describedBy?: string, preview?: Preview | null) => { - const StateIcon = target ? linkPreviewStateIcon[state] : Icon; + const StateIcon = target ? linkPreviewStateIcon[state] ?? linkPreviewStateIcon.unknown : Icon; const leadingIcon = github ?