From f05b90508abc5e25861c402c5f16d5f505929903 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Tue, 17 Nov 2026 14:00:14 -0800 Subject: [PATCH] refactor(core): remove retired compatibility paths (#22055) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Core manages chat authorization, AI connection defaults, navigation, and the plugin host. > - Core still writes old default rows and checks an Agent Chat flag that always reads true. > - It also carries a desktop rail that cannot open and private aliases with canonical equivalents. > - This pull request removes those paths and moves their tests onto the paths Core uses. > - The result is fewer Core database operations and less code to maintain. ## Linked Issues or Issue Description **What existing behavior does this improve?** Core AI default writes, Agent Chat execution and delivery, private plugin host and Runner setup, and board navigation. **Subsystem affected** Cross-cutting. Core server, board UI, private Runner helpers, and a repository guard script. **Current behavior** The server writes provider-scoped and per-method AI defaults, then reads only the provider-scoped rows. It reads settings to decide whether to block Agent Chat, although every settings view enables it. The desktop sidebar renders expanded while still tracking requests to open and close a retired icon rail. The agent client retries conflicts that the server already resolves when there is exactly one active match. **Proposed behavior** Write provider-scoped defaults directly. Use the existing Agent Chat authorization and retry checks without the redundant settings reads. Render the current sidebar directly and let the API report true agent reference conflicts. **Reason and benefit** A personal non-custom connection save or explicit default selection sends one fewer SQL statement. It also avoids the provider-default write that the legacy trigger performed when the old statement inserted or updated a row. A successful task-to-chat send or receipt replay avoids two transaction settings SELECTs when the singleton row already exists. Conversation comment, wake release, and retry paths also avoid a transaction settings read when they previously entered the gate. Savings in other settings paths depend on cache hits. Core-to-plugin RPC and plugin-to-Launcher HTTP traffic stay the same. **Breaking changes** The public plugin SDK, host navigation, and organization-switcher fields retain their existing interfaces and behavior. The settings API still accepts and reports the Agent Chat compatibility key. This change needs no schema migration or rollout ordering. **Additional context** Refs #10610 for prior reporting on the retired sidebar rail. Refs #21756 for adjacent Coordinator plugin slots, which remain a separate change. ## What Changed - Stop writing per-method AI defaults. Preserve the provider-scope upsert and first-account behavior. Keep the existing tables and migration trigger. - Remove Agent Chat checks that read a constant true value. Keep conversation ownership, task scope, session, and request-retry checks. - Remove unused lock-owner fields and private plugin lifecycle, secret extraction, Gmail connector, PRP setup, heartbeat resolver, and ACPX aliases. - Use a single API request for agent references. Remove retired sidebar rail state, hooks, and branches across the active and production snapshot layouts. Preserve desktop resizing, mobile drawer controls, contextual navigation, and public plugin slot inputs. - Remove unused FeedCard and AgentDetail inputs and the test-only Git push matcher alias. - Keep the cleanup that erases historical plaintext chat retries from browser storage. Production source in the touched files is 106,800 → 105,633 nonblank lines, down 1,167. The production Git diff adds 251 physical lines and removes 1,480, down 1,229. Those figures exclude tests, fixtures, docs, and Storybook. The entire Git diff adds 482 physical lines and removes 2,325, down 1,843. ## Verification - Merged master at `b56f240f45` into the PR branch as `f73fea4009`. The five sidebar files retain the expanded navigation cleanup and master’s explicit session-replay masking contract. The merge also preserves master’s account-repair recovery guard and GitHub star-prompt behavior. - Focused UI Vitest run passed 361 tests across 11 files. This covers analytics privacy and replay masking, sidebar and layout, GitHub star prompt, and agent detail. - Focused server Vitest run passed 45 tests across three files. This covers restored configuration handling, conversation recovery, and Agent Chat authority and receipt replay. - `pnpm --filter @paperclipai/ui typecheck`, the Git push guard and its 14 tests, and `git diff --check origin/master...HEAD` passed. - `pnpm verify --base origin/master` classified the Git-push guard as a global CI input and returned exit 2. GitHub CI supplied the broader coverage. - GitHub CI and Runner image checks passed on `f73fea4009`. Both required checks, `ci / verify` and `ci / e2e`, passed. [CI workflow](https://github.com/paperclipai/paperclip/actions/runs/44181261752) · [Runner image workflow](https://github.com/paperclipai/paperclip/actions/runs/44181261413) - Standard Greptile reported 5/5 with no actionable findings or open review threads. [Greptile review](https://github.com/paperclipai/paperclip/pull/22055#issuecomment-6959078925) - The optional Superagent Security Scan finished neutral with an inconclusive workflow result and zero annotations. The final rollup had 61 successes, five skips, and one neutral, with no failed or pending checks. [PR checks](https://github.com/paperclipai/paperclip/pull/22055/checks) ## Risks Agent Chat authorization and retry are sensitive to small query changes. The final diff keeps the conversation agent field and all existing authorization and idempotency checks. The tests cover revoked defaults, legacy migration reads, bound-listener authority, and mobile and desktop navigation. Installations that still run software old enough to read the per-method AI table will no longer see new defaults in that table. Current Core reads the provider-scoped table. ## Model Used OpenAI Codex, GPT-6.1 Sol (`gpt-6.1-sol`), with source inspection and shell-based tests. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- .../src/backends/codex-acpx-native-backend.ts | 18 +- .../src/backends/native-backend-factory.ts | 4 +- .../src/cli/acpx-runtime-sidecar.ts | 4 +- ...me-adapter.claude-background-tasks.test.ts | 6 +- ...-runtime-adapter.claude-login-text.test.ts | 6 +- ...-adapter.claude-overlapping-shells.test.ts | 6 +- ...ntime-adapter.claude-provider-turn.test.ts | 6 +- ...apter.claude-session-update-events.test.ts | 6 +- ...px-runtime-adapter.claude-tool-use.test.ts | 6 +- .../drivers/acpx/acpx-runtime-adapter.test.ts | 206 +++++++++--------- .../src/drivers/acpx/acpx-runtime-adapter.ts | 6 - .../src/drivers/acpx/codex-acpx-driver.ts | 4 +- .../native-distribution-integrity.test.ts | 6 +- .../src/drivers/acpx/runtime-host.test.ts | 4 +- packages/plugins/sdk/README.md | 4 +- scripts/check-no-git-push.mjs | 2 - scripts/check-no-git-push.test.mjs | 19 +- server/scripts/smoke-native-task-monitor.ts | 2 +- server/src/__tests__/ai-connections.test.ts | 10 +- .../case-handoff-native.integration.test.ts | 2 +- server/src/__tests__/dot-runner.test.ts | 2 +- .../historical-listener-continuation.ts | 2 +- .../helpers/native-restart-fixture.ts | 2 +- .../__tests__/helpers/runner-api-server.ts | 2 +- ...ue-agent-mutation-ownership-routes.test.ts | 8 +- .../modules/wake-queue/adapters/postgres.ts | 8 - server/src/realtime/runner-prp-ws.ts | 7 +- server/src/routes/issues.ts | 9 - server/src/services/agent-chat-messages.ts | 5 +- server/src/services/ai-connections.ts | 18 -- .../src/services/chat-completion-delivery.ts | 2 - server/src/services/heartbeat.ts | 7 - server/src/services/heartbeat/queue.ts | 5 +- server/src/services/heartbeat/run-control.ts | 9 +- server/src/services/instance-settings.ts | 4 - server/src/services/issues.ts | 3 - .../native-codex-runner.integration.test.ts | 4 +- .../native-question-bridge.test.ts | 2 +- .../native-session-resume.test.ts | 4 +- ...lip-runner-real-server.integration.test.ts | 4 +- .../runner-prp-coordinator.test.ts | 2 +- .../native-runtime/runtime-mode.test.ts | 58 +---- .../services/native-runtime/runtime-mode.ts | 101 --------- .../services/paperclip-id-gmail-connector.ts | 26 --- server/src/services/plugin-lifecycle.ts | 18 +- server/src/services/plugin-secrets-handler.ts | 22 -- server/src/services/recovery/service.ts | 2 - server/src/services/runtime-skill-cache.ts | 5 +- server/src/services/task-retry.ts | 10 +- server/src/services/tool-access.ts | 10 +- server/src/services/tool-gateway.ts | 10 +- ui/src/api/agents.test.ts | 11 +- ui/src/api/agents.ts | 31 +-- ui/src/components/ActivityFeed.tsx | 8 - ui/src/components/AgentChatSidebar.tsx | 45 ++-- ui/src/components/BreadcrumbBar.test.tsx | 2 - .../CompanySettingsSidebar.test.tsx | 1 - ui/src/components/ContextualSidebarFrame.tsx | 47 ++-- ui/src/components/CoordinatorSidebar.test.tsx | 30 +-- ui/src/components/CoordinatorSidebar.tsx | 25 +-- ui/src/components/DesignSidebar.tsx | 8 +- ui/src/components/FeedCard.tsx | 4 - ui/src/components/Layout.production.tsx | 137 ------------ ui/src/components/Layout.test.tsx | 117 +--------- ui/src/components/Layout.tsx | 118 +--------- ui/src/components/Layout.viewport.test.tsx | 4 +- ui/src/components/PinnedNavigationList.tsx | 16 +- .../PluginOrganizationSwitcher.test.tsx | 10 +- .../components/PluginOrganizationSwitcher.tsx | 14 +- ui/src/components/RecentTaskGroup.tsx | 11 +- .../RequestCollapsedSidebar.test.tsx | 111 ---------- ui/src/components/RequestCollapsedSidebar.tsx | 32 --- .../SecondarySidebar.production.tsx | 19 +- ui/src/components/SecondarySidebar.tsx | 3 +- ui/src/components/Sidebar.production.tsx | 38 +--- ui/src/components/Sidebar.test.tsx | 21 -- ui/src/components/Sidebar.tsx | 41 +--- .../SidebarAccountMenu.production.tsx | 13 +- ui/src/components/SidebarAccountMenu.tsx | 17 +- .../components/SidebarAgents.production.tsx | 35 +-- ui/src/components/SidebarAgents.test.tsx | 43 ---- ui/src/components/SidebarAgents.tsx | 35 +-- .../SidebarCompanyMenu.production.tsx | 12 +- ui/src/components/SidebarCompanyMenu.tsx | 12 +- .../components/SidebarNavItem.production.tsx | 111 +--------- ui/src/components/SidebarNavItem.test.tsx | 84 +------ ui/src/components/SidebarNavItem.tsx | 111 +--------- ui/src/components/SidebarProjects.test.tsx | 41 +--- ui/src/components/SidebarProjects.tsx | 38 +--- ui/src/components/SidebarRecentTasks.test.tsx | 2 - ui/src/components/SidebarRecentTasks.tsx | 97 ++++----- ui/src/components/SidebarSection.test.tsx | 82 ------- ui/src/components/SidebarSection.tsx | 27 --- ui/src/components/SidebarShell.production.tsx | 82 +------ ui/src/components/SidebarShell.test.tsx | 47 +--- ui/src/components/SidebarShell.tsx | 84 +------ .../SidebarStarredProjects.production.tsx | 29 +-- .../SidebarStarredProjects.test.tsx | 21 +- ui/src/components/SidebarStarredProjects.tsx | 29 +-- .../SkillsContextualSidebar.test.tsx | 1 - .../chat/ChatDetailSidebar.test.tsx | 20 +- ui/src/context/SidebarContext.test.tsx | 37 +--- ui/src/context/SidebarContext.tsx | 49 ----- ui/src/index.css | 1 - ui/src/lib/utils.ts | 12 - ui/src/pages/AgentDetail.progress.test.ts | 4 +- ui/src/pages/AgentDetail.tsx | 16 -- ui/src/pages/Timeline.test.tsx | 4 - ui/src/pages/Timeline.tsx | 3 - .../coordinator-tasks.stories.tsx | 2 +- .../sidebar-icon-alignment.stories.tsx | 2 +- .../design-proposals/FlyoutPreview.tsx | 2 +- 112 files changed, 482 insertions(+), 2325 deletions(-) delete mode 100644 server/src/services/paperclip-id-gmail-connector.ts delete mode 100644 ui/src/components/RequestCollapsedSidebar.test.tsx delete mode 100644 ui/src/components/RequestCollapsedSidebar.tsx diff --git a/packages/paperclip-runner/src/backends/codex-acpx-native-backend.ts b/packages/paperclip-runner/src/backends/codex-acpx-native-backend.ts index a5ddc64f80e..046cf34ff4f 100644 --- a/packages/paperclip-runner/src/backends/codex-acpx-native-backend.ts +++ b/packages/paperclip-runner/src/backends/codex-acpx-native-backend.ts @@ -13,14 +13,11 @@ import { nativeTaskConstraints, } from "./runtime-context.js"; -export interface CodexAcpxNativeSessionBackendOptions extends Omit< +export interface AcpxNativeSessionBackendOptions extends Omit< CodexAcpxDriverOptions, "model" | "permissionMode" | "mode" | "piThinkingLevel" | "claudeEffort" | "grokEffort" | "grokDisableWebSearch" | "systemInstructions" | "providerPolicy" | "runtimeContext" > {} -export type AcpxNativeSessionBackendOptions = - CodexAcpxNativeSessionBackendOptions; - /** * Constructs a backend only after the persisted ACPX snapshot matches the * closed, package-owned qualification profile for its selected agent. @@ -85,16 +82,3 @@ export function createAcpxNativeSessionBackend( }), ); } - -/** Backward-compatible Codex-specific constructor. */ -export function createCodexAcpxNativeSessionBackend( - input: NativeExecutionInput, - options: CodexAcpxNativeSessionBackendOptions, -): NativeSessionBackend { - if (input.provider.kind !== "acpx" || input.provider.agent !== "codex") { - throw new Error( - "Codex ACPX backend requires provider kind acpx with agent codex", - ); - } - return createAcpxNativeSessionBackend(input, options); -} diff --git a/packages/paperclip-runner/src/backends/native-backend-factory.ts b/packages/paperclip-runner/src/backends/native-backend-factory.ts index f603fb0a8c8..cebb0e4e954 100644 --- a/packages/paperclip-runner/src/backends/native-backend-factory.ts +++ b/packages/paperclip-runner/src/backends/native-backend-factory.ts @@ -15,7 +15,7 @@ import { } from "./codex-native-backend.js"; import { createAcpxNativeSessionBackend, - type CodexAcpxNativeSessionBackendOptions, + type AcpxNativeSessionBackendOptions, } from "./codex-acpx-native-backend.js"; import { createOpenCodeNativeSessionBackend } from "./opencode-native-backend.js"; @@ -39,7 +39,7 @@ export interface NativeBackendFactoryOptions extends Omit< acpxRuntimeDirectory?: string; acpxEnvironment?: NodeJS.ProcessEnv; acpxManagedCodexCredentialSourcePath?: string; - acpxDynamicToolHandler?: CodexAcpxNativeSessionBackendOptions["dynamicToolHandler"]; + acpxDynamicToolHandler?: AcpxNativeSessionBackendOptions["dynamicToolHandler"]; opencodeRuntimeDirectory?: string; opencodeEnvironment?: NodeJS.ProcessEnv; opencodeCommand?: string; diff --git a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts index d4088ad9ae8..2f320c63aa6 100644 --- a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts +++ b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts @@ -50,7 +50,7 @@ import { normalizeAcpFormElicitation, type NormalizedAcpForm, } from "../drivers/acpx/acp-question-adapter.js"; -import { openCodexAcpxRuntime, AcpxProviderProcessLostError } from "../drivers/acpx/acpx-runtime-adapter.js"; +import { openQualifiedAcpxRuntime, AcpxProviderProcessLostError } from "../drivers/acpx/acpx-runtime-adapter.js"; import { AcpxApprovalRequiredError } from "../drivers/acpx/permission-policy.js"; import { normalizeAcpxPermission, type NormalizedAcpxPermission } from "../drivers/acpx/acp-permission-adapter.js"; import { acpxGoalProjection } from "../drivers/acpx/session-goals.js"; @@ -398,7 +398,7 @@ async function dispatch( retainAdmissionCleanup: retainFailedAdmissionCleanup, reportRetainedCleanupFailure: reportRetainedAcpxCleanupFailure, openRuntime: (options) => - openCodexAcpxRuntime(options, { + openQualifiedAcpxRuntime(options, { retainCleanup: retainFailedAdmissionCleanup, }), }, diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-background-tasks.test.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-background-tasks.test.ts index 2c040d0cf67..6a89f04ce42 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-background-tasks.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-background-tasks.test.ts @@ -7,7 +7,7 @@ import { join } from "node:path"; import { expect, it, vi } from "vitest"; -import { openCodexAcpxRuntime } from "./acpx-runtime-adapter.js"; +import { openQualifiedAcpxRuntime } 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"; @@ -108,7 +108,7 @@ it("knows from the real Claude ACP stream when a turn leaves background work run mcpServers: [], retainFailedAdmissionCleanup: vi.fn(), } as AcpxRuntimePortOpenOptions; - let port: Awaited> | undefined; + let port: Awaited> | undefined; const runTurn = async (turnId: string, text: string) => { const before = await port!.getStatus(); const turn = port!.startTurn({ text, requestId: turnId, onPermissionRequest: async () => ({ outcome: "allow_once" }) }); @@ -119,7 +119,7 @@ it("knows from the real Claude ACP stream when a turn leaves background work run return { result, state, usage }; }; try { - port = await openCodexAcpxRuntime(options, { + port = await openQualifiedAcpxRuntime(options, { awaitProviderOwnership: async () => undefined, awaitProviderExit: child => new Promise(resolve => child.once("exit", () => resolve())), }); 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 index 5ad29ba2763..2ba0b046d42 100644 --- 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 @@ -8,7 +8,7 @@ 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 { openQualifiedAcpxRuntime } 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"; @@ -79,9 +79,9 @@ async function runTurn() { mcpServers: [], retainFailedAdmissionCleanup: vi.fn(), } as AcpxRuntimePortOpenOptions; - let port: Awaited> | undefined; + let port: Awaited> | undefined; try { - port = await openCodexAcpxRuntime(options, { + port = await openQualifiedAcpxRuntime(options, { awaitProviderOwnership: async () => undefined, awaitProviderExit: child => new Promise(resolve => child.once("exit", () => resolve())), }); diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-overlapping-shells.test.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-overlapping-shells.test.ts index 8e32695445d..cf1e0bd2e8e 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-overlapping-shells.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-overlapping-shells.test.ts @@ -8,7 +8,7 @@ import { join } from "node:path"; import { createAcpRuntime } from "acpx/runtime"; import { expect, it, vi } from "vitest"; -import { openCodexAcpxRuntime } from "./acpx-runtime-adapter.js"; +import { openQualifiedAcpxRuntime } from "./acpx-runtime-adapter.js"; import type { ClaudeBackgroundTaskState } from "./claude-background-tasks.js"; import type { VerifiedAcpxCommandLease } from "./installation-integrity.js"; import { resolveQualifiedAcpxProfile } from "./qualified-profiles.js"; @@ -96,9 +96,9 @@ it("is unknown after a cycle whose first update came after a second shell finish mcpServers: [], retainFailedAdmissionCleanup: vi.fn(), } as AcpxRuntimePortOpenOptions; - let port: Awaited> | undefined; + let port: Awaited> | undefined; try { - port = await openCodexAcpxRuntime(options, { + port = await openQualifiedAcpxRuntime(options, { awaitProviderOwnership: async () => undefined, awaitProviderExit: child => new Promise(resolve => child.once("exit", () => resolve())), createRuntime: (created) => { diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-provider-turn.test.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-provider-turn.test.ts index 009c174a285..89ff4c39dad 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-provider-turn.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-provider-turn.test.ts @@ -9,7 +9,7 @@ import type { AcpRuntimeEvent } from "acpx/runtime"; import { expect, it, vi } from "vitest"; import { startRunnerToolBridge } from "../runner-tool-bridge.js"; -import { openCodexAcpxRuntime } from "./acpx-runtime-adapter.js"; +import { openQualifiedAcpxRuntime } from "./acpx-runtime-adapter.js"; import { CLAUDE_TOOL_USE_META_KEY, ClaudeToolUseAdmission } from "./claude-tool-use-admission.js"; import type { ClaudeProviderTurnResult } from "./claude-provider-turns.js"; import type { VerifiedAcpxCommandLease } from "./installation-integrity.js"; @@ -124,9 +124,9 @@ it("adopts Claude's own task-notification cycle as a provider-started turn throu body: JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "probe", arguments: { tag }, _meta: { [CLAUDE_TOOL_USE_META_KEY]: toolUseId } } }) }) .then(response => response.json() as Promise<{ result: { isError?: boolean; content: Array<{ text: string }> } }>); - let port: Awaited> | undefined; + let port: Awaited> | undefined; try { - port = await openCodexAcpxRuntime(options, { + port = await openQualifiedAcpxRuntime(options, { awaitProviderOwnership: async () => undefined, awaitProviderExit: child => new Promise(resolve => child.once("exit", () => resolve())), }); diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-session-update-events.test.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-session-update-events.test.ts index 8738a45e7d1..83c30121809 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-session-update-events.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-session-update-events.test.ts @@ -9,7 +9,7 @@ import type { AcpRuntimeEvent } from "acpx/runtime"; import { expect, it, vi } from "vitest"; import { ACP_SESSION_UPDATE_EVENT_KINDS, createAcpSessionUpdateEventConverter } from "./acp-session-update-event.js"; -import { openCodexAcpxRuntime } from "./acpx-runtime-adapter.js"; +import { openQualifiedAcpxRuntime } 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"; @@ -151,7 +151,7 @@ it("converts the real Claude ACP stream exactly as ACPX does for every update ki } as unknown as AcpxRuntimePortOpenOptions; const converter = createAcpSessionUpdateEventConverter(); const seen = new Map(); - let port: Awaited> | undefined; + let port: Awaited> | undefined; const runTurn = async (turnId: string, text: string) => { capture = []; promptAnswered = false; @@ -178,7 +178,7 @@ it("converts the real Claude ACP stream exactly as ACPX does for every update ki return yielded; }; try { - port = await openCodexAcpxRuntime(options, { + port = await openQualifiedAcpxRuntime(options, { awaitProviderOwnership: async () => undefined, awaitProviderExit: child => new Promise(resolve => child.once("exit", () => resolve())), }); diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-tool-use.test.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-tool-use.test.ts index 9177861e604..5b923174134 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-tool-use.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-tool-use.test.ts @@ -8,7 +8,7 @@ import { join } from "node:path"; import { expect, it, vi } from "vitest"; import { startRunnerToolBridge } from "../runner-tool-bridge.js"; -import { openCodexAcpxRuntime } from "./acpx-runtime-adapter.js"; +import { openQualifiedAcpxRuntime } from "./acpx-runtime-adapter.js"; import { CLAUDE_TOOL_USE_META_KEY, ClaudeToolUseAdmission } from "./claude-tool-use-admission.js"; import type { VerifiedAcpxCommandLease } from "./installation-integrity.js"; import { resolveQualifiedAcpxProfile } from "./qualified-profiles.js"; @@ -138,9 +138,9 @@ it("admits each Claude tool call through the real ACP turn stream only for its o body: JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "probe", arguments: { tag }, _meta: { [CLAUDE_TOOL_USE_META_KEY]: toolUseId } } }) }) .then(response => response.json() as Promise<{ result: { isError?: boolean; content: Array<{ text: string }> } }>); - let port: Awaited> | undefined; + let port: Awaited> | undefined; try { - port = await openCodexAcpxRuntime(options, { + port = await openQualifiedAcpxRuntime(options, { awaitProviderOwnership: async () => undefined, awaitProviderExit: child => new Promise(resolve => child.once("exit", () => resolve())), }); diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.test.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.test.ts index b22ab267bfc..bf94a35f5b9 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.test.ts @@ -19,7 +19,7 @@ import { decodeAcpxRuntimeHandleState } from "acpx/runtime"; import { describe, expect, it, vi } from "vitest"; import type { VerifiedAcpxCommandLease } from "./installation-integrity.js"; -import { acpxSessionHandshakeTimeoutMs, claudeExitPlanModeProposal, openCodexAcpxRuntime, resetAbandonedBootstrapRecord } from "./acpx-runtime-adapter.js"; +import { acpxSessionHandshakeTimeoutMs, claudeExitPlanModeProposal, openQualifiedAcpxRuntime, resetAbandonedBootstrapRecord } from "./acpx-runtime-adapter.js"; import { cursorInstructionBinding } from "./cursor-instructions.js"; import { persistedAcpxTurnUsage } from "./usage-accounting.js"; import { createAcpxCommandLeaseOwner } from "./command-lease-owner.js"; @@ -44,7 +44,7 @@ describe("Codex ACPX runtime adapter", () => { vi.mocked(runtime.ensureSession).mockRejectedValue(rejection); const options = openOptions(fakeCommand()); options.profile = { ...options.profile, agent: "claude" }; - await expect(openCodexAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), + await expect(openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime })).rejects.toMatchObject({ code: "ACPX_SESSION_ENSURE_FAILED", providerFailure: { provider: "anthropic", category: "rate_limit", httpStatus: 429, @@ -59,7 +59,7 @@ describe("Codex ACPX runtime adapter", () => { options.launchEnvironment = { ANTHROPIC_API_KEY: "fixture-anthropic-secret" }; const rejection = new Error("Claude Code exited during startup for fixture-anthropic-secret (sk-ant-api03-fixtureprivate)"); vi.mocked(runtime.ensureSession).mockRejectedValue(rejection); - const failure = await openCodexAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), + const failure = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime }).catch((error: unknown) => error); expect(failure).toBe(rejection); expect(failure).toMatchObject({ code: "ACPX_SESSION_ENSURE_FAILED", providerFailure: { provider: "anthropic", @@ -72,7 +72,7 @@ describe("Codex ACPX runtime adapter", () => { vi.mocked(runtime.ensureSession).mockRejectedValue(Object.assign(new Error(message), { code: -32000 })); const options = openOptions(fakeCommand()); options.profile = { ...options.profile, agent: "claude" }; - await expect(openCodexAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), + await expect(openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime })).rejects.toMatchObject({ code: "ACPX_SESSION_ENSURE_FAILED", providerFailure: { category: "authentication", message, phase: "startup", retryability: "requires_action" } }); }); @@ -81,7 +81,7 @@ describe("Codex ACPX runtime adapter", () => { vi.mocked(runtime.ensureSession).mockRejectedValue({ code: -32603, message: "Internal error", data: { errorKind: "billing_error" } }); const options = openOptions(fakeCommand()); options.profile = { ...options.profile, agent: "claude" }; - await expect(openCodexAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), + await expect(openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime })).rejects.toMatchObject({ code: "ACPX_SESSION_ENSURE_NON_ERROR", providerFailure: { category: "quota_exhausted", providerCode: "billing_error", phase: "startup" } }); }); @@ -96,7 +96,7 @@ describe("Codex ACPX runtime adapter", () => { }); const options = openOptions(fakeCommand()); options.signal = controller.signal; - await expect(openCodexAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), + await expect(openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime })).rejects.toBe(reason); await vi.waitFor(() => expect(rejection).toHaveProperty("code", "ACPX_SESSION_ENSURE_FAILED")); expect(rejection).not.toHaveProperty("providerFailure"); @@ -124,7 +124,7 @@ describe("Codex ACPX runtime adapter", () => { guard("outbound", { id: 1, method: "session/set_config_option", params: { sessionId: "backend-1", configId: input.key, value: input.value } }); guard("inbound", { id: 1, result: { configOptions: [{ id: "effort", currentValue: input.value }] } }); }); - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: value => { created = value; return runtime; }, awaitProviderOwnership: providerOwnershipEstablished, awaitProviderExit: providerOwnershipEstablished, @@ -160,7 +160,7 @@ describe("Codex ACPX runtime adapter", () => { runtime.requestExtension.mockImplementation(async () => { spawnProvider(); acknowledge(); return {}; }); - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: value => { created = value; return runtime; }, awaitProviderOwnership: providerOwnershipEstablished, awaitProviderExit: providerOwnershipEstablished, @@ -205,11 +205,11 @@ describe("Codex ACPX runtime adapter", () => { PAPERCLIP_RUNNER_HOME_MODE: "preconfigured", ANTHROPIC_API_KEY: "local-fixture-only", ANTHROPIC_BASE_URL: `http://127.0.0.1:${address.port}`, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }, }; - let port: Awaited> | undefined; + let port: Awaited> | undefined; const priorSettingsFlag = process.env.ACPX_CLAUDE_INCLUDE_USER_SETTINGS; process.env.ACPX_CLAUDE_INCLUDE_USER_SETTINGS = "1"; try { - port = await openCodexAcpxRuntime(options, { + port = await openQualifiedAcpxRuntime(options, { // This test exercises ACP/model admission; lifetime-fence tests are separate. awaitProviderOwnership: async () => undefined, awaitProviderExit: child => new Promise(resolve => child.once("exit", () => resolve())), @@ -241,7 +241,7 @@ describe("Codex ACPX runtime adapter", () => { const options = openOptions(command); options.profile = { ...options.profile, agent: "claude" }; options.permissionMode = "approve-all"; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, awaitProviderExit: () => providerExit, createRuntime: value => { created = value; return runtimeWithProvider(runtime, value); }, @@ -283,7 +283,7 @@ describe("Codex ACPX runtime adapter", () => { const createRuntime = vi.fn(); const options = openOptions(fakeCommand()); options.launchEnvironment = { HOME: "/users/executor", PAPERCLIP_RUNNER_HOME_MODE: "preconfigured" }; - await expect(openCodexAcpxRuntime(options, { createRuntime })).rejects.toThrow("cannot protect Runner state"); + await expect(openQualifiedAcpxRuntime(options, { createRuntime })).rejects.toThrow("cannot protect Runner state"); expect(createRuntime).not.toHaveBeenCalled(); }); @@ -301,7 +301,7 @@ describe("Codex ACPX runtime adapter", () => { const options = openOptions(command); options.profile = { ...options.profile, agent: "copilot" }; options.permissionMode = "approve-paperclip"; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, awaitProviderExit: () => providerExit, @@ -351,7 +351,7 @@ describe("Codex ACPX runtime adapter", () => { const options = openOptions(command); options.profile = { ...options.profile, agent: "copilot" }; options.permissionMode = "approve-paperclip"; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, awaitProviderExit: () => providerExit, @@ -400,7 +400,7 @@ describe("Codex ACPX runtime adapter", () => { const options = openOptions(command); options.profile = { ...options.profile, agent: "copilot" }; options.permissionMode = "approve-paperclip"; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, awaitProviderExit: () => providerExit, createRuntime: value => { created = value; return runtimeWithProvider(runtime, value); }, @@ -428,7 +428,7 @@ describe("Codex ACPX runtime adapter", () => { let created!: AcpRuntimeOptions; const options = openOptions(fakeCommand()); options.profile = { ...options.profile, agent }; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: value => { created = value; return runtime; }, }); // Copilot no longer needs a patched ACPX admission hook; Grok keeps one @@ -460,7 +460,7 @@ describe("Codex ACPX runtime adapter", () => { let created!: AcpRuntimeOptions; const options = openOptions(fakeCommand()); options.profile = { ...options.profile, agent: "copilot" }; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: value => { created = value; return runtime; }, }); created.onAcpMessage!("inbound", { jsonrpc: "2.0", method: "session/update", params: { sessionId: "backend-1", update: { @@ -487,7 +487,7 @@ describe("Codex ACPX runtime adapter", () => { { name: "paperclip_runner_fixture", url: "http://127.0.0.1:3211/mcp", bearerToken: "runner-fixture", runnerOwned: true }, { name: "paperclip", url: "http://127.0.0.1:3212/mcp", bearerToken: "external-fixture", runnerOwned: false }, ]; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: value => { created = value; return runtime; }, }); const sessionOptions = vi.mocked(runtime.ensureSession).mock.calls[0]?.[0].sessionOptions; @@ -511,7 +511,7 @@ describe("Codex ACPX runtime adapter", () => { const runtime = fakeRuntime(); vi.mocked(runtime.startTurn).mockReturnValue(pending.turn); let created!: AcpRuntimeOptions; const options = openOptions(fakeCommand()); - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: (value) => { created = value; return runtime; }, }); const handler = vi.fn(async () => ({ outcome: "allow_once" as const })); @@ -535,7 +535,7 @@ describe("Codex ACPX runtime adapter", () => { const runtime = fakeRuntime(); vi.mocked(runtime.startTurn).mockReturnValue(pending.turn); let created!: AcpRuntimeOptions; const options = openOptions(fakeCommand()); - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: value => { created = value; return runtime; }, }); let callbackSignal!: AbortSignal; @@ -572,7 +572,7 @@ describe("Codex ACPX runtime adapter", () => { const runtime = fakeRuntime(); const options = openOptions(fakeCommand()); options.profile = { ...options.profile, agent: "cursor" }; - await expect(openCodexAcpxRuntime(options, { + await expect(openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, })).rejects.toThrow("Cursor instruction admission failed"); expect(runtime.startTurn).not.toHaveBeenCalled(); @@ -592,7 +592,7 @@ describe("Codex ACPX runtime adapter", () => { } } } }); if (mode === "unsupported") throw new Error("Exact model unsupported"); }); - const opening = openCodexAcpxRuntime(options, { + const opening = openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: value => { created = value; return runtime; }, }); if (mode === "valid") { @@ -620,7 +620,7 @@ describe("Codex ACPX runtime adapter", () => { guard("outbound", { id: 1, method: "session/set_config_option", params: { sessionId: "backend-1", configId: input.key, value: input.value } }); guard("inbound", { id: 1, result: { configOptions: configs(input.key === "mode" ? selected : "agent") } }); }); - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: value => { created = value; return runtime; }, }); expect(vi.mocked(runtime.setConfigOption!).mock.calls.map(([call]) => [call.key, call.value])).toEqual([["model", options.profile.reportedModelId], ["mode", selected]]); @@ -639,7 +639,7 @@ describe("Codex ACPX runtime adapter", () => { const options = openOptions(fakeCommand()); options.profile = { ...options.profile, agent: "cursor" }; options.clientCapabilities = { _meta: { cursor: { test: true } } }; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: (value) => { created = value; @@ -702,7 +702,7 @@ describe("Codex ACPX runtime adapter", () => { guard("outbound", { id: 1, method: "session/set_config_option", params: { sessionId: "backend-1", configId: input.key, value: input.value } }); guard("inbound", { id: 1, result: { configOptions: [{ id: "thought_level", currentValue: "low" }] } }); }); - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: (value) => { created = value; return runtime; }, }); @@ -735,7 +735,7 @@ describe("Codex ACPX runtime adapter", () => { let created!: AcpRuntimeOptions; const baseRecord = { acpxRecordId: "record-1", acpSessionId: "backend-1", cwd: "/workspace", agentCapabilities: { loadSession: true, _meta: { vendor: { kept: true } } } } as unknown as AcpSessionRecord; - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => ({ load: vi.fn(), save: vi.fn(async (record: AcpSessionRecord) => { saved.push(structuredClone(record)); }) }), createRuntime: (value) => { created = value; return fakeRuntime(); }, @@ -767,7 +767,7 @@ describe("Codex ACPX runtime adapter", () => { guard("outbound", { id: 1, method: "session/set_config_option", params: { sessionId: "backend-1", configId: input.key, value: input.value } }); guard("inbound", { id: 1, result: { configOptions: [{ id: "thought_level", currentValue: "low" }] } }); }); - const restoredPort = await openCodexAcpxRuntime(piOptions, { + const restoredPort = await openQualifiedAcpxRuntime(piOptions, { createRegistry: () => registry(), createStore: () => ({ load: vi.fn(async () => structuredClone(record)), save: vi.fn() }), createRuntime: (value) => { restored = value; return piRuntime; }, @@ -793,7 +793,7 @@ describe("Codex ACPX runtime adapter", () => { let created!: AcpRuntimeOptions; const options = openOptions(fakeCommand()); options.stateDirectory = stateDirectory; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => ({ load: vi.fn(async () => structuredClone(parsed)), save: vi.fn(async (record: AcpSessionRecord) => { saves.push(structuredClone(record)); }) }), createRuntime: (value) => { created = value; return fakeRuntime(); }, @@ -812,7 +812,7 @@ describe("Codex ACPX runtime adapter", () => { it("does not grant steering to Copilot or Cursor when an untrusted initialize result claims Pi support", async () => { const options = openOptions(fakeCommand()); options.profile = { ...options.profile, agent: "copilot" }; const runtime = fakeRuntime(); - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: (created) => { initializeOverWire(created, { agentCapabilities: { _meta: { paperclipPi: { version: 1, steering: true, queuedFollowUp: true } } } }); @@ -826,7 +826,7 @@ describe("Codex ACPX runtime adapter", () => { const options = openOptions(fakeCommand()); options.profile = { ...options.profile, agent: "claude" }; let runtimeOptions: AcpRuntimeOptions | undefined; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: (created) => { runtimeOptions = created; return fakeRuntime(); }, }); @@ -856,7 +856,7 @@ describe("Codex ACPX runtime adapter", () => { const options = openOptions(fakeCommand()); options.profile = { ...options.profile, agent: "claude" }; let runtimeOptions: AcpRuntimeOptions | undefined; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: (created) => { runtimeOptions = created; return fakeRuntime(); }, }); @@ -886,7 +886,7 @@ describe("Codex ACPX runtime adapter", () => { const options = openOptions(fakeCommand()); options.profile = { ...options.profile, agent: "claude" }; let runtimeOptions: AcpRuntimeOptions | undefined; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: (created) => { runtimeOptions = created; return fakeRuntime(); }, }); @@ -943,7 +943,7 @@ describe("Codex ACPX runtime adapter", () => { }); const options = openOptions(fakeCommand()); options.permissionMode = permissionMode; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: (created) => { runtimeOptions = created; return runtime; }, @@ -971,7 +971,7 @@ describe("Codex ACPX runtime adapter", () => { events: { async *[Symbol.asyncIterator]() {} }, result: Promise.resolve(result), cancel: vi.fn(), closeStream: vi.fn(), }); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, }); try { @@ -993,7 +993,7 @@ describe("Codex ACPX runtime adapter", () => { const retainFailedAdmissionCleanup = vi.fn(); await expect( - openCodexAcpxRuntime( + openQualifiedAcpxRuntime( { ...openOptions(command), signal: controller.signal, @@ -1015,7 +1015,7 @@ describe("Codex ACPX runtime adapter", () => { const runtime = fakeRuntime(); let runtimeOptions: AcpRuntimeOptions | undefined; const command = fakeCommand(); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: ({ overrides }) => { expect(overrides).toEqual({ codex: ["paperclip-verified-acpx-command"], @@ -1068,7 +1068,7 @@ describe("Codex ACPX runtime adapter", () => { options.profile = resolveQualifiedAcpxProfile(agent, model); options.launchEnvironment = { PATH: "/verified/bin" }; - await openCodexAcpxRuntime(options, { + await openQualifiedAcpxRuntime(options, { createRegistry: ({ overrides }) => { expect(overrides).toEqual({ [agent]: [agent === "claude" ? "/paperclip-verified/claude-agent-acp" : "paperclip-verified-acpx-command"], @@ -1107,7 +1107,7 @@ describe("Codex ACPX runtime adapter", () => { bearerToken: "bridge-secret", runnerOwned: binding === "runner-owned", }]; let runtimeOptions: AcpRuntimeOptions | undefined; - await openCodexAcpxRuntime(options, { + await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: (created) => { @@ -1128,7 +1128,7 @@ describe("Codex ACPX runtime adapter", () => { const child = fakeChild(); vi.mocked(command.spawn).mockReturnValue(child); const spawnOptions = { cwd: "/runtime/spawn" }; - await openCodexAcpxRuntime(openOptions(command), { + await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -1165,7 +1165,7 @@ describe("Codex ACPX runtime adapter", () => { const assertWorkspaceHeld = vi.fn(() => { throw workspaceSubstituted; }); - await openCodexAcpxRuntime( + await openQualifiedAcpxRuntime( { ...openOptions(command), assertWorkspaceHeld }, { createRegistry: () => registry(), @@ -1194,7 +1194,7 @@ describe("Codex ACPX runtime adapter", () => { let created!: AcpRuntimeOptions; const options = openOptions(fakeCommand()); options.profile = { ...options.profile, agent: "grok" }; - const port = await openCodexAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => durableStore, + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => durableStore, createRuntime: value => { created = value; return runtime; } }); let sequence = 0; vi.mocked(runtime.startTurn).mockImplementation(input => { @@ -1228,7 +1228,7 @@ describe("Codex ACPX runtime adapter", () => { it("journals a turn before provider work and its prompt dispatch before the prompt write", async () => { const runtime = fakeRuntime(); let created!: AcpRuntimeOptions; - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: value => { created = value; return runtime; } }); const order: string[] = []; const journal = { @@ -1256,7 +1256,7 @@ describe("Codex ACPX runtime adapter", () => { it("runs a turn unjournaled when its start cannot be journaled", async () => { const runtime = fakeRuntime(); let created!: AcpRuntimeOptions; - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: value => { created = value; return runtime; } }); const pending = pendingExtensionTurn("unjournaled-start"); vi.mocked(runtime.startTurn).mockImplementation(() => pending.turn); @@ -1274,7 +1274,7 @@ describe("Codex ACPX runtime adapter", () => { it("aborts the prompt write when its dispatch cannot be journaled", async () => { const runtime = fakeRuntime(); let created!: AcpRuntimeOptions; - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: value => { created = value; return runtime; } }); const pending = pendingExtensionTurn("unjournaled-turn"); vi.mocked(runtime.startTurn).mockImplementation(() => pending.turn); @@ -1302,7 +1302,7 @@ describe("Codex ACPX runtime adapter", () => { const result = new Promise<{ status: "completed" }>(resolve => { settle = resolve; }); const options = openOptions(fakeCommand()); options.profile = { ...options.profile, agent: "grok" }; - const port = await openCodexAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => durableStore, + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => durableStore, createRuntime: value => { created = value; return runtime; } }); vi.mocked(runtime.startTurn).mockImplementation(input => { durableRecord.lastRequestId = input.requestId; @@ -1352,7 +1352,7 @@ describe("Codex ACPX runtime adapter", () => { load: vi.fn(async () => structuredClone(durableRecord)), save: vi.fn(), }; - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => durableStore, createRuntime: () => runtime, @@ -1398,7 +1398,7 @@ describe("Codex ACPX runtime adapter", () => { const child = fakeChild(); const command = fakeCommand(); vi.mocked(command.spawn).mockReturnValue(child); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -1445,7 +1445,7 @@ describe("Codex ACPX runtime adapter", () => { const child = fakeChild(); const command = fakeCommand(); vi.mocked(command.spawn).mockReturnValue(child); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -1497,7 +1497,7 @@ describe("Codex ACPX runtime adapter", () => { const child = fakeChild(); const command = fakeCommand(); vi.mocked(command.spawn).mockReturnValue(child); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -1556,7 +1556,7 @@ describe("Codex ACPX runtime adapter", () => { const child = fakeChild(); const command = fakeCommand(); vi.mocked(command.spawn).mockReturnValue(child); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -1611,7 +1611,7 @@ describe("Codex ACPX runtime adapter", () => { .mockRejectedValueOnce(new Error("reconciliation 1 failed")) .mockRejectedValueOnce(new Error("reconciliation 2 failed")) .mockRejectedValueOnce(new Error("reconciliation 3 failed")); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, @@ -1654,7 +1654,7 @@ describe("Codex ACPX runtime adapter", () => { .mockReturnValueOnce(reconciliationAttempts[1]!) .mockReturnValueOnce(reconciliationAttempts[2]!) .mockResolvedValueOnce(undefined); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, @@ -1722,7 +1722,7 @@ describe("Codex ACPX runtime adapter", () => { .mockRejectedValueOnce(new Error("reconciliation 2 failed")) .mockReturnValueOnce(finalReconciliation) .mockResolvedValueOnce(undefined); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, @@ -1780,7 +1780,7 @@ describe("Codex ACPX runtime adapter", () => { .mockRejectedValueOnce(new Error("renewed reconciliation 1 failed")) .mockRejectedValueOnce(new Error("renewed reconciliation 2 failed")) .mockRejectedValueOnce(new Error("renewed reconciliation 3 failed")); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, @@ -1842,7 +1842,7 @@ describe("Codex ACPX runtime adapter", () => { .mockRejectedValueOnce(new Error("reconciliation 1 failed")) .mockRejectedValueOnce(new Error("reconciliation 2 failed")) .mockReturnValueOnce(finalReconciliation); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, @@ -1916,7 +1916,7 @@ describe("Codex ACPX runtime adapter", () => { const child = failingSignalChild(); const command = fakeCommand(); vi.mocked(command.spawn).mockReturnValue(child.child); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -1995,7 +1995,7 @@ describe("Codex ACPX runtime adapter", () => { const child = failingSignalChild(); const command = fakeCommand(); vi.mocked(command.spawn).mockReturnValue(child.child); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -2055,7 +2055,7 @@ describe("Codex ACPX runtime adapter", () => { .mockRejectedValueOnce(new Error("reconciliation 1 failed")) .mockRejectedValueOnce(new Error("reconciliation 2 failed")) .mockRejectedValueOnce(new Error("reconciliation 3 failed")); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, @@ -2103,7 +2103,7 @@ describe("Codex ACPX runtime adapter", () => { .mockRejectedValueOnce(new Error("reconciliation 3 failed")) .mockReturnValueOnce(newerClose) .mockResolvedValueOnce(undefined); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, @@ -2152,7 +2152,7 @@ describe("Codex ACPX runtime adapter", () => { let finishPendingWork!: () => void; const pendingWork = new Promise((resolve) => { finishPendingWork = resolve; }); runtime.shutdown = vi.fn(() => pendingWork); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, @@ -2189,7 +2189,7 @@ describe("Codex ACPX runtime adapter", () => { let finishPendingWork!: () => void; const pendingWork = new Promise((resolve) => { finishPendingWork = resolve; }); runtime.shutdown = vi.fn(() => pendingWork); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, @@ -2213,7 +2213,7 @@ describe("Codex ACPX runtime adapter", () => { const runtime = fakeRuntime(); vi.mocked(runtime.close).mockResolvedValue(undefined); runtime.shutdown = vi.fn().mockRejectedValue(new Error("owned client close failed")); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, @@ -2234,7 +2234,7 @@ describe("Codex ACPX runtime adapter", () => { const providerExit = new Promise((resolve) => { proveProviderExit = resolve; }); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -2270,7 +2270,7 @@ describe("Codex ACPX runtime adapter", () => { const child = childThatExitsOnKill(); const command = fakeCommand(); vi.mocked(command.spawn).mockReturnValue(child); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -2311,7 +2311,7 @@ describe("Codex ACPX runtime adapter", () => { const child = stubbornChild(); const command = fakeCommand(); vi.mocked(command.spawn).mockReturnValue(child); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -2346,7 +2346,7 @@ describe("Codex ACPX runtime adapter", () => { const createRuntime = vi.fn(() => fakeRuntime()); await expect( - openCodexAcpxRuntime(openOptions(command), { + openQualifiedAcpxRuntime(openOptions(command), { platform: "win32", createRuntime, }), @@ -2367,7 +2367,7 @@ describe("Codex ACPX runtime adapter", () => { const createRuntime = vi.fn(() => fakeRuntime()); await expect( - openCodexAcpxRuntime( + openQualifiedAcpxRuntime( { ...openOptions(command), credentialFenceFds: fences as unknown as readonly [number, number], @@ -2387,7 +2387,7 @@ describe("Codex ACPX runtime adapter", () => { const createRuntime = vi.fn(() => fakeRuntime()); await expect( - openCodexAcpxRuntime( + openQualifiedAcpxRuntime( { ...openOptions(command), activateCredentialFenceOwner: null, @@ -2414,7 +2414,7 @@ describe("Codex ACPX runtime adapter", () => { .mockReturnValueOnce(lateChild); const retainedCleanups: Promise[] = []; let runtimeOptions: AcpRuntimeOptions | undefined; - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -2470,7 +2470,7 @@ describe("Codex ACPX runtime adapter", () => { cancel: vi.fn(), closeStream: vi.fn(), }); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, }); const onTerminalSessionFailure = vi.fn(); @@ -2491,7 +2491,7 @@ describe("Codex ACPX runtime adapter", () => { cancel: vi.fn(), closeStream: vi.fn(), }); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, }); const onTerminalSessionFailure = vi.fn(); @@ -2511,7 +2511,7 @@ describe("Codex ACPX runtime adapter", () => { closeStream: vi.fn(), }; vi.mocked(runtime.startTurn).mockReturnValue(turn); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, @@ -2561,7 +2561,7 @@ describe("Codex ACPX runtime adapter", () => { cancel: vi.fn(), closeStream: vi.fn(), })); - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: () => runtime, }); const turn = port.startTurn({ text: "Resume", requestId: "turn-recovered-failure" }); @@ -2587,7 +2587,7 @@ describe("Codex ACPX runtime adapter", () => { await Promise.resolve(); runtimeOptions?.spawnAgent?.({ command: "ignored", args: ["--stdio"], options: {} }); }); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: () => ownership, awaitProviderExit: providerOwnershipEstablished, @@ -2634,7 +2634,7 @@ describe("Codex ACPX runtime adapter", () => { closeStream: vi.fn(), }; }); - const port = await openCodexAcpxRuntime( + const port = await openQualifiedAcpxRuntime( { ...openOptions(owner.command), refreshConsumedCommand: owner.refreshConsumedCommand, @@ -2689,7 +2689,7 @@ describe("Codex ACPX runtime adapter", () => { }); return rawTurn; }); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -2718,7 +2718,7 @@ describe("Codex ACPX runtime adapter", () => { it("projects only ephemeral MCP bindings and applies fail-closed permissions", async () => { const runtime = fakeRuntime(); let runtimeOptions: AcpRuntimeOptions | undefined; - const port = await openCodexAcpxRuntime( + const port = await openQualifiedAcpxRuntime( { ...openOptions(fakeCommand()), permissionMode: "deny-all", @@ -2770,7 +2770,7 @@ describe("Codex ACPX runtime adapter", () => { it("rejects permissions that require an unavailable coordinator", async () => { const runtime = fakeRuntime(); let runtimeOptions: AcpRuntimeOptions | undefined; - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), createRuntime: (options) => { @@ -2804,7 +2804,7 @@ describe("Codex ACPX runtime adapter", () => { const options = openOptions(fakeCommand()); options.profile = resolveQualifiedAcpxProfile(agent, model); options.permissionMode = permissionMode; - const port = await openCodexAcpxRuntime(options, { + const port = await openQualifiedAcpxRuntime(options, { createRegistry: () => registry(), createStore: () => store(), createRuntime: (createdOptions) => { @@ -2836,7 +2836,7 @@ describe("Codex ACPX runtime adapter", () => { ), save: vi.fn(), }; - const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { + const port = await openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => durableStore, createRuntime: () => runtime, @@ -2869,7 +2869,7 @@ describe("Codex ACPX runtime adapter", () => { const child = fakeChild(); const command = fakeCommand(); vi.mocked(command.spawn).mockReturnValue(child); - const opening = openCodexAcpxRuntime(openOptions(command), { + const opening = openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderExit: providerOwnershipEstablished, @@ -2915,7 +2915,7 @@ describe("Codex ACPX runtime adapter", () => { vi.mocked(command.spawn).mockReturnValue(child); const runtime = fakeRuntime(); const options = openOptions(command); - const opening = openCodexAcpxRuntime({ ...options, profile: { ...options.profile, agent } }, { + const opening = openQualifiedAcpxRuntime({ ...options, profile: { ...options.profile, agent } }, { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -2977,7 +2977,7 @@ describe("Codex ACPX runtime adapter", () => { const runtime = fakeRuntime(); const order: string[] = []; vi.mocked(sessions.save).mockImplementation(async () => { order.push("save"); }); - const port = await openCodexAcpxRuntime({ ...openOptions(command), restoringSession: restoring }, { + const port = await openQualifiedAcpxRuntime({ ...openOptions(command), restoringSession: restoring }, { createRegistry: () => registry(), createStore: () => sessions, awaitProviderOwnership: providerOwnershipEstablished, @@ -3004,7 +3004,7 @@ describe("Codex ACPX runtime adapter", () => { const runtime = fakeRuntime(); await expect( - openCodexAcpxRuntime(openOptions(command), { + openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderExit: providerOwnershipEstablished, @@ -3037,7 +3037,7 @@ describe("Codex ACPX runtime adapter", () => { const controller = new AbortController(); const cancellation = new Error("runtime admission cancelled"); - const opening = openCodexAcpxRuntime( + const opening = openQualifiedAcpxRuntime( { ...openOptions(command), signal: controller.signal }, { createRegistry: () => registry(), @@ -3099,7 +3099,7 @@ describe("Codex ACPX runtime adapter", () => { const cancellation = new Error("runtime admission cancelled"); let runtimeOptions: AcpRuntimeOptions | undefined; - const opening = openCodexAcpxRuntime( + const opening = openQualifiedAcpxRuntime( { ...openOptions(fakeCommand()), signal: controller.signal, @@ -3154,7 +3154,7 @@ describe("Codex ACPX runtime adapter", () => { const cancellation = new Error("runtime admission cancelled"); const retainedAdmissionCleanups: Promise[] = []; - const opening = openCodexAcpxRuntime( + const opening = openQualifiedAcpxRuntime( { ...openOptions(fakeCommand()), signal: controller.signal, @@ -3202,7 +3202,7 @@ describe("Codex ACPX runtime adapter", () => { const cancellation = new Error("runtime admission cancelled"); const retainedCleanups: Promise[] = []; - const opening = openCodexAcpxRuntime( + const opening = openQualifiedAcpxRuntime( { ...openOptions(fakeCommand()), signal: controller.signal }, { createRegistry: () => registry(), @@ -3257,7 +3257,7 @@ describe("Codex ACPX runtime adapter", () => { const cancellation = new Error("runtime admission cancelled"); let runtimeOptions: AcpRuntimeOptions | undefined; - const opening = openCodexAcpxRuntime( + const opening = openQualifiedAcpxRuntime( { ...openOptions(fakeCommand()), signal: controller.signal, @@ -3319,7 +3319,7 @@ describe("Codex ACPX runtime adapter", () => { const retainedCleanups: Promise[] = []; let runtimeOptions: AcpRuntimeOptions | undefined; - const opening = openCodexAcpxRuntime( + const opening = openQualifiedAcpxRuntime( { ...openOptions(fakeCommand()), signal: controller.signal, @@ -3383,7 +3383,7 @@ describe("Codex ACPX runtime adapter", () => { const cancellation = new Error("runtime admission cancelled"); let runtimeOptions: AcpRuntimeOptions | undefined; - const opening = openCodexAcpxRuntime( + const opening = openQualifiedAcpxRuntime( { ...openOptions(fakeCommand()), signal: controller.signal }, { createRegistry: () => registry(), @@ -3435,7 +3435,7 @@ describe("Codex ACPX runtime adapter", () => { const cancellation = new Error("runtime admission cancelled"); let runtimeOptions: AcpRuntimeOptions | undefined; - const opening = openCodexAcpxRuntime( + const opening = openQualifiedAcpxRuntime( { ...openOptions(fakeCommand()), signal: controller.signal, @@ -3493,7 +3493,7 @@ describe("Codex ACPX runtime adapter", () => { const runtime = fakeRuntime(); const retainedCleanups: Promise[] = []; - const result = openCodexAcpxRuntime(openOptions(command), { + const result = openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderExit: providerOwnershipEstablished, @@ -3541,7 +3541,7 @@ describe("Codex ACPX runtime adapter", () => { const retainedCleanups: Promise[] = []; await expect( - openCodexAcpxRuntime(openOptions(command), { + openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderExit: providerOwnershipEstablished, @@ -3579,7 +3579,7 @@ describe("Codex ACPX runtime adapter", () => { const failure = new Error("recovered ACP handshake rejected"); await expect( - openCodexAcpxRuntime(openOptions(fakeCommand()), { + openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => recoveredStore, createRuntime: (runtimeOptions) => { @@ -3627,7 +3627,7 @@ describe("Codex ACPX runtime adapter", () => { vi.mocked(failingStore.save).mockRejectedValue(failure); await expect( - openCodexAcpxRuntime(openOptions(fakeCommand()), { + openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => failingStore, createRuntime: (runtimeOptions) => { @@ -3674,7 +3674,7 @@ describe("Codex ACPX runtime adapter", () => { ); await expect( - openCodexAcpxRuntime(openOptions(command), { + openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderExit: providerOwnershipEstablished, @@ -3731,7 +3731,7 @@ describe("Codex ACPX runtime adapter", () => { const retainedCleanups: Promise[] = []; await expect( - openCodexAcpxRuntime(openOptions(fakeCommand()), { + openQualifiedAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), runtimeCloseTimeoutMs: 1, @@ -3780,7 +3780,7 @@ describe("Codex ACPX runtime adapter", () => { const command = fakeCommand(); const child = failingSignalChild(); vi.mocked(command.spawn).mockReturnValue(child.child); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -3817,7 +3817,7 @@ describe("Codex ACPX runtime adapter", () => { const child = fakeChild(); const providerError = new Error("provider spawn failed"); vi.mocked(command.spawn).mockReturnValue(child); - const port = await openCodexAcpxRuntime(openOptions(command), { + const port = await openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership: providerOwnershipEstablished, @@ -3879,7 +3879,7 @@ describe("Codex ACPX runtime adapter", () => { return HANDLE; }); - const opening = openCodexAcpxRuntime(openOptions(command), { + const opening = openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), awaitProviderOwnership, @@ -3907,7 +3907,7 @@ describe("Codex ACPX runtime adapter", () => { const runtime = fakeRuntime(); await expect( - openCodexAcpxRuntime(openOptions(command), { + openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), sessionHandshakeTimeoutMs: 1, @@ -3948,7 +3948,7 @@ describe("Codex ACPX runtime adapter", () => { ); await expect( - openCodexAcpxRuntime(openOptions(command), { + openQualifiedAcpxRuntime(openOptions(command), { createRegistry: () => registry(), createStore: () => store(), sessionHandshakeTimeoutMs: 1, diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts index 929fccf4c4c..dbe75691181 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts @@ -198,9 +198,6 @@ export interface QualifiedAcpxRuntimeDependencies { platform?: NodeJS.Platform; } -/** @deprecated Use QualifiedAcpxRuntimeDependencies for provider-neutral ACPX runtimes. */ -export type CodexAcpxRuntimeDependencies = QualifiedAcpxRuntimeDependencies; - /** * Adapt the pinned ACPX library to Paperclip's admitted runtime port. The * executable, launch environment, and spawn cwd stay host-owned and are never @@ -866,9 +863,6 @@ export async function openQualifiedAcpxRuntime( } } -/** Backward-compatible name retained for existing Codex-only consumers. */ -export const openCodexAcpxRuntime = openQualifiedAcpxRuntime; - function classifySessionEnsureFailure(error: unknown, providerFailure: ProviderFailure | null): Error { const failure = error instanceof Error ? error : Object.assign(new Error("ACPX session ensure rejected a non-error"), { code: "ACPX_SESSION_ENSURE_NON_ERROR" }); diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.ts b/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.ts index da8f07e34bf..fb26b126cd0 100644 --- a/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.ts +++ b/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.ts @@ -67,7 +67,7 @@ import { import { DEFAULT_CODEX_ACPX_RUNTIME_SHUTDOWN_BOUND_MS, AcpxProviderProcessLostError, - openCodexAcpxRuntime, + openQualifiedAcpxRuntime, } from "./acpx-runtime-adapter.js"; import { normalizeAcpxPermission } from "./acp-permission-adapter.js"; import { @@ -276,7 +276,7 @@ function openProductionAcpxHost( options: OpenAcpxRuntimeHostOptions, ): Promise { return AcpxRuntimeHost.open(options, { - openRuntime: openCodexAcpxRuntime, + openRuntime: openQualifiedAcpxRuntime, reportRetainedCleanupFailure: reportRetainedAcpxCleanupFailure, }); } diff --git a/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test.ts b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test.ts index 7c4e66acd9b..6f9b02e4233 100644 --- a/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test.ts @@ -11,7 +11,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { copyOwnedNodeRuntime } from "../../test-support/owned-node-runtime.js"; import { awaitVerifiedAcpxProviderExit, awaitVerifiedAcpxProviderOwnership, verifyNativeAcpxInstallation } from "./installation-integrity.js"; import { createNativeAcpxDistributionSnapshot, readNativeAcpxDistributionEntries, parseNativeAcpxDistributionEntries, type NativeAcpxDistributionInput, type NativeAcpxDistributionEntry } from "./native-distribution-integrity.js"; -import { openCodexAcpxRuntime } from "./acpx-runtime-adapter.js"; +import { openQualifiedAcpxRuntime } from "./acpx-runtime-adapter.js"; import { createAcpxCommandLeaseOwner } from "./command-lease-owner.js"; import { resolveQualifiedAcpxProfile } from "./qualified-profiles.js"; @@ -688,10 +688,10 @@ describe("native ACPX execution closure", () => { const installation = await verifyNativeAcpxInstallation(declaration); const owner = createAcpxCommandLeaseOwner(await installation.openCommand(), signal => installation.openCommand({ signal })); const pidFile = join(declaration.distributionRoot, "native-pid"); - let port: Awaited> | undefined; + let port: Awaited> | undefined; let deadline: ReturnType | undefined; try { - port = await openCodexAcpxRuntime({ + port = await openQualifiedAcpxRuntime({ command: owner.command, refreshConsumedCommand: owner.refreshConsumedCommand, profile: resolveQualifiedAcpxProfile("copilot", "gpt-5.6-luna"), cwd: declaration.distributionRoot, stateDirectory: join(declaration.distributionRoot, "state"), diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts index 86bbccaa142..26331441036 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts @@ -20,7 +20,7 @@ import { type NativeRuntimeContextSnapshot, } from "../../contracts/runtime-context.js"; import { releaseMaterializedNativeRuntimeSkills } from "../runtime-context-materializer.js"; -import { openCodexAcpxRuntime } from "./acpx-runtime-adapter.js"; +import { openQualifiedAcpxRuntime } from "./acpx-runtime-adapter.js"; import { acpxSidecarErrorCode } from "../../cli/acpx-sidecar-input.js"; import { stageManagedCodexCredential } from "./codex-credentials.js"; import type { @@ -949,7 +949,7 @@ describe("ACPX runtime host", () => { // staged credential to that pending admission. Abort before entering the // adapter so its pre-entry path must publish a completed cleanup proof. controller.abort(cancellation); - return openCodexAcpxRuntime(options, { createRuntime }); + return openQualifiedAcpxRuntime(options, { createRuntime }); }); await expect( diff --git a/packages/plugins/sdk/README.md b/packages/plugins/sdk/README.md index b8d01e0c5ce..6f6f0cb6540 100644 --- a/packages/plugins/sdk/README.md +++ b/packages/plugins/sdk/README.md @@ -302,9 +302,7 @@ Adds a navigation-style entry to the main company sidebar navigation area, rende #### `routeSidebar` -A contextual sidebar shown while the current route is a plugin page route with the same `routePath`. Use this for full-page plugin workspaces that need their own local navigation. It does **not** replace the app sidebar: the host collapses the main `` to its 64px icon rail (still hover/peek-able) and renders your `routeSidebar` in a secondary pane beside it, producing `[ app rail ][ your sidebar ][ content ]`. Receives `PluginRouteSidebarProps` with `context.companyId` and `context.companyPrefix` set to the active company. Requires the `ui.sidebar.register` capability. - -Do **not** mount `RequestCollapsedSidebar` (or otherwise try to collapse the app sidebar) from a `routeSidebar` plugin — the host drives the collapse automatically while your route is active and restores the user's preference when they navigate away. The collapse is a hard invariant: a secondary sidebar always forces the app rail collapsed (hiding its expand toggle), overriding any user pin, but it never mutates the user's saved expanded/collapsed preference — that is restored as soon as they leave your route. +A contextual sidebar shown while the current route is a plugin page route with the same `routePath`. Use this for full-page plugin workspaces that need their own local navigation. The host displays it in the sidebar area using the active app layout. Receives `PluginRouteSidebarProps` with `context.companyId` and `context.companyPrefix` set to the active company. Requires the `ui.sidebar.register` capability. #### `sidebarPanel` diff --git a/scripts/check-no-git-push.mjs b/scripts/check-no-git-push.mjs index 7254f6cafed..58394e59113 100644 --- a/scripts/check-no-git-push.mjs +++ b/scripts/check-no-git-push.mjs @@ -50,8 +50,6 @@ export const GIT_PUSH_PATTERNS = [ /\bgit[\s_-]+push\b/i, /["'`]git["'`]\s*,\s*\[?\s*["'`]push["'`]/i, ]; -// Kept for backwards-compatibility with existing tests/importers. -export const GIT_PUSH_PATTERN = GIT_PUSH_PATTERNS[0]; export const ALLOW_MARKER = "paperclip:allow-git-push"; function lineMatchesGitPush(line) { diff --git a/scripts/check-no-git-push.test.mjs b/scripts/check-no-git-push.test.mjs index b7917783603..e435d6c13d3 100644 --- a/scripts/check-no-git-push.test.mjs +++ b/scripts/check-no-git-push.test.mjs @@ -6,25 +6,24 @@ import test from "node:test"; import { ALLOW_MARKER, - GIT_PUSH_PATTERN, collectScannableFiles, findGitPushOffenses, runCheck, } from "./check-no-git-push.mjs"; test("regex matches common git push forms", () => { - assert.ok(GIT_PUSH_PATTERN.test("git push")); - assert.ok(GIT_PUSH_PATTERN.test("GIT PUSH")); - assert.ok(GIT_PUSH_PATTERN.test("git push origin master")); - assert.ok(GIT_PUSH_PATTERN.test("git-push")); - assert.ok(GIT_PUSH_PATTERN.test("git_push")); + assert.equal(findGitPushOffenses("git push").length, 1); + assert.equal(findGitPushOffenses("GIT PUSH").length, 1); + assert.equal(findGitPushOffenses("git push origin master").length, 1); + assert.equal(findGitPushOffenses("git-push").length, 1); + assert.equal(findGitPushOffenses("git_push").length, 1); }); test("regex ignores unrelated `push` usages", () => { - assert.ok(!GIT_PUSH_PATTERN.test("args.push('git')")); - assert.ok(!GIT_PUSH_PATTERN.test("notes.push('git remote')")); - assert.ok(!GIT_PUSH_PATTERN.test("pushed")); - assert.ok(!GIT_PUSH_PATTERN.test("git fetch")); + assert.equal(findGitPushOffenses("args.push('git')").length, 0); + assert.equal(findGitPushOffenses("notes.push('git remote')").length, 0); + assert.equal(findGitPushOffenses("pushed").length, 0); + assert.equal(findGitPushOffenses("git fetch").length, 0); }); test("findGitPushOffenses flags a bare invocation in a string", () => { diff --git a/server/scripts/smoke-native-task-monitor.ts b/server/scripts/smoke-native-task-monitor.ts index 0231bdba098..e8ada8d2862 100644 --- a/server/scripts/smoke-native-task-monitor.ts +++ b/server/scripts/smoke-native-task-monitor.ts @@ -30,7 +30,7 @@ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); const address = server.address(); if (!address || typeof address === "string") throw new Error("TCP listener missing"); process.env.PAPERCLIP_API_URL = `http://127.0.0.1:${address.port}`; -setupRunnerPrpWebSocketServer(server, { apiUrl: process.env.PAPERCLIP_API_URL }); +setupRunnerPrpWebSocketServer(server); const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); const heartbeat = heartbeatService(db); const lifecycle = startAgentLifecycle(db, createLifecycleDriver(db, createPluginWorkerManager()), () => true); diff --git a/server/src/__tests__/ai-connections.test.ts b/server/src/__tests__/ai-connections.test.ts index b914c4b75ac..8e12493de88 100644 --- a/server/src/__tests__/ai-connections.test.ts +++ b/server/src/__tests__/ai-connections.test.ts @@ -1902,6 +1902,7 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello" await create(userId, "Another API"); await expect(service.select({ ...input, userId })).rejects.toThrow("Reconnect"); await service.setDefault(companyId, userId, subscription.grantId); + expect(await db.select().from(aiConnectionDefaults).where(eq(aiConnectionDefaults.userId, userId))).toEqual([]); expect((await service.select({ ...input, userId })).attribution).toMatchObject({ method: "subscription", grantId: subscription.grantId }); expect((await service.list(companyId, userId)).filter(account => account.isDefault)).toHaveLength(1); await expect(service.select({ ...input, userId, binding: { ...binding, mode: "delegated", ...subscription } })).rejects.toThrow("incompatible"); @@ -1913,7 +1914,10 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello" const api = await create(userId, "Migration API"); const subscription = await service.save(companyId, userId, { provider: "anthropic", method: "subscription", ownership: "personal", name: "Migration subscription", loginSessionId: "fixture", allAgents: true, agentIds: [] }, "fixture-migration-subscription"); await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, api.grantId)); - await db.update(aiConnectionDefaults).set({ updatedAt: new Date("2030-01-01") }).where(eq(aiConnectionDefaults.grantId, api.grantId)); + await db.insert(aiConnectionDefaults).values([ + { companyId, userId, provider: "anthropic", method: "api_key", grantId: api.grantId, updatedAt: new Date("2030-01-01") }, + { companyId, userId, provider: "anthropic", method: "subscription", grantId: subscription.grantId }, + ]); await db.delete(aiProviderDefaults).where(and(eq(aiProviderDefaults.companyId, companyId), eq(aiProviderDefaults.userId, userId))); const legacyRows = await db.select().from(aiConnectionDefaults).where(eq(aiConnectionDefaults.userId, userId)); const migration = await readFile(new URL("../../../packages/db/src/migrations/0277_uneven_lady_deathstrike.sql", import.meta.url), "utf8"); @@ -1930,6 +1934,10 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello" const api = await create(userId, "Rolling API"); const subscription = await service.save(companyId, userId, { provider: "anthropic", method: "subscription", ownership: "personal", name: "Rolling subscription", loginSessionId: "fixture", allAgents: true, agentIds: [] }, "fixture-rolling-subscription"); expect((await service.select({ ...input, userId })).grant.id).toBe(api.grantId); + await db.insert(aiConnectionDefaults).values([ + { companyId, userId, provider: "anthropic", method: "api_key", grantId: api.grantId }, + { companyId, userId, provider: "anthropic", method: "subscription", grantId: subscription.grantId }, + ]); // An older server updates only the legacy per-method row on Make default. await db.update(aiConnectionDefaults).set({ grantId: subscription.grantId, updatedAt: new Date() }) .where(and(eq(aiConnectionDefaults.userId, userId), eq(aiConnectionDefaults.method, "subscription"))); diff --git a/server/src/__tests__/case-handoff-native.integration.test.ts b/server/src/__tests__/case-handoff-native.integration.test.ts index 84cfd883ba4..1d4ec147790 100644 --- a/server/src/__tests__/case-handoff-native.integration.test.ts +++ b/server/src/__tests__/case-handoff-native.integration.test.ts @@ -57,7 +57,7 @@ suite("case handoff through the assembled native runner", () => { await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); const apiUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; process.env.PAPERCLIP_API_URL = apiUrl; - setupRunnerPrpWebSocketServer(server, { apiUrl }); + setupRunnerPrpWebSocketServer(server); }, 30_000); afterAll(async () => { if (db) { diff --git a/server/src/__tests__/dot-runner.test.ts b/server/src/__tests__/dot-runner.test.ts index 1153b853e45..97870df2b78 100644 --- a/server/src/__tests__/dot-runner.test.ts +++ b/server/src/__tests__/dot-runner.test.ts @@ -993,7 +993,7 @@ describe("durable Dot Runner integration", () => { await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, run!.id)); const server = createServer(); await new Promise(done => server.listen(0, "127.0.0.1", done)); const address = server.address(); if (!address || typeof address === "string") throw new Error("Missing test server"); - setupRunnerPrpWebSocketServer(server, { apiUrl: `http://127.0.0.1:${address.port}` }); + setupRunnerPrpWebSocketServer(server); const observed: Array> = []; const appCall = vi.fn().mockResolvedValue({ status: "completed", result: { content: [{ type: "text", text: "synthetic gateway result" }] } }); const gatewayTools = [{ name: "fixture:read_status", displayName: "Read fixture status", description: "Read a synthetic app", parametersSchema: { type: "object", properties: {}, additionalProperties: false }, risk: "read" }]; diff --git a/server/src/__tests__/helpers/historical-listener-continuation.ts b/server/src/__tests__/helpers/historical-listener-continuation.ts index 332003b42ee..2350922ec80 100644 --- a/server/src/__tests__/helpers/historical-listener-continuation.ts +++ b/server/src/__tests__/helpers/historical-listener-continuation.ts @@ -103,7 +103,7 @@ export async function completeHistoricalListenerSuccessor(input: { db: Db; runId await new Promise(resolveListen => server.listen(0, "127.0.0.1", resolveListen)); const address = server.address(); if (!address || typeof address === "string") throw new Error("TCP listener required"); - setupRunnerPrpWebSocketServer(server, { apiUrl: `http://127.0.0.1:${address.port}` }); + setupRunnerPrpWebSocketServer(server); const bundle = createRunnerdCodexTransport({ runnerBinary: defaultCapabilityRunnerdBinary(), codexCommand: resolve(import.meta.dirname, "../../../../packages/paperclip-runner/runner/target/debug/fake-codex-app-server"), codexArgs: ["--state-file", join(input.root, "provider.json"), "--terminal-result-file", report, "--call-log", calls, "--record-process-start"], diff --git a/server/src/__tests__/helpers/native-restart-fixture.ts b/server/src/__tests__/helpers/native-restart-fixture.ts index 6c3b382e959..78ba00dafbe 100644 --- a/server/src/__tests__/helpers/native-restart-fixture.ts +++ b/server/src/__tests__/helpers/native-restart-fixture.ts @@ -112,7 +112,7 @@ export function nativeRestartFixture(options: { dedicatedDatabaseUrl?: string } throw new Error("Expected restart recovery TCP listener"); } apiUrl = `http://127.0.0.1:${address.port}`; - setupRunnerPrpWebSocketServer(server, { apiUrl }); + setupRunnerPrpWebSocketServer(server); const db = createDb(temporary.connectionString); try { diff --git a/server/src/__tests__/helpers/runner-api-server.ts b/server/src/__tests__/helpers/runner-api-server.ts index 349ca88ada7..521483b0fc9 100644 --- a/server/src/__tests__/helpers/runner-api-server.ts +++ b/server/src/__tests__/helpers/runner-api-server.ts @@ -58,7 +58,7 @@ export async function startRunnerApiTestServer(options: { const address = http.address(); if (!address || typeof address === "string") throw new Error("Missing eval listener"); const apiUrl = `http://127.0.0.1:${address.port}`; - setupRunnerPrpWebSocketServer(http, { apiUrl }); + setupRunnerPrpWebSocketServer(http); return { databaseUrl: temporary.connectionString, db, root, apiUrl, storage, diff --git a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts index c5e7342b877..f562c0a16e9 100644 --- a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts +++ b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts @@ -944,14 +944,12 @@ describe("agent issue mutation checkout ownership", () => { }); it.each([ - { owner: "another-user", enabled: true, status: 403 }, - { owner: "board-user", enabled: false, status: 404 }, - { owner: "board-user", enabled: true, status: 202 }, - ])("gates Agent Chat task Retry by owner and feature ($owner, $enabled)", async ({ owner, enabled, status }) => { + { owner: "another-user", status: 403 }, + { owner: "board-user", status: 202 }, + ])("gates Agent Chat task Retry by owner ($owner)", async ({ owner, status }) => { mockIssueService.getById.mockResolvedValue(makeIssue({ conversationAgentId: ownerAgentId, conversationUserId: owner, })); - mockGetExperimental.mockResolvedValue({ enableAgentChat: enabled }); const response = await request(createApp(boardActor())).post(`/api/issues/${issueId}/retry`).send({ idempotencyKey: recoveryActionId, observedRunId: ownerRunId, }); diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index 1803aab486a..b3bbe973f9d 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -13,7 +13,6 @@ import { readRunCancellation } from "../../../services/run-cancellation.js"; import { withRunRedactionHistory } from "../../../services/run-secret-redaction.js"; import { CHAT_COMPLETION_WAKE_REASON, isCompletedOnboardingHandoffWake, settleReportedChatCompletions } from "../../../services/chat-completion-delivery.js"; import { earlierDeclinedOutcomeReply } from "../../../services/chat-interaction-outcome-report.js"; -import { instanceSettingsService } from "../../../services/instance-settings.js"; import { currentConversationCommentCondition } from "../../../services/agent-conversations.js"; import { getExecutionBlocker, hasPendingRunCleanup } from "../../../services/execution-blocker.js"; import { nativeManualAdmissionHoldsExecution } from "../../../services/native-runtime/native-runner-ownership.js"; @@ -1516,13 +1515,6 @@ export function createPostgresWakeQueueAdapter(db: Db, deps: WakeQueuePostgresAd return { outcome: { kind: "released" }, postCommitEffects: [], run: runSnapshot }; } - // Releases still settle while Agent Chat is disabled, but no deferred - // turn or recovery successor may be created. Check here in the shared - // transaction so cleanup retries and restart sweeps use the same gate. - if (issueRow.conversationAgentId && !(await instanceSettingsService(tx).getExperimental()).enableAgentChat) { - return { outcome: { kind: "released" }, postCommitEffects: [], run: runSnapshot }; - } - const locked: LockedIssueExecution = { primaryIssue: toIssueSnapshot(issueRow), run: runSnapshot, recoveryOnly: recoveryOnly && !handoffAssigneeAgentId, ...(handoffAssigneeAgentId ? { handoffAssigneeAgentId } : {}) }; const result = await fn(locked, { host: buildHost(tx, deps), transaction: buildTransaction(tx, deps, db, run) }); diff --git a/server/src/realtime/runner-prp-ws.ts b/server/src/realtime/runner-prp-ws.ts index f1dbefcd48c..f7ab28d4d75 100644 --- a/server/src/realtime/runner-prp-ws.ts +++ b/server/src/realtime/runner-prp-ws.ts @@ -68,12 +68,7 @@ function rejectUpgrade( } } -export function setupRunnerPrpWebSocketServer( - server: Server, - _options?: { readonly apiUrl: string }, -): void { - // Older launchers may still pass an advertised apiUrl. Only the actual - // bound listener can authorize native transport, including ephemeral ports. +export function setupRunnerPrpWebSocketServer(server: Server): void { registerLocalRuntimeApiServer(server); server.on( "upgrade", diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 386acf2b0bf..59771b00bf1 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -9757,7 +9757,6 @@ export function issueRoutes( if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision)); // An Agent Chat run starts only for the conversation's owner. if (issue.conversationAgentId) { - if (!(await instanceSettings.getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled"); if (req.actor.userId !== issue.conversationUserId) throw forbidden("Only the conversation owner can compact a chat agent's context"); } @@ -10443,7 +10442,6 @@ export function issueRoutes( const decision = await decideIssueAccess(req, issue, "issue:mutate"); if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision)); if (issue.conversationAgentId) { - if (!(await instanceSettings.getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled"); if (!req.actor.userId || req.actor.userId !== issue.conversationUserId) throw forbidden("Only the conversation owner can retry a chat run"); } @@ -17950,7 +17948,6 @@ export function issueRoutes( const decision = await decideIssueAccess(req, issue, "issue:comment"); if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision)); if (issue.conversationAgentId) { - if (!(await instanceSettings.getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled"); if (req.actor.userId !== issue.conversationUserId) { throw forbidden("Only the conversation owner can interrupt a chat to send queued messages"); } @@ -19886,7 +19883,6 @@ export function issueRoutes( const companyId = req.params.companyId as string; assertCompanyAccess(req, companyId); if (req.actor.type !== "board" || !req.actor.userId) throw forbidden("Board user access required"); - if (!(await instanceSettings.getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled"); const conversations = await svc.listConversations(companyId, req.actor.userId); res.json(await withConversationReadState(db, companyId, req.actor.userId, await filterIssuesForActor(req, conversations))); }); @@ -19897,7 +19893,6 @@ export function issueRoutes( const companyId = req.params.companyId as string; assertCompanyAccess(req, companyId); if (req.actor.type !== "board" || !req.actor.userId) throw forbidden("Board user access required"); - if (!(await instanceSettings.getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled"); const resolved = await agentsSvc.resolveByReference(companyId, req.params.agentRef as string); if (resolved.ambiguous) throw conflict("Agent reference is ambiguous"); if (!resolved.agent) throw notFound("Agent not found"); @@ -19933,7 +19928,6 @@ export function issueRoutes( ); if (!issue) return; if (issue.conversationAgentId && req.actor.type === "board") { - if (!(await instanceSettings.getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled"); if (!req.actor.userId) throw forbidden("Board user access required"); if (req.actor.userId !== issue.conversationUserId) throw forbidden("Only the conversation owner can send messages or start a new session"); if (!req.body.clientRequestId) throw unprocessable("Chat messages require a clientRequestId for safe retries"); @@ -21149,9 +21143,6 @@ export function issueRoutes( res.status(422).json({ error: "Issue does not belong to company" }); return; } - if (issue.conversationAgentId && req.actor.type === "board" && !(await instanceSettings.getExperimental()).enableAgentChat) { - throw notFound("Agent Chat is disabled"); - } if (issue.conversationAgentId && req.actor.type === "board" && req.actor.userId !== issue.conversationUserId) { throw forbidden("Only the conversation owner can upload attachments"); } diff --git a/server/src/services/agent-chat-messages.ts b/server/src/services/agent-chat-messages.ts index c857ca914aa..c3a310e6d51 100644 --- a/server/src/services/agent-chat-messages.ts +++ b/server/src/services/agent-chat-messages.ts @@ -2,11 +2,10 @@ import { createHash } from "node:crypto"; import { and, eq, isNull, sql } from "drizzle-orm"; import { agentApiKeys, agents, companies, companyMemberships, heartbeatRuns, issueComments, issues, nativeRunResults, type Db } from "@paperclipai/db"; import { agentApiKeyScopeSchema, isUuidLike, sendChatMessageSchema, type AgentApiKeyScope } from "@paperclipai/shared"; -import { badRequest, conflict, forbidden, notFound, tooManyRequests } from "../errors.js"; +import { badRequest, conflict, forbidden, tooManyRequests } from "../errors.js"; import { agentRunWritesRevoked, assertAgentRunWriteAllowed } from "../agent-run-cancellation.js"; import { authorizationService, canActorReadIssuePrivacy, type AuthorizationActor } from "./authorization.js"; import { persistActivity, publishActivity, type ActivityPublication } from "./activity-log.js"; -import { instanceSettingsService } from "./instance-settings.js"; import { issueService } from "./issues.js"; import { issueTreeControlService } from "./issue-tree-control.js"; import { resolveActorSourceTrustForIssue } from "./source-trust.js"; @@ -78,7 +77,6 @@ export async function sendAgentChatMessage( }; const [initialContext] = await contextQuery(); const context = validateContext(initialContext); - if (!(await instanceSettingsService(tx).getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled"); const userId = context.run.responsibleUserId; if (!userId) throw forbidden("This task has no responsible human to receive the message"); if (actor.onBehalfOfUserId !== undefined && actor.onBehalfOfUserId !== userId) throw forbidden("The authenticated responsible human no longer matches this run"); @@ -144,7 +142,6 @@ export async function sendAgentChatMessage( eq(nativeRunResults.companyId, actor.companyId), eq(nativeRunResults.runId, actor.runId), eq(nativeRunResults.schemaStatus, "accepted"), )).limit(1); if (finished) throw forbidden("Send the message before finishing the run"); - if (!(await instanceSettingsService(tx).getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled"); await authorize(source.id, "issue:read"); if (!conversation) return null; await authorize(conversation.id, "issue:comment"); diff --git a/server/src/services/ai-connections.ts b/server/src/services/ai-connections.ts index 04964272014..a8a2ec35329 100644 --- a/server/src/services/ai-connections.ts +++ b/server/src/services/ai-connections.ts @@ -10,7 +10,6 @@ import { type Db, authUsers, adapterAuthSessions, - aiConnectionDefaults, aiProviderDefaults, agents, heartbeatRuns, @@ -211,13 +210,6 @@ export function aiConnectionService(db: Db) { ); const metadata = aiConnectionMetadataSchema.parse(row.connection.config.ai); if (metadata.routing) throw unprocessable("Custom providers use an explicit connection selection on the agent."); - // Keep old servers' method preferences intact during an additive rollout. - await tx.insert(aiConnectionDefaults) - .values({ companyId, userId, ...metadata, grantId }) - .onConflictDoUpdate({ - target: [aiConnectionDefaults.companyId, aiConnectionDefaults.userId, aiConnectionDefaults.provider, aiConnectionDefaults.method], - set: { grantId, updatedAt: new Date() }, - }); await tx.insert(aiProviderDefaults) .values({ companyId, userId, provider: metadata.provider, grantId }) .onConflictDoUpdate({ @@ -923,16 +915,6 @@ export function aiConnectionService(db: Db) { .where(eq(toolConnections.id, id)); await syncConnectionCredentialBindings(tx, savedConnection, refs); if (input.ownership === "personal" && !routing) { - await tx - .insert(aiConnectionDefaults) - .values({ - companyId, - userId, - provider: input.provider, - method: input.method, - grantId, - }) - .onConflictDoNothing(); await tx.insert(aiProviderDefaults).values({ companyId, userId, provider: input.provider, grantId }).onConflictDoNothing(); } if (!reconnect) { diff --git a/server/src/services/chat-completion-delivery.ts b/server/src/services/chat-completion-delivery.ts index 6c39dbca92e..c9df7255995 100644 --- a/server/src/services/chat-completion-delivery.ts +++ b/server/src/services/chat-completion-delivery.ts @@ -6,7 +6,6 @@ import { agents, agentWakeupRequests, chatCompletionDeliveries as deliveries, ch heartbeatRunEvents, heartbeatRuns, issueComments, issueDocuments, issueThreadInteractions, issues, type Db } from "@paperclipai/db"; import { extractIssueReferenceMatches } from "@paperclipai/shared"; import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js"; -import { instanceSettingsService } from "./instance-settings.js"; import { conflict, forbidden, notFound } from "../errors.js"; export const CHAT_COMPLETION_WAKE_REASON = "chat_task_completed"; @@ -318,7 +317,6 @@ export function chatCompletionDeliveryService(db: Db, heartbeat: { wakeup(agentI if (!row || !current(row)) { await db.update(deliveries).set({ status: "superseded" }).where(eq(deliveries.id, id)); return; } - if (!(await instanceSettingsService(db).getExperimental()).enableAgentChat) return; const [agent] = await db.select().from(agents).where(and(eq(agents.id, row.handoff.agentId), eq(agents.companyId, claimed.companyId))); if (!agent || ["paused", "terminated"].includes(agent.status)) return; const key = `chat-completion:${id}:${claimed.attempts}`; diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index b381fc8d40b..da3b169aaf3 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -2238,13 +2238,6 @@ export function heartbeatService( ? await db.select({ conversationAgentId: issues.conversationAgentId, conversationUserId: issues.conversationUserId }) .from(issues).where(and(eq(issues.companyId, run.companyId), eq(issues.id, dispatchIssueId))).then(rows => rows[0] ?? null) : null; - if (isConversation(conversationIdentity) && !(await instanceSettings.getExperimental()).enableAgentChat) { - await setRunStatus(run.id, "cancelled", { finishedAt: new Date(), error: "Agent Chat is disabled", errorCode: "agent_chat_disabled" }); - await setWakeupStatus(run.wakeupRequestId, "cancelled", { finishedAt: new Date() }); - await releaseIssueExecutionAndPromote((await getRun(run.id))!, { suppressImmediateRecovery: true }); - await finalizeAgentStatus(agent.id, "cancelled"); - return; - } if (await deferRunForProviderLimit(run, agent, { resumingAdmittedRun: !!runOptions.nativeLeaseOwner, conversation: isConversation(conversationIdentity), diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index f104d29a928..84b38160dad 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -2859,7 +2859,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende if (reason === "issue_comment_mentioned" || enrichedContextSnapshot.wakeReason === "issue_comment_mentioned") return null; if (issueId) { const conversation = await getIssueExecutionContext(agent.companyId, issueId); - if (taskRetryActorId && conversation) await assertTaskRetryConversationAllowed(db, conversation, taskRetryActorId); + if (taskRetryActorId && conversation) assertTaskRetryConversationAllowed(conversation, taskRetryActorId); if (reason === "issue_children_completed" && conversation?.originKind === "onboarding_first_task") enrichedContextSnapshot.onboardingCompletion = true; if (isConversation(conversation)) { if (opts.manualUserWake && conversation!.conversationUserId !== opts.requestedByActorId) { @@ -2867,7 +2867,6 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende } if (isConversationExecutionWake(conversation, reason ?? readNonEmptyString(enrichedContextSnapshot.wakeReason))) return null; if (agent.id !== conversation!.conversationAgentId) return null; - if (!(await instanceSettings.getExperimental()).enableAgentChat) return null; if (isWaitingConversation(conversation) && !hasIndependentConversationWakeCause()) return null; } } @@ -3825,7 +3824,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende } if (taskRetryActorId) { - await assertTaskRetryConversationAllowed(tx as unknown as Db, issue, taskRetryActorId); + assertTaskRetryConversationAllowed(issue, taskRetryActorId); if (await retireSupersededTaskRetry(tx as unknown as Db, { companyId: issue.companyId, issueId: issue.id, requestId: opts.taskRetryRequestId!, sourceRunId: readNonEmptyString(enrichedContextSnapshot.previousRunId)!, diff --git a/server/src/services/heartbeat/run-control.ts b/server/src/services/heartbeat/run-control.ts index 3584d55ff43..dc4c6cb8c20 100644 --- a/server/src/services/heartbeat/run-control.ts +++ b/server/src/services/heartbeat/run-control.ts @@ -1,4 +1,3 @@ -import { instanceSettingsService } from "../instance-settings.js"; import { writeDeferredExecutionWait } from "../deferred-execution-wait.js"; import type { DeferredReceiptRecoveryOptions } from "../deferred-execution-notifications.js"; import { observeStoppedWorkspaceRecovery } from "../workspace-recovery.js"; @@ -947,8 +946,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont async function resumeExecutionWaitComments(scope: DeferredReceiptRecoveryOptions = {}) { if ((await getSchedulingSuppression()).suppressed) return; await reconcileTaskChatRetryReceipts(db, scope); - const retries = await db.select({ id: agentWakeupRequests.id, companyId: agentWakeupRequests.companyId, - conversationAgentId: issues.conversationAgentId }) + const retries = await db.select({ id: agentWakeupRequests.id, companyId: agentWakeupRequests.companyId }) .from(agentWakeupRequests).innerJoin(issues, and(eq(issues.companyId, agentWakeupRequests.companyId), sql`${issues.id}::text = ${agentWakeupRequests.payload}->>'issueId'`, eq(issues.assigneeAgentId, agentWakeupRequests.agentId))) @@ -960,13 +958,8 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont sql`${agentWakeupRequests.payload}->'taskRetry'->>'queuedChatRequestId' is null`, notInArray(issues.status, ["done", "cancelled"]))) .orderBy(asc(agentWakeupRequests.updatedAt)).limit(50); - const chatEnabled = !retries.some(retry => retry.conversationAgentId) - || (await instanceSettingsService(db).getExperimental()).enableAgentChat; for (const retry of retries) { - // Accepted chat work waits for the flag's committed eligibility signal. - // Public Retry still rejects new requests while the feature is disabled. await db.update(agentWakeupRequests).set({ updatedAt: new Date() }).where(eq(agentWakeupRequests.id, retry.id)); - if (retry.conversationAgentId && !chatEnabled) continue; await resumeTaskRetry(retry.companyId, retry.id).catch(err => { scope.onError?.(err); logger.warn({ err, requestId: retry.id }, "Task retry dispatch deferred"); }); diff --git a/server/src/services/instance-settings.ts b/server/src/services/instance-settings.ts index 8a30e8f2720..ad7e673d4ef 100644 --- a/server/src/services/instance-settings.ts +++ b/server/src/services/instance-settings.ts @@ -657,13 +657,10 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsService } } } - const chatBecameEnabled = !toExperimentalView(current.experimental).enableAgentChat - && toExperimentalView(nextExperimental).enableAgentChat; const now = new Date(); const [updated] = await db.transaction(async tx => { await announceInstanceSettingsChange(tx); if (patch.enableStatusCards !== undefined) await notifyStatusCardEvaluation(tx); - if (chatBecameEnabled) await notifyDeferredExecutionEligibility(tx); if (patch.enableMcpTasks !== undefined) await notifyDeliveryWork(tx, DELIVERY_QUEUES.mcpTasks); await notifyDeliveryWork(tx, DELIVERY_QUEUES.mcpIngressHandoffs); await notifyDeliveryWork(tx, DELIVERY_QUEUES.mcpClientMirror); @@ -673,7 +670,6 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsService await notifyDeliveryWork(tx, DELIVERY_QUEUES.grokDispatch); if (toExperimentalView(current.experimental).enableMuse !== toExperimentalView(nextExperimental).enableMuse || toExperimentalView(current.experimental).enableNativeRunner !== toExperimentalView(nextExperimental).enableNativeRunner) await notifyMuseContactVerification(tx); if (patch.enableExternalObjects !== undefined) await notifyExternalObjectRefresh(tx); - if (chatBecameEnabled) await notifyDeliveryWork(tx, DELIVERY_QUEUES.strandedAssignments, "*"); if (patch.enableWorktreeRunExecution !== undefined) await notifyScheduledRetryCancellation(tx); if (patch.enableWorktreeRunExecution !== undefined) { await notifyRunDispatch(tx); diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 3d14f402788..8ff17885260 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -13698,9 +13698,6 @@ export function issueService(db: Db) { if (!issue) throw notFound("Issue not found"); - if (issue.conversationAgentId && actor.userId && !(await instanceSettingsService(dbOrTx).getExperimental()).enableAgentChat) { - throw unprocessable("Agent Chat is disabled in Experimental settings"); - } await assertAgentInteraction(dbOrTx, { companyId: issue.companyId, actorAgentId: actor.agentId, operation: "comment", issueId, texts: [body], lock: true, diff --git a/server/src/services/native-runtime/native-codex-runner.integration.test.ts b/server/src/services/native-runtime/native-codex-runner.integration.test.ts index 13d8c73b71c..4a37f2c2996 100644 --- a/server/src/services/native-runtime/native-codex-runner.integration.test.ts +++ b/server/src/services/native-runtime/native-codex-runner.integration.test.ts @@ -102,9 +102,7 @@ describeEmbeddedPostgres("native Codex server vertical slice", () => { await new Promise((resolveListen) => server!.listen(0, "127.0.0.1", resolveListen)); const address = server.address(); if (!address || typeof address === "string") throw new Error("Expected a TCP listener"); - setupRunnerPrpWebSocketServer(server, { - apiUrl: `http://127.0.0.1:${address.port}`, - }); + setupRunnerPrpWebSocketServer(server); }, 660_000); afterAll(async () => { diff --git a/server/src/services/native-runtime/native-question-bridge.test.ts b/server/src/services/native-runtime/native-question-bridge.test.ts index 971ccc16ac5..2992b1e425b 100644 --- a/server/src/services/native-runtime/native-question-bridge.test.ts +++ b/server/src/services/native-runtime/native-question-bridge.test.ts @@ -263,7 +263,7 @@ describeEmbeddedPostgres("native question bridge", () => { const stateDirectory = mkdtempSync(join(tmpdir(), "native-permission-authority-")); const server = createServer(); await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); - setupRunnerPrpWebSocketServer(server, { apiUrl: "http://127.0.0.1:3213" }); + setupRunnerPrpWebSocketServer(server); const authority = new DurablePrpControlPlane({ stateDirectory, identity: { runnerInstanceId, environmentLeaseId: "lease-1", runId, normalizedSessionId: sessionId, turnId: "turn-1", itemId: "item-1" }, diff --git a/server/src/services/native-runtime/native-session-resume.test.ts b/server/src/services/native-runtime/native-session-resume.test.ts index 44feab70bd8..4f82fe98a7b 100644 --- a/server/src/services/native-runtime/native-session-resume.test.ts +++ b/server/src/services/native-runtime/native-session-resume.test.ts @@ -668,9 +668,7 @@ const recoveryFakeCodex = resolve( const address = server.address(); if (!address || typeof address === "string") throw new Error("Missing test listener"); - setupRunnerPrpWebSocketServer(server, { - apiUrl: `http://127.0.0.1:${address.port}`, - }); + setupRunnerPrpWebSocketServer(server); const makeExecution = (runId: string): NativeExecutionInput => { const { runtimeContext: _runtimeContext, ...value } = execution( runId, diff --git a/server/src/services/native-runtime/paperclip-runner-real-server.integration.test.ts b/server/src/services/native-runtime/paperclip-runner-real-server.integration.test.ts index 622ed0da3e4..ab3fbc32fee 100644 --- a/server/src/services/native-runtime/paperclip-runner-real-server.integration.test.ts +++ b/server/src/services/native-runtime/paperclip-runner-real-server.integration.test.ts @@ -84,9 +84,7 @@ describe("paperclip-runner real server vertical slice", () => { await new Promise((resolveListen) => server.listen(0, "127.0.0.1", resolveListen)); const address = server.address(); if (address === null || typeof address === "string") throw new Error("Expected a TCP listener."); - setupRunnerPrpWebSocketServer(server, { - apiUrl: `http://127.0.0.1:${address.port}`, - }); + setupRunnerPrpWebSocketServer(server); const stateDirectory = await mkdtemp(resolve(tmpdir(), "paperclip-runner-real-resume-")); const expectedContextFile = resolve(stateDirectory, "expected-context.json"); await writeFile(expectedContextFile, JSON.stringify({ companyId, actorId: agentId, taskId: issueId, runId, callId: "semantic-call-1" })); diff --git a/server/src/services/native-runtime/runner-prp-coordinator.test.ts b/server/src/services/native-runtime/runner-prp-coordinator.test.ts index d2336bc0746..687d45e2dc0 100644 --- a/server/src/services/native-runtime/runner-prp-coordinator.test.ts +++ b/server/src/services/native-runtime/runner-prp-coordinator.test.ts @@ -239,7 +239,7 @@ describeEmbeddedPostgres("hidden runner PRP coordinator", () => { await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); const address = server.address(); if (!address || typeof address === "string") throw new Error("Expected a bound TCP controller"); - setupRunnerPrpWebSocketServer(server, { apiUrl: "http://127.0.0.1:3213" }); + setupRunnerPrpWebSocketServer(server); const stateRoot = mkdtempSync(resolve(tmpdir(), "paperclip-runner-state-")); scratchDirectories.push(stateRoot); const coordinator = runnerPrpCoordinator(db, { stateRoot }); diff --git a/server/src/services/native-runtime/runtime-mode.test.ts b/server/src/services/native-runtime/runtime-mode.test.ts index b8089e6f25d..3ec2cce11cc 100644 --- a/server/src/services/native-runtime/runtime-mode.test.ts +++ b/server/src/services/native-runtime/runtime-mode.test.ts @@ -2,11 +2,9 @@ import { describe, expect, it } from "vitest"; import { BUILTIN_ADAPTER_TYPES } from "../../adapters/builtin-adapter-types.js"; import { - NativeRunnerSelectionError, NativeRuntimeEligibilityError, isRunnerIngressAuthorized, resolveHeartbeatNativeRuntimeMode, - resolveHeartbeatRuntimeMode, resolveNativeRuntimeMode, } from "./runtime-mode.js"; @@ -492,58 +490,26 @@ describe("resolveNativeRuntimeMode", () => { }); }); -const compatibilityInput = { - persisted: { runtimeMode: "legacy", runtimeModeResolvedAt: null }, - enabled: true, - adapterConfig: { provider: "codex" }, - agentStatus: "running", - issue: { workMode: "standard" }, - executionTarget: { kind: "local" }, -} as const; - -describe("resolveHeartbeatRuntimeMode compatibility", () => { +describe("resolveHeartbeatNativeRuntimeMode", () => { it("keeps every direct built-in adapter on the legacy path", () => { for (const adapterType of BUILTIN_ADAPTER_TYPES) { if (adapterType === "paperclip_runner") continue; - expect(resolveHeartbeatRuntimeMode({ - ...compatibilityInput, - adapterType, - })).toEqual({ - kind: "legacy", - resolverVersion: "paperclip-runner-v1", - reason: "direct_adapter", - }); + expect(resolveHeartbeatNativeRuntimeMode({ + ...eligible, + persisted: { runtimeMode: null, runtimeModeReason: null, runtimeModeResolvedAt: null }, + agent: { ...eligible.agent, adapterType }, + })).toMatchObject({ kind: "legacy", reason: "direct_adapter" }); } }); - it("preserves the original public result and error contracts", () => { - expect(resolveHeartbeatRuntimeMode({ - ...compatibilityInput, - adapterType: "paperclip_runner", - })).toEqual({ - kind: "native", - resolverVersion: "paperclip-runner-v1", - reason: "explicit_paperclip_runner", - provider: "codex", - }); - expect(resolveHeartbeatRuntimeMode({ - ...compatibilityInput, + it("recovers a persisted Codex run with no recorded driver kind", () => { + expect(resolveHeartbeatNativeRuntimeMode({ + ...eligible, enabled: false, - adapterType: "paperclip_runner", - persisted: { runtimeMode: "native", runtimeModeResolvedAt: new Date() }, - })).toEqual({ - kind: "native", - resolverVersion: "paperclip-runner-v1", - reason: "persisted_native_selection", - provider: "codex", - }); - expect(() => resolveHeartbeatRuntimeMode({ - ...compatibilityInput, - enabled: false, - adapterType: "paperclip_runner", - adapterConfig: { provider: "acpx", acpxAgent: "grok", model: "openrouter/anthropic/claude-sonnet-4.6" }, - })).toThrow(NativeRunnerSelectionError); + persisted: { runtimeMode: "native", runtimeModeReason: null, runtimeModeResolvedAt: new Date() }, + })).toMatchObject({ kind: "native", profile: { backend: "codex_app_server" } }); }); + it("admits native Claude without enabling other ACPX providers", () => { expect(resolveNativeRuntimeMode({ ...eligible, enabled: false, adapterConfig: { provider: "acpx", acpxAgent: "claude" } })).toMatchObject({ kind: "native", profile: { backend: "acpx_runtime" } }); expect(() => resolveNativeRuntimeMode({ ...eligible, enabled: false, adapterConfig: { provider: "acpx", acpxAgent: "grok" } })).toThrow(expect.objectContaining({ code: "paperclip_runner_rollout_disabled" })); diff --git a/server/src/services/native-runtime/runtime-mode.ts b/server/src/services/native-runtime/runtime-mode.ts index 255eb2e18b9..19e1167d276 100644 --- a/server/src/services/native-runtime/runtime-mode.ts +++ b/server/src/services/native-runtime/runtime-mode.ts @@ -19,19 +19,6 @@ export const NATIVE_RUNTIME_RESOLVER_VERSION = "paperclip-runner-v1" as const; /** Resolver version for the richer native runtime profile used by runnerd. */ export const NATIVE_RUNTIME_PROFILE_RESOLVER_VERSION = "phase6-v1" as const; -export type HeartbeatRuntimeResolution = - | { - kind: "legacy"; - resolverVersion: typeof NATIVE_RUNTIME_RESOLVER_VERSION; - reason: "direct_adapter" | "persisted_legacy_selection"; - } - | { - kind: "native"; - resolverVersion: typeof NATIVE_RUNTIME_RESOLVER_VERSION; - reason: "explicit_paperclip_runner" | "persisted_native_selection"; - provider: PaperclipRunnerProviderProfile["provider"]; - }; - export type NativeRuntimeResolution = | { kind: "legacy"; @@ -191,94 +178,6 @@ export function resolveNativeRuntimeMode(input: { }; } -/** - * Backward-compatible heartbeat selection API. New runnerd code consumes the - * richer profile from resolveHeartbeatNativeRuntimeMode; this public seam - * keeps the original result shape, reason codes, and resolver version. - */ -export function resolveHeartbeatRuntimeMode(input: { - persisted: { - runtimeMode: string | null; - runtimeModeResolvedAt: Date | null; - }; - enabled: boolean; - museEnabled?: boolean; - dotEnabled?: boolean; - grokEnabled?: boolean; - adapterType: string | null; - adapterConfig: unknown; - agentStatus: string; - issue: { workMode: string } | null; - executionTarget: { kind?: string } | null | undefined; -}): HeartbeatRuntimeResolution { - if (input.persisted.runtimeModeResolvedAt) { - if (input.persisted.runtimeMode === "native") { - return { - kind: "native", - resolverVersion: NATIVE_RUNTIME_RESOLVER_VERSION, - reason: "persisted_native_selection", - provider: "codex", - }; - } - return { - kind: "legacy", - resolverVersion: NATIVE_RUNTIME_RESOLVER_VERSION, - reason: "persisted_legacy_selection", - }; - } - - let resolution: NativeRuntimeResolution; - try { - resolution = resolveNativeRuntimeMode({ - enabled: input.enabled, - museEnabled: input.museEnabled, - dotEnabled: input.dotEnabled, - grokEnabled: input.grokEnabled, - runtimeConfig: {}, - adapterConfig: input.adapterConfig, - agent: { - status: input.agentStatus, - adapterType: input.adapterType, - }, - issue: input.issue - ? { id: "heartbeat-runtime-selection", workMode: input.issue.workMode } - : null, - target: input.executionTarget, - workspaceId: null, - }); - } catch (error) { - if (error instanceof NativeRuntimeEligibilityError) { - throw new NativeRunnerSelectionError(error.code, error.message); - } - throw error; - } - if (resolution.kind === "legacy") { - return { - kind: "legacy", - resolverVersion: NATIVE_RUNTIME_RESOLVER_VERSION, - reason: "direct_adapter", - }; - } - return { - kind: "native", - resolverVersion: NATIVE_RUNTIME_RESOLVER_VERSION, - reason: "explicit_paperclip_runner", - provider: resolution.profile.backend === "opencode_server" - ? "opencode" - : resolution.profile.backend === "claude_managed_agents_api" - ? "claude_managed" - : resolution.profile.backend === "aws_agentcore_harness_api" - ? "aws_agentcore" - : resolution.profile.backend === "muse_external" ? "muse" - : resolution.profile.backend === "grok_bot_mcp" ? "grok_bot" - : resolution.profile.backend === "openai_dot_mcp" ? "openai_dot" - : resolution.profile.backend === "cursor_cloud_api" ? "cursor_cloud" - : resolution.profile.backend === "acpx_runtime" - ? "acpx" - : "codex", - }; -} - /** * Production heartbeat selection seam. A resolved run keeps its persisted * mode across configuration changes; only a fresh unresolved run consults the diff --git a/server/src/services/paperclip-id-gmail-connector.ts b/server/src/services/paperclip-id-gmail-connector.ts deleted file mode 100644 index 5b848712fd2..00000000000 --- a/server/src/services/paperclip-id-gmail-connector.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * @deprecated Paperclip ID is identity-only. Import the Paperclip Cloud - * connector names from `paperclip-cloud-connector.ts` for new code. - * - * These aliases keep source compatibility while deployments and persisted app - * definitions move from the former Paperclip ID broker prototype. - */ -export { - GMAIL_CONNECTOR_SCOPES, - GMAIL_MCP_URL, - GOOGLE_WORKSPACE_CONNECTOR_PROFILES, - PaperclipCloudConnectorError as PaperclipIdConnectorError, - createPaperclipCloudConnector as createPaperclipIdGmailConnector, - paperclipCloudConnectorCapabilitiesFromEnv as paperclipIdGoogleConnectorCapabilitiesFromEnv, - paperclipCloudConnectorConfigFromEnv as paperclipIdGmailConnectorConfigFromEnv, -} from "./paperclip-cloud-connector.js"; - -export type { - PaperclipCloudConnector as PaperclipIdGmailConnector, - PaperclipCloudConnector as PaperclipIdGoogleWorkspaceConnector, - PaperclipCloudConnectorConfig as PaperclipIdGmailConnectorConfig, - PaperclipCloudConnectorEnvironment as PaperclipIdConnectorEnvironment, - PaperclipCloudConnectorOperation as PaperclipIdConnectorOperation, - SealedGmailCredentials, - SealedGoogleWorkspaceCredentials, -} from "./paperclip-cloud-connector.js"; diff --git a/server/src/services/plugin-lifecycle.ts b/server/src/services/plugin-lifecycle.ts index 3c2014c94c1..0e251016edb 100644 --- a/server/src/services/plugin-lifecycle.ts +++ b/server/src/services/plugin-lifecycle.ts @@ -308,22 +308,8 @@ async function retireConnectorConnectionsFor(db: Db, pluginKey: string): Promise export function pluginLifecycleManager( db: Db, - options?: PluginLoader | PluginLifecycleManagerOptions, + { loader, workerManager }: PluginLifecycleManagerOptions = {}, ): PluginLifecycleManager { - // Support the legacy signature: pluginLifecycleManager(db, loader) - // as well as the new options object form. - let loaderArg: PluginLoader | undefined; - let workerManager: PluginWorkerManager | undefined; - - if (options && typeof options === "object" && "discoverAll" in options) { - // Legacy: second arg is a PluginLoader directly - loaderArg = options as PluginLoader; - } else if (options && typeof options === "object") { - const opts = options as PluginLifecycleManagerOptions; - loaderArg = opts.loader; - workerManager = opts.workerManager; - } - const registry = pluginRegistryService(db); const retireConnectorConnections = (pluginKey: string) => retireConnectorConnectionsFor(db, pluginKey); /** @@ -341,7 +327,7 @@ export function pluginLifecycleManager( await completeLegacyPluginToolAccess(db, pluginKey); })().catch((error) => log.warn({ err: error, pluginId }, "Could not update plugin connectors after activation")); } - const pluginLoaderInstance = loaderArg ?? pluginLoader(db); + const pluginLoaderInstance = loader ?? pluginLoader(db); const emitter = new EventEmitter(); emitter.setMaxListeners(100); // plugins may have many listeners; 100 is a safe upper bound diff --git a/server/src/services/plugin-secrets-handler.ts b/server/src/services/plugin-secrets-handler.ts index 308acbe858e..68349b1027a 100644 --- a/server/src/services/plugin-secrets-handler.ts +++ b/server/src/services/plugin-secrets-handler.ts @@ -124,28 +124,6 @@ export function extractSecretRefBindingsFromConfig( return [...refsByPath.values()]; } -/** Backward-compatible helper returning only secret IDs. */ -export function extractSecretRefsFromConfig( - configJson: unknown, - schema?: Record | null, -): Set { - return new Set(extractSecretRefBindingsFromConfig(configJson, schema).map((ref) => ref.secretId)); -} - -/** Backward-compatible helper returning secret IDs grouped by config path. */ -export function extractSecretRefPathsFromConfig( - configJson: unknown, - schema?: Record | null, -): Map> { - const refs = new Map>(); - for (const ref of extractSecretRefBindingsFromConfig(configJson, schema)) { - const paths = refs.get(ref.secretId) ?? new Set(); - paths.add(ref.configPath); - refs.set(ref.secretId, paths); - } - return refs; -} - // --------------------------------------------------------------------------- // Handler factory // --------------------------------------------------------------------------- diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 67c3829b097..cd7bdb1c7b1 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -41,7 +41,6 @@ import { } from "./legacy-continuation.js"; import { CONTROLLER_LEASE_LOST_FAILURE_CODE, hasLiveLegacyController, legacyControllerBootId, liveLegacyControllerExpiresAt } from "../legacy-controller-lease.js"; import { isCompletedOnboardingHandoffWake } from "../chat-completion-delivery.js"; -import { instanceSettingsService } from "../instance-settings.js"; import { NATIVE_STATUS_COMMITTER_ACTOR_ID } from "../issue-rewake-throttle.js"; import { isWaitingConversation, settleConversationTurnForRun, deliverConversationComments } from "../agent-conversations.js"; import { @@ -4918,7 +4917,6 @@ export function recoveryService( if (current) Object.assign(issue, current); } } - if (!(await instanceSettingsService(db).getExperimental()).enableAgentChat) { result.skipped += 1; continue; } { if (await deliverConversationComments(db, issue, deps.enqueueWakeup, { onDeferredDeadline: opts?.onDeferredDeadline }) === "deferred") { diff --git a/server/src/services/runtime-skill-cache.ts b/server/src/services/runtime-skill-cache.ts index 0366a774c37..c0150097ef9 100644 --- a/server/src/services/runtime-skill-cache.ts +++ b/server/src/services/runtime-skill-cache.ts @@ -1,6 +1,5 @@ import { createHash, randomUUID } from "node:crypto"; import { constants, promises as fs } from "node:fs"; -import os from "node:os"; import path from "node:path"; import type { CompanySkill } from "@paperclipai/shared"; import { currentControllerProcessStamp, readControllerProcess } from "./controller-process-identity.js"; @@ -230,10 +229,8 @@ async function publishLocked(root: string, fingerprint: string, action: () => const lock = path.join(root, `${fingerprint}.lock`); const token = randomUUID(); const owner = path.join(root, `.owner-${token}`); - // `pid` and `host` stay for older readers; `controller` is the proof input. // The stamp does no I/O, so preparation adds no wait before the turn. - await fs.writeFile(owner, JSON.stringify({ pid: process.pid, host: os.hostname(), token, - controller: currentControllerProcessStamp() }), { flag: "wx" }); + await fs.writeFile(owner, JSON.stringify({ token, controller: currentControllerProcessStamp() }), { flag: "wx" }); let acquired = false; // A live holder is re-proved at most once a second, not on every 20 ms poll. let judged: { inode: number; at: number } | null = null; diff --git a/server/src/services/task-retry.ts b/server/src/services/task-retry.ts index 61deed96b34..248362ee749 100644 --- a/server/src/services/task-retry.ts +++ b/server/src/services/task-retry.ts @@ -13,7 +13,6 @@ import { conflict, forbidden, notFound, HttpError } from "../errors.js"; import { persistActivity } from "./activity-log.js"; import { createSystemRecovery, readSystemRecovery, savedFilesUnrecoverable } from "./system-recovery-state.js"; import { adoptSystemRecovery, updateSystemRecovery } from "./system-recovery.js"; -import { instanceSettingsService } from "./instance-settings.js"; import { notifyChatActionWork } from "./chat-work-notifications.js"; import { authorizationService } from "./authorization.js"; import { preserveNativeFailedWorkspace, preserveTaskRemoteWorkspaceWriter } from "./native-runtime/native-failed-workspace-recovery.js"; @@ -43,13 +42,11 @@ export async function taskRetryMutationAllowed(db: Db, input: { return permission.allowed; } -export async function assertTaskRetryConversationAllowed( - db: Db, +export function assertTaskRetryConversationAllowed( issue: { conversationAgentId?: string | null; conversationUserId?: string | null }, actorId: string, ) { if (!issue.conversationAgentId) return; - if (!(await instanceSettingsService(db).getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled"); if (issue.conversationUserId !== actorId) throw forbidden("Only the conversation owner can retry a chat run"); } @@ -296,7 +293,7 @@ function admitTaskRetry(input: TaskRetryRequest) { const [issue] = await tx.select().from(issues).where(and(eq(issues.companyId, input.companyId), eq(issues.id, input.issueId))).for("update"); if (!issue) throw notFound("Task not found"); - await assertTaskRetryConversationAllowed(db, issue, input.actorId); + assertTaskRetryConversationAllowed(issue, input.actorId); const key = `task-retry:${input.idempotencyKey}`; const [sameRequest] = await tx.select().from(agentWakeupRequests).where(and( eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.idempotencyKey, key))); @@ -660,8 +657,7 @@ export async function reconcileTaskChatRetryReceipts(db: Db, scope: { companyId? requestId: wake.id, sourceRunId: intent.sourceRunId })) return "denied"; if (!await taskRetryMutationAllowed(tx as unknown as Db, { companyId: wake.companyId, issueId, actorId: intent.actorId, actorSource: intent.actorSource })) return "denied"; - if (issue.conversationAgentId && (issue.conversationUserId !== intent.actorId || - !(await instanceSettingsService(tx as unknown as Db).getExperimental()).enableAgentChat)) return "denied"; + if (issue.conversationAgentId && issue.conversationUserId !== intent.actorId) return "denied"; if (adapterExecutionControls.has(intent.sourceRunId) || await hasPendingRunCleanup(tx as unknown as Db, wake.companyId, intent.sourceRunId)) return "waiting"; return "ready"; diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts index d5ae794a920..f08fa43240a 100644 --- a/server/src/services/tool-access.ts +++ b/server/src/services/tool-access.ts @@ -170,8 +170,6 @@ type ToolAccessServiceOptions = { composioAppToolkits?: readonly string[]; /** Test seam for the centrally registered Gmail OAuth broker. */ paperclipCloudConnector?: PaperclipCloudConnector | null; - /** @deprecated Use paperclipCloudConnector. */ - paperclipIdGmailConnector?: PaperclipCloudConnector | null; /** Test seam for Vercel Connect without live vendor traffic. */ vercelConnectClient?: VercelConnectClient | null; }; @@ -756,12 +754,8 @@ export function toolAccessService( const profileService = createToolProfileService(db, now); const profileDetails = profileService.getProfile; const profileResolver = createToolProfileResolver(db, { assertOptionalAgent, resolveInstalledConnectionsForAgent, toCatalogEntry }); - const configuredCloudConnector = - options.paperclipCloudConnector ?? options.paperclipIdGmailConnector; - const connectorWasProvided = - options.paperclipCloudConnector !== undefined || - options.paperclipIdGmailConnector !== undefined; - let cachedCloudConnector = configuredCloudConnector ?? null; + const connectorWasProvided = options.paperclipCloudConnector !== undefined; + let cachedCloudConnector = options.paperclipCloudConnector ?? null; const currentCloudConnector = (): PaperclipCloudConnector | null => { if (cachedCloudConnector || connectorWasProvided) return cachedCloudConnector; diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index d3960597faf..8a89286857d 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -1385,8 +1385,6 @@ export function createToolGatewayService( remoteHttpRequest?: (url: string, init: RequestInit) => Promise; /** Test seam for refreshing personal Gmail grants. */ paperclipCloudConnector?: PaperclipCloudConnector | null; - /** @deprecated Use paperclipCloudConnector. */ - paperclipIdGmailConnector?: PaperclipCloudConnector | null; /** Refreshes customer-owned/DCR OAuth grants before remote MCP execution. */ oauthGrantRefresher?: (input: { companyId: string; @@ -1638,12 +1636,8 @@ export function createToolGatewayService( headers: Record; } >(); - const configuredCloudConnector = - options.paperclipCloudConnector ?? options.paperclipIdGmailConnector; - const connectorWasProvided = - options.paperclipCloudConnector !== undefined || - options.paperclipIdGmailConnector !== undefined; - let cachedCloudConnector = configuredCloudConnector ?? null; + const connectorWasProvided = options.paperclipCloudConnector !== undefined; + let cachedCloudConnector = options.paperclipCloudConnector ?? null; const currentCloudConnector = (): PaperclipCloudConnector | null => { if (cachedCloudConnector || connectorWasProvided) return cachedCloudConnector; diff --git a/ui/src/api/agents.test.ts b/ui/src/api/agents.test.ts index c6820c9144d..a7ba3927d93 100644 --- a/ui/src/api/agents.test.ts +++ b/ui/src/api/agents.test.ts @@ -1,9 +1,18 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { agentsApi } from "./agents"; -import { api } from "./client"; +import { ApiError, api } from "./client"; afterEach(() => vi.restoreAllMocks()); +it("reports a shortname conflict from the server without retrying", async () => { + const error = new ApiError("Agent reference is ambiguous", 409, {}); + const get = vi.spyOn(api, "get").mockRejectedValue(error); + const options = { signal: new AbortController().signal }; + + await expect(agentsApi.get("research-agent", "company-1", options)).rejects.toBe(error); + expect(get).toHaveBeenCalledExactlyOnceWith("/agents/research-agent?companyId=company-1", options); +}); + describe("agentsApi.retryFailedRun", () => { it("sends only the selected failed run and preserves a retry waiting for dispatch", async () => { const post = vi.spyOn(api, "post").mockResolvedValue({ diff --git a/ui/src/api/agents.ts b/ui/src/api/agents.ts index b9a0b343f96..1f0448f960e 100644 --- a/ui/src/api/agents.ts +++ b/ui/src/api/agents.ts @@ -38,8 +38,7 @@ import type { ClearAgentErrorResponse, AgentApiKeyScope, } from "@paperclipai/shared"; -import { isUuidLike, normalizeAgentUrlKey } from "@paperclipai/shared"; -import { ApiError, api, type RequestOptions } from "./client"; +import { api, type RequestOptions } from "./client"; export interface AgentKey { id: string; @@ -127,32 +126,8 @@ export const agentsApi = { org: (companyId: string) => api.get(`/companies/${companyId}/org`), listConfigurations: (companyId: string) => api.get[]>(`/companies/${companyId}/agent-configurations`), - get: async (id: string, companyId?: string, options?: RequestOptions) => { - try { - return await api.get(agentPath(id, companyId), options); - } catch (error) { - // Backward-compat fallback: if backend shortname lookup reports ambiguity, - // resolve using company agent list while ignoring terminated agents. - if ( - !(error instanceof ApiError) || - error.status !== 409 || - !companyId || - isUuidLike(id) - ) { - throw error; - } - - const urlKey = normalizeAgentUrlKey(id); - if (!urlKey) throw error; - - const agents = await api.get(`/companies/${companyId}/agents`, options); - const matches = agents.filter( - (agent) => agent.status !== "terminated" && normalizeAgentUrlKey(agent.urlKey) === urlKey, - ); - if (matches.length !== 1) throw error; - return api.get(agentPath(matches[0]!.id, companyId), options); - } - }, + get: (id: string, companyId?: string, options?: RequestOptions) => + api.get(agentPath(id, companyId), options), getConfiguration: (id: string, companyId?: string) => api.get(agentPath(id, companyId, "/configuration")), listConfigRevisions: (id: string, companyId?: string) => diff --git a/ui/src/components/ActivityFeed.tsx b/ui/src/components/ActivityFeed.tsx index ce055e201ee..af8f6df3dff 100644 --- a/ui/src/components/ActivityFeed.tsx +++ b/ui/src/components/ActivityFeed.tsx @@ -393,12 +393,6 @@ export function ActivityFeed({ className }: ActivityFeedProps) { return map; }, [issues]); - const entityStatusMap = useMemo(() => { - const map = new Map(); - for (const i of issues ?? []) map.set(`issue:${i.id}`, i.status); - return map; - }, [issues]); - // Filter, tier, sort events const processedItems = useMemo(() => { const events = (activity ?? []) @@ -526,7 +520,6 @@ export function ActivityFeed({ className }: ActivityFeedProps) { agentMap={agentMap} entityNameMap={entityNameMap} entityTitleMap={entityTitleMap} - entityStatusMap={entityStatusMap} isActive={isActiveHeartbeat} /> @@ -544,7 +537,6 @@ export function ActivityFeed({ className }: ActivityFeedProps) { agentMap={agentMap} entityNameMap={entityNameMap} entityTitleMap={entityTitleMap} - entityStatusMap={entityStatusMap} isActive={isActiveHeartbeat} isMuted /> diff --git a/ui/src/components/AgentChatSidebar.tsx b/ui/src/components/AgentChatSidebar.tsx index 66f4f352237..96518da829d 100644 --- a/ui/src/components/AgentChatSidebar.tsx +++ b/ui/src/components/AgentChatSidebar.tsx @@ -2,7 +2,6 @@ import { Star, SquarePen } from "lucide-react"; import { SidebarNavItem } from "@/components/SidebarNavItem"; import { AgentIcon } from "@/components/AgentIconPicker"; import { Button } from "@/components/ui/button"; -import { useSidebar } from "@/context/SidebarContext"; import type { Agent } from "@paperclipai/shared"; import { agentRouteRef, cn } from "@/lib/utils"; import { orderChatAgents } from "@/lib/recent-agent-chats"; @@ -24,8 +23,6 @@ export function AgentChatSidebar({ onToggleStar: (id: string) => void; onOpenChat: () => void; }) { - const { collapsed, peeking } = useSidebar(); - const rail = collapsed && !peeking; const ordered = orderChatAgents(agents, starredIds, recentIds); const row = (agent: Agent) => { const pinned = starredIds.includes(agent.id); @@ -38,35 +35,33 @@ export function AgentChatSidebar({ iconNode={ } - className={rail ? undefined : "pr-9"} + className="pr-9" /> - {!rail && ( - - )} + ); }; return (
- Chats + Chats -
- {Icon ?
+ - +
+ ) : null} + {children} + ); } diff --git a/ui/src/components/CoordinatorSidebar.test.tsx b/ui/src/components/CoordinatorSidebar.test.tsx index e7b02c69cc3..99625dd0a63 100644 --- a/ui/src/components/CoordinatorSidebar.test.tsx +++ b/ui/src/components/CoordinatorSidebar.test.tsx @@ -10,7 +10,7 @@ import { coordinatorAttentionQueryKey, coordinatorAttentionSummaryQueryKey, coor import { queryKeys } from "@/lib/queryKeys"; (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; -const fixture = vi.hoisted(() => ({ attention: vi.fn(), summary: vi.fn(), openNewIssue: vi.fn(), pathname: "/COO/issues", search: "", collapsed: false, userId: "reviewer" as string | null, chats: [] as Array<{ isUnreadForMe: boolean }>, +const fixture = vi.hoisted(() => ({ attention: vi.fn(), summary: vi.fn(), openNewIssue: vi.fn(), pathname: "/COO/issues", search: "", userId: "reviewer" as string | null, chats: [] as Array<{ isUnreadForMe: boolean }>, recentTasks: [] as Array>, projects: [] as Array>, projectTasks: vi.fn(), enableCases: false, agents: [] as Agent[] })); vi.mock("@/hooks/useCoordinatorWorkspaceEnabled", () => ({ useCoordinatorWorkspaceEnabled: () => ({ enabled: true, userId: fixture.userId }) })); vi.mock("@/hooks/useAgentChatNavigation", () => ({ useAgentChatNavigation: () => ({ @@ -24,7 +24,7 @@ vi.mock("@/lib/issueDetailCache", async (importOriginal) => ({ prefetchIssueDetailForNavigation: taskPrefetch, })); vi.mock("@/context/DialogContext", () => ({ useDialogActions: () => ({ openNewIssue: fixture.openNewIssue }) })); -vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ collapsed: fixture.collapsed, peeking: false, isMobile: false, setSidebarOpen: vi.fn() }) })); +vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: false, setSidebarOpen: vi.fn() }) })); vi.mock("@/api/attention", () => ({ attentionApi: { list: fixture.attention, summary: fixture.summary } })); vi.mock("@/api/instanceSettings", () => ({ instanceSettingsApi: { getExperimental: async () => ({ enableCases: fixture.enableCases }) } })); vi.mock("@/api/projects", () => ({ projectsApi: { list: async () => fixture.projects } })); @@ -51,7 +51,7 @@ function summary(items: AttentionItem[], mineCount = items.length) { let root: Root, container: HTMLDivElement, client: QueryClient; beforeEach(() => { - vi.clearAllMocks(); localStorage.clear(); fixture.collapsed = false; fixture.userId = "reviewer"; fixture.pathname = "/COO/issues"; fixture.search = ""; + vi.clearAllMocks(); localStorage.clear(); fixture.userId = "reviewer"; fixture.pathname = "/COO/issues"; fixture.search = ""; fixture.chats = []; fixture.recentTasks = []; fixture.projects = []; fixture.enableCases = false; fixture.agents = []; fixture.summary.mockResolvedValue(summary([pending("question"), pending("review")])); container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); @@ -142,8 +142,7 @@ describe("Coordinator task creation", () => { expect(region.textContent).not.toContain("Recents"); expect(region.querySelector('a[href="/issues/TASK-0"]')).not.toBeNull(); }); - it.each([false, true])("opens global search from the organization header when collapsed is %s", async collapsed => { - fixture.collapsed = collapsed; + it("opens global search from the organization header", async () => { await renderSidebar(); const listener = vi.fn(); document.addEventListener("keydown", listener); @@ -154,8 +153,7 @@ describe("Coordinator task creation", () => { expect(listener).toHaveBeenCalledWith(expect.objectContaining({ key: "k", metaKey: true })); } finally { document.removeEventListener("keydown", listener); } }); - it.each([false, true])("opens the task form from New task above Chat when collapsed is %s", async (collapsed) => { - fixture.collapsed = collapsed; + it("opens the task form from New task above Chat", async () => { await renderSidebar(); const button = container.querySelector('button[aria-label="New task"]'); const chat = container.querySelector('a[href="/chats"]'); @@ -256,10 +254,6 @@ describe("Coordinator pinned pages", () => { await act(async () => root.unmount()); root = createRoot(container); await renderSidebar(); expect(order()).toEqual(["/dashboard", "/artifacts"]); - fixture.collapsed = true; - await renderSidebar(); - expect(navigation().querySelector('[aria-label^="Reorder pinned"]')).toBeNull(); - expect(order()).toEqual(["/dashboard", "/artifacts"]); } finally { rect.mockRestore(); } }); it.each([false, true])("keeps Cases reachable in More only when enabled (%s)", async enabled => { @@ -268,13 +262,10 @@ describe("Coordinator pinned pages", () => { await act(async () => container.querySelector('button[aria-label="More workspace pages"]')!.click()); expect(document.querySelector('a[href="/cases"]') !== null).toBe(enabled); }); - it("announces unread chat totals in expanded and collapsed navigation", async () => { + it("announces unread chat totals", async () => { fixture.chats = [{ isUnreadForMe: true }, { isUnreadForMe: false }, { isUnreadForMe: true }]; await renderSidebar(); expect(container.querySelector('a[href="/chats"] [aria-label="2 unread chats"]')).not.toBeNull(); - fixture.collapsed = true; - await renderSidebar(); - expect(container.querySelector('a[href="/chats"]')?.getAttribute("aria-label")).toBe("Chat, 2 unread chats"); }); const navigation = () => container.querySelector('nav[aria-label="Workspace navigation"]')!; const pinnedPage = (to: string) => navigation().querySelector(`a[href="${to}"]`); @@ -285,8 +276,7 @@ describe("Coordinator pinned pages", () => { await flush(); } - it.each([false, true])("keeps pins above More without a separate section, restores and unpins when collapsed is %s", async collapsed => { - fixture.collapsed = collapsed; + it("keeps pins above More without a separate section, restores and unpins", async () => { await renderSidebar(); expect(pinnedPage("/projects")).toBeNull(); await click("More workspace pages"); @@ -302,7 +292,6 @@ describe("Coordinator pinned pages", () => { root = createRoot(container); await renderSidebar(); expect(pinnedPage("/projects")).not.toBeNull(); - if (collapsed) await click("More workspace pages"); await click("Unpin Projects"); expect(pinnedPage("/projects")).toBeNull(); }); @@ -399,11 +388,10 @@ describe("Coordinator Inbox badge", () => { expect(decisionLink().textContent).toBe("Inbox"); }); - it("announces only your outstanding count when the sidebar is collapsed", async () => { - fixture.collapsed = true; + it("announces only your outstanding count", async () => { fixture.summary.mockResolvedValue(summary([pending("for-reviewer"), pending("for-someone-else")], 1)); await renderSidebar(); - expect(decisionLink().getAttribute("aria-label")).toBe("Inbox, 1 decisions"); + expect(decisionLink().querySelector('[aria-label="1 decisions"]')).not.toBeNull(); }); }); diff --git a/ui/src/components/CoordinatorSidebar.tsx b/ui/src/components/CoordinatorSidebar.tsx index 8895ac8150c..86ea28b72db 100644 --- a/ui/src/components/CoordinatorSidebar.tsx +++ b/ui/src/components/CoordinatorSidebar.tsx @@ -13,7 +13,7 @@ import { useDialogActions } from "@/context/DialogContext"; import { useSidebar } from "@/context/SidebarContext"; import { queryKeys } from "@/lib/queryKeys"; import { Link, useLocation } from "@/lib/router"; -import { agentRouteRef, cn, projectRouteRef, SIDEBAR_RAIL_HIDDEN_LABEL } from "@/lib/utils"; +import { agentRouteRef, cn, projectRouteRef } from "@/lib/utils"; import { SidebarCompanyMenu } from "./SidebarCompanyMenu"; import { SidebarNavItem } from "./SidebarNavItem"; import { RecentTaskNavItem } from "./RecentTaskNavItem"; @@ -124,11 +124,10 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) { const moreContentRef = useRef(null); const orderedPins = useMemo(() => buildPinnedNavigationItems(pinnedNavigation.pins, agents.data ?? [], destinations), [pinnedNavigation.pins, agents.data, destinations]); const { entries: recentTasks } = useRecentTasks({ companyId, userId }); - const { collapsed, peeking, isMobile, setSidebarOpen } = useSidebar(); - const rail = collapsed && !peeking; + const { isMobile, setSidebarOpen } = useSidebar(); // Warm opens only while the Recents list is on screen. const location = useLocation(); - useRecentTaskOpenWarmup({ companyId, userId, tasks: !rail && session.isSuccess ? recentTasks : NO_RECENT_TASKS, navigationKey: location.pathname }); + useRecentTaskOpenWarmup({ companyId, userId, tasks: 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); @@ -156,28 +155,28 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) { }, [agents.data, chats.data, recentTasks, projects, projectVisits, scope, hierarchy]); const newTaskButton = ; return