refactor(core): remove retired compatibility paths (#22055)

## 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 <noreply@paperclip.ing>
This commit is contained in:
Nicky LeachandPaperclip authored and GitHub committed 2026-11-17 14:00:14 -08:00
1 parent f5f60cfcb2
commit f05b90508a
112 files changed
+482 -2325

No files matched your search

@@ -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);
}
@@ -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;
@@ -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,
}),
},
@@ -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<ReturnType<typeof openCodexAcpxRuntime>> | undefined;
let port: Awaited<ReturnType<typeof openQualifiedAcpxRuntime>> | 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<void>(resolve => child.once("exit", () => resolve())),
});
@@ -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<ReturnType<typeof openCodexAcpxRuntime>> | undefined;
let port: Awaited<ReturnType<typeof openQualifiedAcpxRuntime>> | undefined;
try {
port = await openCodexAcpxRuntime(options, {
port = await openQualifiedAcpxRuntime(options, {
awaitProviderOwnership: async () => undefined,
awaitProviderExit: child => new Promise<void>(resolve => child.once("exit", () => resolve())),
});
@@ -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<ReturnType<typeof openCodexAcpxRuntime>> | undefined;
let port: Awaited<ReturnType<typeof openQualifiedAcpxRuntime>> | undefined;
try {
port = await openCodexAcpxRuntime(options, {
port = await openQualifiedAcpxRuntime(options, {
awaitProviderOwnership: async () => undefined,
awaitProviderExit: child => new Promise<void>(resolve => child.once("exit", () => resolve())),
createRuntime: (created) => {
@@ -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<ReturnType<typeof openCodexAcpxRuntime>> | undefined;
let port: Awaited<ReturnType<typeof openQualifiedAcpxRuntime>> | undefined;
try {
port = await openCodexAcpxRuntime(options, {
port = await openQualifiedAcpxRuntime(options, {
awaitProviderOwnership: async () => undefined,
awaitProviderExit: child => new Promise<void>(resolve => child.once("exit", () => resolve())),
});
@@ -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<string, { acpx: number; paperclip: number }>();
let port: Awaited<ReturnType<typeof openCodexAcpxRuntime>> | undefined;
let port: Awaited<ReturnType<typeof openQualifiedAcpxRuntime>> | 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<void>(resolve => child.once("exit", () => resolve())),
});
@@ -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<ReturnType<typeof openCodexAcpxRuntime>> | undefined;
let port: Awaited<ReturnType<typeof openQualifiedAcpxRuntime>> | undefined;
try {
port = await openCodexAcpxRuntime(options, {
port = await openQualifiedAcpxRuntime(options, {
awaitProviderOwnership: async () => undefined,
awaitProviderExit: child => new Promise<void>(resolve => child.once("exit", () => resolve())),
});
@@ -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<ReturnType<typeof openCodexAcpxRuntime>> | undefined;
let port: Awaited<ReturnType<typeof openQualifiedAcpxRuntime>> | 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<void>(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<void>((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<void>((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<void>((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<void>[] = [];
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<void>[] = [];
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<void>[] = [];
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<void>[] = [];
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<void>[] = [];
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<void>[] = [];
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<void>[] = [];
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,
@@ -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" });
@@ -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<AcpxRuntimeHost> {
return AcpxRuntimeHost.open(options, {
openRuntime: openCodexAcpxRuntime,
openRuntime: openQualifiedAcpxRuntime,
reportRetainedCleanupFailure: reportRetainedAcpxCleanupFailure,
});
}
@@ -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<ReturnType<typeof openCodexAcpxRuntime>> | undefined;
let port: Awaited<ReturnType<typeof openQualifiedAcpxRuntime>> | undefined;
let deadline: ReturnType<typeof setTimeout> | 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"),
@@ -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(
+1 -3
View File
@@ -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 `<Sidebar/>` 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`
-2
View File
@@ -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) {
+9 -10
View File
@@ -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", () => {
+1 -1
View File
@@ -30,7 +30,7 @@ await new Promise<void>(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);
+9 -1
View File
@@ -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")));
@@ -57,7 +57,7 @@ suite("case handoff through the assembled native runner", () => {
await new Promise<void>(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) {
+1 -1
View File
@@ -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<void>(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<Record<string, any>> = [];
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" }];
@@ -103,7 +103,7 @@ export async function completeHistoricalListenerSuccessor(input: { db: Db; runId
await new Promise<void>(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"],
@@ -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 {
@@ -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,
@@ -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,
});
@@ -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) });
+1 -6
View File
@@ -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",
-9
View File
@@ -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");
}
+1 -4
View File
@@ -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");
-18
View File
@@ -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) {
@@ -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}`;
-7
View File
@@ -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),
+2 -3
View File
@@ -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)!,
+1 -8
View File
@@ -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");
});
-4
View File
@@ -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);
-3
View File
@@ -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,
@@ -102,9 +102,7 @@ describeEmbeddedPostgres("native Codex server vertical slice", () => {
await new Promise<void>((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 () => {
@@ -263,7 +263,7 @@ describeEmbeddedPostgres("native question bridge", () => {
const stateDirectory = mkdtempSync(join(tmpdir(), "native-permission-authority-"));
const server = createServer();
await new Promise<void>(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" },
@@ -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,
@@ -84,9 +84,7 @@ describe("paperclip-runner real server vertical slice", () => {
await new Promise<void>((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" }));
@@ -239,7 +239,7 @@ describeEmbeddedPostgres("hidden runner PRP coordinator", () => {
await new Promise<void>(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 });
@@ -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" }));
@@ -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
@@ -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";
+2 -16
View File
@@ -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
@@ -124,28 +124,6 @@ export function extractSecretRefBindingsFromConfig(
return [...refsByPath.values()];
}
/** Backward-compatible helper returning only secret IDs. */
export function extractSecretRefsFromConfig(
configJson: unknown,
schema?: Record<string, unknown> | null,
): Set<string> {
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<string, unknown> | null,
): Map<string, Set<string>> {
const refs = new Map<string, Set<string>>();
for (const ref of extractSecretRefBindingsFromConfig(configJson, schema)) {
const paths = refs.get(ref.secretId) ?? new Set<string>();
paths.add(ref.configPath);
refs.set(ref.secretId, paths);
}
return refs;
}
// ---------------------------------------------------------------------------
// Handler factory
// ---------------------------------------------------------------------------
-2
View File
@@ -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") {
+1 -4
View File
@@ -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<T>(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;
+3 -7
View File
@@ -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";
+2 -8
View File
@@ -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;
+2 -8
View File
@@ -1385,8 +1385,6 @@ export function createToolGatewayService(
remoteHttpRequest?: (url: string, init: RequestInit) => Promise<Response>;
/** 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<string, string>;
}
>();
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;
+10 -1
View File
@@ -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({
+3 -28
View File
@@ -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<OrgNode[]>(`/companies/${companyId}/org`),
listConfigurations: (companyId: string) =>
api.get<Record<string, unknown>[]>(`/companies/${companyId}/agent-configurations`),
get: async (id: string, companyId?: string, options?: RequestOptions) => {
try {
return await api.get<AgentDetail>(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<Agent[]>(`/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<AgentDetail>(agentPath(matches[0]!.id, companyId), options);
}
},
get: (id: string, companyId?: string, options?: RequestOptions) =>
api.get<AgentDetail>(agentPath(id, companyId), options),
getConfiguration: (id: string, companyId?: string) =>
api.get<import("@paperclipai/shared").AgentConfigurationResponse>(agentPath(id, companyId, "/configuration")),
listConfigRevisions: (id: string, companyId?: string) =>
-8
View File
@@ -393,12 +393,6 @@ export function ActivityFeed({ className }: ActivityFeedProps) {
return map;
}, [issues]);
const entityStatusMap = useMemo(() => {
const map = new Map<string, string>();
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}
/>
</div>
@@ -544,7 +537,6 @@ export function ActivityFeed({ className }: ActivityFeedProps) {
agentMap={agentMap}
entityNameMap={entityNameMap}
entityTitleMap={entityTitleMap}
entityStatusMap={entityStatusMap}
isActive={isActiveHeartbeat}
isMuted
/>
+20 -25
View File
@@ -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={
<AgentIcon icon={agent.icon} className="h-4 w-4 shrink-0" />
}
className={rail ? undefined : "pr-9"}
className="pr-9"
/>
{!rail && (
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label={`${pinned ? "Unstar" : "Star"} ${agent.name}`}
aria-pressed={pinned}
title={pinned ? "Unstar agent" : "Star agent to pin"}
onClick={(event) => {
event.stopPropagation();
onToggleStar(agent.id);
}}
className={cn("absolute right-2 top-(--pct-50) -translate-y-(--pct-50) text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover/agent-chat:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100", pinned && "opacity-100")}
>
<Star
aria-hidden="true"
className={cn("size-3.5", pinned && "fill-current")}
/>
</Button>
)}
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label={`${pinned ? "Unstar" : "Star"} ${agent.name}`}
aria-pressed={pinned}
title={pinned ? "Unstar agent" : "Star agent to pin"}
onClick={(event) => {
event.stopPropagation();
onToggleStar(agent.id);
}}
className={cn("absolute right-2 top-(--pct-50) -translate-y-(--pct-50) text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover/agent-chat:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100", pinned && "opacity-100")}
>
<Star
aria-hidden="true"
className={cn("size-3.5", pinned && "fill-current")}
/>
</Button>
</div>
);
};
return (
<section aria-label="Chats" className="group/chats flex flex-col gap-0.5">
<div className="relative flex min-h-9 items-center px-4 py-1.5">
<span className={cn("font-mono text-(length:--text-nano) font-medium uppercase tracking-widest text-muted-foreground/60", rail && "sr-only")}>Chats</span>
<span className="font-mono text-(length:--text-nano) font-medium uppercase tracking-widest text-muted-foreground/60">Chats</span>
<Button
type="button"
variant="ghost"
-2
View File
@@ -31,9 +31,7 @@ vi.mock("@/lib/router", () => ({
vi.mock("../context/SidebarContext", () => ({
useSidebar: () => ({
collapsed: false,
isMobile: viewport.isMobile,
toggleCollapsed: vi.fn(),
toggleSidebar: vi.fn(),
}),
}));
@@ -56,7 +56,6 @@ vi.mock("@/context/SidebarContext", () => ({
}));
vi.mock("./SidebarNavItem", () => ({
SidebarNavExpandedProvider: ({ children }: { children: React.ReactNode }) => children,
SidebarNavItem: (props: {
to: string;
label: string;
+22 -25
View File
@@ -8,7 +8,6 @@ import {
type ContextualSidebarSurface,
} from "@/lib/shell-navigation";
import { cn } from "@/lib/utils";
import { SidebarNavExpandedProvider } from "./SidebarNavItem";
export function ContextualSidebarFrame({
surface,
@@ -41,30 +40,28 @@ export function ContextualSidebarFrame({
}
return (
<SidebarNavExpandedProvider>
<aside
data-contextual-sidebar={surface}
className={cn("flex h-full min-h-0 w-full flex-col bg-muted", className)}
>
{showHeader ? (
<div className="flex shrink-0 flex-col gap-1 px-3 py-3">
<button
type="button"
onClick={goBack}
className="flex items-center gap-1.5 rounded-md px-2 py-1 text-left text-xs text-muted-foreground transition-colors hover:bg-background hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label={`Back from ${title}`}
>
<ChevronLeft className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
<span className="truncate">{selectedCompany?.name ?? "Organization"}</span>
</button>
<div className="flex min-w-0 items-center gap-2 px-2 py-1">
{Icon ? <Icon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" /> : null}
<span className="min-w-0 flex-1 truncate text-sm font-bold text-foreground">{title}</span>
</div>
<aside
data-contextual-sidebar={surface}
className={cn("flex h-full min-h-0 w-full flex-col bg-muted", className)}
>
{showHeader ? (
<div className="flex shrink-0 flex-col gap-1 px-3 py-3">
<button
type="button"
onClick={goBack}
className="flex items-center gap-1.5 rounded-md px-2 py-1 text-left text-xs text-muted-foreground transition-colors hover:bg-background hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label={`Back from ${title}`}
>
<ChevronLeft className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
<span className="truncate">{selectedCompany?.name ?? "Organization"}</span>
</button>
<div className="flex min-w-0 items-center gap-2 px-2 py-1">
{Icon ? <Icon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" /> : null}
<span className="min-w-0 flex-1 truncate text-sm font-bold text-foreground">{title}</span>
</div>
) : null}
{children}
</aside>
</SidebarNavExpandedProvider>
</div>
) : null}
{children}
</aside>
);
}
+9 -21
View File
@@ -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<Record<string, unknown>>, projects: [] as Array<Record<string, unknown>>, 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<HTMLButtonElement>('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<HTMLButtonElement>('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();
});
});
+12 -13
View File
@@ -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<HTMLDivElement>(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 = <Button type="button" variant="ghost" className="design-sidebar-new-task rounded-lg" aria-label="New task" onClick={() => openNewIssue()}>
<SquarePen aria-hidden />
<span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : "truncate"}>New task</span>
<span className="truncate">New task</span>
</Button>;
return <FlyoutAppearanceProvider><TruncatedTextMarqueeProvider><aside className="coordinator-sidebar design-sidebar w-full">
<div className="design-sidebar-brand" data-collapsed={rail || undefined}>
<div className="design-sidebar-brand">
<SidebarCompanyMenu showChevron={false} />
<Tooltip><TooltipTrigger asChild><Button variant="ghost" size="icon-sm" className="design-sidebar-search" aria-label="Global search" onClick={() => document.dispatchEvent(new KeyboardEvent("keydown", { key: "k", metaKey: true, bubbles: true, cancelable: true }))}><Search aria-hidden /></Button></TooltipTrigger><TooltipContent side="right">Search tasks, agents, projects</TooltipContent></Tooltip>
</div>
<nav className="design-sidebar-navigation" aria-label="Workspace navigation">
<div className="design-sidebar-primary">
{rail ? <Tooltip><TooltipTrigger asChild>{newTaskButton}</TooltipTrigger><TooltipContent side="right">New task</TooltipContent></Tooltip> : newTaskButton}
{newTaskButton}
<div className="design-sidebar-primary my-2">
<SidebarNavItem className="design-sidebar-item" to="/chats" label="Chat" icon={MessageCircle} badge={unreadChatCount} badgeLabel="unread chats" />
<div className="group/coordinator-new relative">
<SidebarNavItem to="/issues" label="Tasks" icon={CircleCheck} className={cn("design-sidebar-item", !rail && "pr-9")} />
{!rail && <button type="button" aria-label="New task" title="New task" onClick={() => openNewIssue()}
className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity group-hover/coordinator-new:opacity-100 group-focus-within/coordinator-new:opacity-100 pointer-coarse:opacity-100 hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-ring"><Plus className="size-4" /></button>}
<SidebarNavItem to="/issues" label="Tasks" icon={CircleCheck} className="design-sidebar-item pr-9" />
<button type="button" aria-label="New task" title="New task" onClick={() => openNewIssue()}
className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity group-hover/coordinator-new:opacity-100 group-focus-within/coordinator-new:opacity-100 pointer-coarse:opacity-100 hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-ring"><Plus className="size-4" /></button>
</div>
<SidebarNavItem className="design-sidebar-item" to="/decisions" label="Inbox" icon={Inbox} badge={attentionCount} badgeLabel="decisions" />
{orderedPins.length > 0 && <PinnedNavigationList key={`${companyId}:${userId}`} items={orderedPins} rail={rail} onReorder={pinnedNavigation.reorder} onUnpin={pinnedNavigation.toggle} />}
{orderedPins.length > 0 && <PinnedNavigationList key={`${companyId}:${userId}`} items={orderedPins} onReorder={pinnedNavigation.reorder} onUnpin={pinnedNavigation.toggle} />}
</div>
<Flyout open={moreOpen} onOpenChange={setMoreOpen}>
<FlyoutTrigger asChild><button type="button" aria-label="More workspace pages" className="design-sidebar-item flex w-auto items-center gap-2.5 rounded-lg py-1.5 text-left transition-colors focus-visible:ring-2 focus-visible:ring-ring"><MoreHorizontal className="size-4 shrink-0" /><span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : undefined}>More</span></button></FlyoutTrigger>
<FlyoutTrigger asChild><button type="button" aria-label="More workspace pages" className="design-sidebar-item flex w-auto items-center gap-2.5 rounded-lg py-1.5 text-left transition-colors focus-visible:ring-2 focus-visible:ring-ring"><MoreHorizontal className="size-4 shrink-0" /><span>More</span></button></FlyoutTrigger>
<FlyoutContent ref={moreContentRef} tabIndex={-1} onOpenAutoFocus={(event) => { event.preventDefault(); moreContentRef.current?.focus(); }} side={isMobile ? "bottom" : "right"} align="start" className="w-56 p-1" aria-label="More workspace pages">
{destinations.map(({ label, to, icon: Icon }, index) => {
const pinned = pinnedNavigation.pins.includes(to);
@@ -198,7 +197,7 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) {
</Flyout>
</div>
{pinnedNavigation.error && <p role="alert" className="px-4 py-2 text-xs text-destructive">{pinnedNavigation.error}</p>}
{!rail && session.isSuccess && recents.length > 0 && <div className="design-sidebar-recents"><SidebarSection label="Recents" collapsible={{ open: recentsOpen, onOpenChange: setRecentsOpen }}>
{session.isSuccess && recents.length > 0 && <div className="design-sidebar-recents"><SidebarSection label="Recents" collapsible={{ open: recentsOpen, onOpenChange: setRecentsOpen }}>
<RecentNavigationList>
{recents.map(item => item.kind === "task"
? <RecentTaskGroup key={`${scope}:${item.id}`} task={item.task} userId={userId} className="design-sidebar-item" flattened={hierarchy.flattenedIds.has(item.id)}
+4 -4
View File
@@ -3,7 +3,7 @@ import { Boxes, CircleCheck, CirclePlus, FolderOpen, History, LayoutDashboard, M
import { useCompany } from "@/context/CompanyContext";
import { SidebarAccountMenu } from "./SidebarAccountMenu";
import { SidebarCompanyMenu } from "./SidebarCompanyMenu";
import { SidebarNavExpandedProvider, SidebarNavItem } from "./SidebarNavItem";
import { SidebarNavItem } from "./SidebarNavItem";
import { SidebarSection } from "./SidebarSection";
import { RecentTaskNavItem, recentTaskPathRef } from "./RecentTaskNavItem";
import { TruncatedTextMarqueeProvider } from "./TruncatedText";
@@ -21,7 +21,7 @@ export function DesignSidebar({ onNewTask, recentTasks = [] }: { onNewTask: () =
const companyRecentTasks = recentTasks.filter(task => task.companyId === selectedCompany?.id);
const handleRecentScroll = useScrollbarWhileScrolling();
return (
<FlyoutAppearanceProvider><TruncatedTextMarqueeProvider><SidebarNavExpandedProvider>
<FlyoutAppearanceProvider><TruncatedTextMarqueeProvider>
<div className="design-sidebar">
<div className="design-sidebar-brand">
<SidebarCompanyMenu showChevron={false} />
@@ -53,8 +53,8 @@ export function DesignSidebar({ onNewTask, recentTasks = [] }: { onNewTask: () =
</SidebarSection>
</div> : null}
</nav>
<div className="design-sidebar-account"><SidebarAccountMenu forceExpanded /></div>
<div className="design-sidebar-account"><SidebarAccountMenu /></div>
</div>
</SidebarNavExpandedProvider></TruncatedTextMarqueeProvider></FlyoutAppearanceProvider>
</TruncatedTextMarqueeProvider></FlyoutAppearanceProvider>
);
}
-4
View File
@@ -401,10 +401,6 @@ interface FeedCardProps {
agentMap: Map<string, Agent>;
entityNameMap: Map<string, string>;
entityTitleMap?: Map<string, string>;
/** Retained for call-site compatibility; no longer read — the collapsed
* card always shows the event-derived status. Lifecycle aggregation (a
* later pass) will pass the live status through its own wrapper. */
entityStatusMap?: Map<string, string>;
isActive?: boolean;
/** Tier 2 treatment: mutes the verb and title text. Actor name and
* timestamp retain their color; leading icon retains its color. */
-137
View File
@@ -102,30 +102,13 @@ const RESERVED_APP_SUBPATHS = new Set([
"app",
]);
function isSkillsStoreRoute(
pathname: string,
companyPrefix: string | undefined,
) {
const segments = pathname.split("/").filter(Boolean);
if (segments[0]?.toLowerCase() === "skills") return true;
if (!companyPrefix) return false;
return (
segments[0]?.toUpperCase() === companyPrefix.toUpperCase() &&
segments[1]?.toLowerCase() === "skills"
);
}
export function Layout() {
const designSandbox = useDesignSandbox();
const {
sidebarOpen,
setSidebarOpen,
toggleSidebar,
collapsed,
peeking,
setPeeking,
isMobile,
setForceCollapsed,
} = useSidebar();
const { openNewIssue, openOnboarding } = useDialogActions();
const { togglePanelVisible } = usePanel();
@@ -170,9 +153,6 @@ export function Layout() {
companyPathSegments[2]
? companyPathSegments[2]
: null;
// The Skills Store renders its own secondary (category) sidebar, so the main
// app nav collapses to its rail throughout the Skills Store section (PAP-10879).
const isSkillsRoute = isSkillsStoreRoute(location.pathname, companyPrefix);
const onboardingTriggered = useRef(false);
const previousPathname = useRef<string | null>(null);
const mainContentRef = useRef<HTMLElement | null>(null);
@@ -219,10 +199,6 @@ export function Layout() {
}),
[routeSidebarCompanyId, routeSidebarCompanyPrefix],
);
// Takeover routes (company settings, plugin `routeSidebar`) no longer replace
// the app `<Sidebar/>`. Instead the host collapses it to its rail and renders
// the contextual sidebar in a second pane (PAP-10695). One resolver drives
// both desktop (SecondarySidebar) and mobile (off-canvas drawer).
const secondarySidebar = isCompanySettingsRoute ? (
<CompanySettingsSidebar />
) : appDetailConnectionId ? (
@@ -254,17 +230,6 @@ export function Layout() {
refetchIntervalInBackground: false,
});
// A secondary sidebar always collapses the app sidebar to its rail (still
// peek-able) — a hard invariant that overrides the user pin while the route
// is active, but does NOT mutate the persisted preference. Clearing the force
// on cleanup restores the user's expanded/collapsed choice when navigating
// off the takeover route (PAP-10694).
const forceRailCollapsed = hasSecondarySidebar || isSkillsRoute;
useLayoutEffect(() => {
setForceCollapsed(forceRailCollapsed);
return () => setForceCollapsed(false);
}, [forceRailCollapsed, setForceCollapsed]);
useEffect(() => {
if (companiesLoading || onboardingTriggered.current) return;
if (health?.deploymentMode === "authenticated") return;
@@ -363,102 +328,6 @@ export function Layout() {
);
}, []);
// Peek (hover flyout) triggers for the collapsed rail. Opening has a tiny
// delay so a pointer merely sweeping across the rail doesn't flash it open;
// closing is debounced to avoid flicker on the rail→overlay seam. Keyboard
// focus opens immediately so tabbing reaches the full nav. Context gates the
// effective `peeking` to desktop + collapsed + hover-capable pointers, so
// these handlers are inert otherwise.
const peekTimer = useRef<number | null>(null);
// Whether the pointer is currently over the peek panel. Used to keep the peek
// open across focus changes (e.g. navigation steals focus to <main>) as long as
// the user is still hovering — it should only close when they actually mouse off
// (PAP-10676).
const pointerInsidePanel = useRef(false);
// When the user explicitly collapses while the pointer is still over the panel,
// suppress re-peeking until the pointer actually leaves — otherwise the lingering
// hover immediately re-expands the rail and the collapse "doesn't take" until the
// mouse moves away (PAP-10676). Re-armed on the next genuine pointer-leave.
const suppressPeekRef = useRef(false);
const clearPeekTimer = useCallback(() => {
if (peekTimer.current !== null) {
window.clearTimeout(peekTimer.current);
peekTimer.current = null;
}
}, []);
const openPeek = useCallback(() => {
clearPeekTimer();
peekTimer.current = window.setTimeout(() => setPeeking(true), 50);
}, [clearPeekTimer, setPeeking]);
const openPeekImmediate = useCallback(() => {
clearPeekTimer();
setPeeking(true);
}, [clearPeekTimer, setPeeking]);
const closePeek = useCallback(() => {
clearPeekTimer();
peekTimer.current = window.setTimeout(() => setPeeking(false), 120);
}, [clearPeekTimer, setPeeking]);
// Tracked even while expanded so that, at the moment of collapse, we know
// whether the pointer is over the panel and should suppress the re-peek.
const handlePanelPointerEnter = useCallback(() => {
pointerInsidePanel.current = true;
if (collapsed && !suppressPeekRef.current) openPeek();
}, [collapsed, openPeek]);
const handlePanelPointerLeave = useCallback(() => {
pointerInsidePanel.current = false;
suppressPeekRef.current = false; // pointer left — re-arm peek for the next hover
closePeek();
}, [closePeek]);
const handlePanelFocus = useCallback(() => {
if (suppressPeekRef.current) return;
openPeekImmediate();
}, [openPeekImmediate]);
// Close on focus leaving the panel only when the pointer isn't hovering it.
// Clicking a rail/peek nav item moves focus to <main> on navigation; if the
// mouse is still over the flyout we keep it open until the pointer leaves.
const handlePanelBlur = useCallback(() => {
if (pointerInsidePanel.current) return;
closePeek();
}, [closePeek]);
// Tidy up any pending peek timer on unmount.
useEffect(() => clearPeekTimer, [clearPeekTimer]);
// An explicit collapse must be atomic: cancel any in-flight/active peek, and if
// the pointer is still over the panel suppress re-peeking until it leaves, so the
// rail doesn't immediately re-expand under the lingering hover (PAP-10676).
const wasCollapsed = useRef(collapsed);
useEffect(() => {
if (collapsed !== wasCollapsed.current) {
if (collapsed) {
clearPeekTimer();
setPeeking(false);
suppressPeekRef.current = pointerInsidePanel.current;
} else {
suppressPeekRef.current = false;
}
wasCollapsed.current = collapsed;
}
}, [collapsed, clearPeekTimer, setPeeking]);
// Intentionally do NOT close the peek on navigation: clicking a nav item means
// the pointer is still over the flyout, so it should stay open until the user
// actually mouses off (handled by onPanelMouseLeave) or blurs out / hits Escape
// (PAP-10676). Auto-closing here made the sidebar collapse on every page change.
// Escape closes an open peek without trapping the pointer.
useEffect(() => {
if (!peeking) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
clearPeekTimer();
setPeeking(false);
}
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [peeking, clearPeekTimer, setPeeking]);
useCompanyPageMemory();
useKeyboardShortcuts({
@@ -642,14 +511,8 @@ export function Layout() {
) : (
<SidebarShell
open={sidebarOpen}
collapsed={designSandbox ? false : collapsed}
peeking={designSandbox ? false : peeking}
resizable
storageKey={designSandbox ? "paperclip.design-proposals.sandbox.sidebar-width" : undefined}
onPanelMouseEnter={handlePanelPointerEnter}
onPanelMouseLeave={handlePanelPointerLeave}
onPanelFocusCapture={collapsed ? handlePanelFocus : undefined}
onPanelBlurCapture={collapsed ? handlePanelBlur : undefined}
>
{designSandbox ? <DesignSandboxSidebar /> : <>
<div className="flex flex-1 min-h-0">
+3 -114
View File
@@ -50,13 +50,9 @@ const mockUsePluginSlots = vi.hoisted(() => vi.fn());
const mockPluginSlotContexts = vi.hoisted(
() => [] as Array<Record<string, unknown>>,
);
const mockSetPeeking = vi.hoisted(() => vi.fn());
const mockSetForceCollapsed = vi.hoisted(() => vi.fn());
const mockSidebarState = vi.hoisted(() => ({
sidebarOpen: true,
isMobile: false,
collapsed: false,
peeking: false,
}));
let currentPathname = "/PAP/dashboard";
@@ -265,14 +261,7 @@ vi.mock("../context/SidebarContext", () => ({
sidebarOpen: mockSidebarState.sidebarOpen,
setSidebarOpen: mockSetSidebarOpen,
toggleSidebar: vi.fn(),
toggleCollapsed: vi.fn(),
collapsed: mockSidebarState.collapsed,
peeking: mockSidebarState.peeking,
setPeeking: mockSetPeeking,
setForceCollapsed: mockSetForceCollapsed,
isMobile: mockSidebarState.isMobile,
routeRequestsCollapsed: false,
setRouteRequestsCollapsed: vi.fn(),
}),
}));
@@ -422,10 +411,6 @@ describe("Layout", () => {
mockPluginSlotContexts.length = 0;
mockSidebarState.sidebarOpen = true;
mockSidebarState.isMobile = false;
mockSidebarState.collapsed = false;
mockSidebarState.peeking = false;
mockSetPeeking.mockClear();
mockSetForceCollapsed.mockClear();
});
afterEach(() => {
@@ -519,102 +504,6 @@ describe("Layout", () => {
});
});
it("collapses atomically when the pointer is still over the sidebar (no re-peek) — PAP-10676", async () => {
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
const renderLayout = async () => {
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
};
// The SidebarShell overlay panel carries the peek mouse handlers.
const panel = () =>
[...container.querySelectorAll<HTMLElement>("div")].find(
(el) =>
el.className.includes("inset-y-0") &&
el.className.includes("overflow-hidden"),
);
const hover = (el: HTMLElement) => {
// React derives onMouseEnter from a mouseover crossing in from outside.
el.dispatchEvent(
new MouseEvent("mouseover", {
bubbles: true,
relatedTarget: document.body,
}),
);
};
// Expanded, then hover the panel so the pointer is registered as inside.
await renderLayout();
const expandedPanel = panel();
expect(expandedPanel).toBeTruthy();
await act(async () => {
hover(expandedPanel!);
});
// Collapse while the pointer is still over the panel.
mockSidebarState.collapsed = true;
await renderLayout();
// The peek is cancelled atomically on collapse.
expect(mockSetPeeking).toHaveBeenCalledWith(false);
// A lingering/spurious hover while collapsed must NOT re-open the peek.
mockSetPeeking.mockClear();
const railPanel = panel();
await act(async () => {
hover(railPanel!);
});
await act(async () => {
await new Promise((r) => setTimeout(r, 80));
});
expect(mockSetPeeking).not.toHaveBeenCalledWith(true);
await act(async () => {
root.unmount();
});
});
it("opens the peek when hovering a collapsed rail (positive control for the hover sim)", async () => {
mockSidebarState.collapsed = true;
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
const panel = [...container.querySelectorAll<HTMLElement>("div")].find(
(el) =>
el.className.includes("inset-y-0") &&
el.className.includes("overflow-hidden"),
);
expect(panel).toBeTruthy();
await act(async () => {
panel!.dispatchEvent(
new MouseEvent("mouseover", {
bubbles: true,
relatedTarget: document.body,
}),
);
});
await act(async () => {
await new Promise((r) => setTimeout(r, 80));
});
// A normal collapsed-rail hover (not just-collapsed) opens the peek.
expect(mockSetPeeking).toHaveBeenCalledWith(true);
await act(async () => {
root.unmount();
});
});
it("retains settings navigation and route content beside the proposed sandbox sidebar", async () => {
currentPathname = "/PAP/company/settings/access";
mockDesignSandbox.enabled = true;
@@ -699,7 +588,7 @@ describe("Layout", () => {
expect(container.textContent).toContain("Main company nav");
expect(container.textContent).toContain("Company settings sidebar");
expect(mockSetForceCollapsed).toHaveBeenCalledWith(true);
expect(container.querySelector<HTMLElement>(".sidebar-shell-panel")?.style.width).toBe("240px");
await act(async () => {
root.unmount();
@@ -1092,7 +981,7 @@ describe("Layout", () => {
}
});
it("keeps the global rail beside Skills navigation in the legacy shell", async () => {
it("keeps the global sidebar beside Skills navigation in the legacy shell", async () => {
currentPathname = "/PAP/skills/studio";
mockInstanceSettingsApi.getExperimental.mockResolvedValue({
enableApps: true,
@@ -1111,7 +1000,7 @@ describe("Layout", () => {
expect(container.textContent).toContain("Main company nav");
expect(container.textContent).toContain("Skills sidebar");
expect(mockSetForceCollapsed).toHaveBeenCalledWith(true);
expect(container.querySelector<HTMLElement>(".sidebar-shell-panel")?.style.width).toBe("240px");
await act(async () => {
root.unmount();
+1 -117
View File
@@ -91,11 +91,7 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
sidebarOpen,
setSidebarOpen,
toggleSidebar,
collapsed,
peeking,
setPeeking,
isMobile,
setForceCollapsed,
} = useSidebar();
const { openNewIssue, openOnboarding } = useDialogActions();
const { togglePanelVisible, setPanelVisible } = usePanel();
@@ -256,11 +252,6 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
refetchIntervalInBackground: false,
});
useLayoutEffect(() => {
setForceCollapsed(!streamlinedUiEnabled && hasSecondarySidebar);
return () => setForceCollapsed(false);
}, [hasSecondarySidebar, setForceCollapsed, streamlinedUiEnabled]);
useEffect(() => {
const previous = previousShellRoute.current;
if (
@@ -364,102 +355,6 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
}));
}, []);
// Peek (hover flyout) triggers for the collapsed rail. Opening has a tiny
// delay so a pointer merely sweeping across the rail doesn't flash it open;
// closing is debounced to avoid flicker on the rail→overlay seam. Keyboard
// focus opens immediately so tabbing reaches the full nav. Context gates the
// effective `peeking` to desktop + collapsed + hover-capable pointers, so
// these handlers are inert otherwise.
const peekTimer = useRef<number | null>(null);
// Whether the pointer is currently over the peek panel. Used to keep the peek
// open across focus changes (e.g. navigation steals focus to <main>) as long as
// the user is still hovering — it should only close when they actually mouse off
// (PAP-10676).
const pointerInsidePanel = useRef(false);
// When the user explicitly collapses while the pointer is still over the panel,
// suppress re-peeking until the pointer actually leaves — otherwise the lingering
// hover immediately re-expands the rail and the collapse "doesn't take" until the
// mouse moves away (PAP-10676). Re-armed on the next genuine pointer-leave.
const suppressPeekRef = useRef(false);
const clearPeekTimer = useCallback(() => {
if (peekTimer.current !== null) {
window.clearTimeout(peekTimer.current);
peekTimer.current = null;
}
}, []);
const openPeek = useCallback(() => {
clearPeekTimer();
peekTimer.current = window.setTimeout(() => setPeeking(true), 50);
}, [clearPeekTimer, setPeeking]);
const openPeekImmediate = useCallback(() => {
clearPeekTimer();
setPeeking(true);
}, [clearPeekTimer, setPeeking]);
const closePeek = useCallback(() => {
clearPeekTimer();
peekTimer.current = window.setTimeout(() => setPeeking(false), 120);
}, [clearPeekTimer, setPeeking]);
// Tracked even while expanded so that, at the moment of collapse, we know
// whether the pointer is over the panel and should suppress the re-peek.
const handlePanelPointerEnter = useCallback(() => {
pointerInsidePanel.current = true;
if (collapsed && !suppressPeekRef.current) openPeek();
}, [collapsed, openPeek]);
const handlePanelPointerLeave = useCallback(() => {
pointerInsidePanel.current = false;
suppressPeekRef.current = false; // pointer left — re-arm peek for the next hover
closePeek();
}, [closePeek]);
const handlePanelFocus = useCallback(() => {
if (suppressPeekRef.current) return;
openPeekImmediate();
}, [openPeekImmediate]);
// Close on focus leaving the panel only when the pointer isn't hovering it.
// Clicking a rail/peek nav item moves focus to <main> on navigation; if the
// mouse is still over the flyout we keep it open until the pointer leaves.
const handlePanelBlur = useCallback(() => {
if (pointerInsidePanel.current) return;
closePeek();
}, [closePeek]);
// Tidy up any pending peek timer on unmount.
useEffect(() => clearPeekTimer, [clearPeekTimer]);
// An explicit collapse must be atomic: cancel any in-flight/active peek, and if
// the pointer is still over the panel suppress re-peeking until it leaves, so the
// rail doesn't immediately re-expand under the lingering hover (PAP-10676).
const wasCollapsed = useRef(collapsed);
useEffect(() => {
if (collapsed !== wasCollapsed.current) {
if (collapsed) {
clearPeekTimer();
setPeeking(false);
suppressPeekRef.current = pointerInsidePanel.current;
} else {
suppressPeekRef.current = false;
}
wasCollapsed.current = collapsed;
}
}, [collapsed, clearPeekTimer, setPeeking]);
// Intentionally do NOT close the peek on navigation: clicking a nav item means
// the pointer is still over the flyout, so it should stay open until the user
// actually mouses off (handled by onPanelMouseLeave) or blurs out / hits Escape
// (PAP-10676). Auto-closing here made the sidebar collapse on every page change.
// Escape closes an open peek without trapping the pointer.
useEffect(() => {
if (!peeking) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
clearPeekTimer();
setPeeking(false);
}
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [peeking, clearPeekTimer, setPeeking]);
useCompanyPageMemory();
useKeyboardShortcuts({
@@ -636,20 +531,13 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
</div>
<SidebarAccountMenu
deploymentMode={health?.deploymentMode}
forceExpanded={replacesPrimarySidebar}
/>
</div>
) : (
<SidebarShell
open={sidebarOpen}
collapsed={designSandbox || replacesPrimarySidebar ? false : collapsed}
peeking={designSandbox || replacesPrimarySidebar ? false : peeking}
resizable
storageKey={designSandbox ? "paperclip.design-proposals.sandbox.sidebar-width" : coordinatorWorkspaceEnabled ? "paperclip.coordinator.sidebar-width" : undefined}
onPanelMouseEnter={replacesPrimarySidebar ? undefined : handlePanelPointerEnter}
onPanelMouseLeave={replacesPrimarySidebar ? undefined : handlePanelPointerLeave}
onPanelFocusCapture={!replacesPrimarySidebar && collapsed ? handlePanelFocus : undefined}
onPanelBlurCapture={!replacesPrimarySidebar && collapsed ? handlePanelBlur : undefined}
>
{designSandbox ? <DesignSandboxSidebar /> : <>
<div className="flex flex-1 min-h-0">
@@ -659,15 +547,11 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
<Sidebar>{sidebarSections}</Sidebar>
)}
</div>
{/* Dock optional announcements in the sidebar column so they never
cover the task thread or composer. While the sidebar is a rail
the card waits until the sidebar is expanded again. */}
{sidebarOpen && (replacesPrimarySidebar || !collapsed) ? (
{sidebarOpen ? (
<AnnouncementWell health={health} placement="sidebar" />
) : null}
<SidebarAccountMenu
deploymentMode={health?.deploymentMode}
forceExpanded={replacesPrimarySidebar}
/>
</>}
</SidebarShell>
+2 -2
View File
@@ -38,8 +38,8 @@ vi.mock("../context/CompanyContext", () => ({ useCompany: () => ({
selectedCompanyId: "company-1", loading: false, setSelectedCompanyId: vi.fn(),
}) }));
vi.mock("../context/SidebarContext", () => ({ useSidebar: () => ({
isMobile: false, sidebarOpen: true, collapsed: false, peeking: false,
setSidebarOpen: vi.fn(), setPeeking: vi.fn(), setForceCollapsed: vi.fn(), setRouteRequestsCollapsed: vi.fn(),
isMobile: false, sidebarOpen: true,
setSidebarOpen: vi.fn(),
}) }));
vi.mock("../hooks/useKeyboardShortcuts", () => ({ useKeyboardShortcuts: () => undefined }));
vi.mock("../hooks/useCompanyPageMemory", () => ({ useCompanyPageMemory: () => undefined }));
+8 -8
View File
@@ -25,13 +25,13 @@ export function SortablePinnedRow({ id, label, disabled = false, className, hand
</div>;
}
function PinnedItem({ item, rail, onUnpin }: { item: PinnedNavigationItem; rail: boolean; onUnpin: (key: string) => void }) {
return <SortablePinnedRow id={item.key} label={item.label} disabled={rail} className="group/coordinator-pin relative"
function PinnedItem({ item, onUnpin }: { item: PinnedNavigationItem; onUnpin: (key: string) => void }) {
return <SortablePinnedRow id={item.key} label={item.label} className="group/coordinator-pin relative"
handleClassName="right-3 size-7 group-hover/coordinator-pin:opacity-100 group-focus-within/coordinator-pin:opacity-100" handleIconClassName="size-3.5">
<SidebarNavItem to={item.to} label={item.label} iconNode={item.icon} className={cn("design-sidebar-item group-hover/coordinator-pin:bg-sidebar-accent", !rail && "pr-16")} />
{!rail && <button type="button" aria-label={`Unpin ${item.label}`} title={`Unpin ${item.label}`}
<SidebarNavItem to={item.to} label={item.label} iconNode={item.icon} className="design-sidebar-item group-hover/coordinator-pin:bg-sidebar-accent pr-16" />
<button type="button" aria-label={`Unpin ${item.label}`} title={`Unpin ${item.label}`}
onMouseDown={event => event.stopPropagation()} onClick={() => onUnpin(item.key)}
className="absolute right-10 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-sidebar-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring group-hover/coordinator-pin:opacity-100 group-focus-within/coordinator-pin:opacity-100 pointer-coarse:opacity-100"><PinOff className="size-3.5" /></button>}
className="absolute right-10 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-sidebar-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring group-hover/coordinator-pin:opacity-100 group-focus-within/coordinator-pin:opacity-100 pointer-coarse:opacity-100"><PinOff className="size-3.5" /></button>
</SortablePinnedRow>;
}
@@ -54,10 +54,10 @@ export function SortablePinnedList({ keys, onReorder, children }: {
</DndContext>;
}
export function PinnedNavigationList({ items, rail, onReorder, onUnpin }: {
items: PinnedNavigationItem[]; rail: boolean; onReorder: (keys: string[]) => void; onUnpin: (key: string) => void;
export function PinnedNavigationList({ items, onReorder, onUnpin }: {
items: PinnedNavigationItem[]; onReorder: (keys: string[]) => void; onUnpin: (key: string) => void;
}) {
return <SortablePinnedList keys={items.map(item => item.key)} onReorder={onReorder}>
{items.map(item => <PinnedItem key={item.key} item={item} rail={rail} onUnpin={onUnpin} />)}
{items.map(item => <PinnedItem key={item.key} item={item} onUnpin={onUnpin} />)}
</SortablePinnedList>;
}
@@ -8,11 +8,11 @@ import type { PluginOrganizationSwitcherProps } from "@paperclipai/plugin-sdk/ui
import { PluginOrganizationSwitcher } from "./PluginOrganizationSwitcher";
import { registerPluginReactComponent, registerPluginWebComponent, type ResolvedPluginSlot } from "@/plugins/slots";
const state = vi.hoisted(() => ({ userId: "alice", companyId: "company-a", settled: true, failed: false, isLoading: false, companyListError: false, companyListReady: true, companyIds: ["company-a", "company-b"], slots: [] as ResolvedPluginSlot[], errorMessage: null as string | null, mobile: false, collapsed: false, close: vi.fn(), signOut: vi.fn(), props: null as PluginOrganizationSwitcherProps | null }));
const state = vi.hoisted(() => ({ userId: "alice", companyId: "company-a", settled: true, failed: false, isLoading: false, companyListError: false, companyListReady: true, companyIds: ["company-a", "company-b"], slots: [] as ResolvedPluginSlot[], errorMessage: null as string | null, mobile: false, close: vi.fn(), signOut: vi.fn(), props: null as PluginOrganizationSwitcherProps | null }));
vi.mock("@/api/companies-query", () => ({ useAccountIdentity: () => state, useCompanyListQuery: () => ({ isSuccess: state.companyListReady, isError: state.companyListError, data: { unauthorized: false, companies: state.companyIds.map(id => ({ id, name: "Acme", issuePrefix: "ACME", logoUrl: "/logo" })) } }) }));
vi.mock("@/api/auth", () => ({ authApi: { getSession: async () => ({ user: { id: state.userId } }) } }));
vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: state.companyId, selectedCompany: { name: "Acme", issuePrefix: "ACME", logoUrl: "/logo" } }) }));
vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: state.mobile, setSidebarOpen: state.close, collapsed: state.collapsed, peeking: false }) }));
vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: state.mobile, setSidebarOpen: state.close }) }));
vi.mock("@/hooks/useSignOut", () => ({ useSignOut: () => ({ mutate: state.signOut, isPending: false }) }));
vi.mock("./CompanyPatternIcon", () => ({ CompanyPatternIcon: () => <span>icon</span> }));
vi.mock("@/plugins/slots", async (importOriginal) => ({ ...await importOriginal<object>(), usePluginSlots: () => state }));
@@ -26,7 +26,7 @@ function render() {
}
afterEach(() => {
if (root) flushSync(() => root!.unmount()); root = undefined; container?.remove(); client.clear(); vi.restoreAllMocks();
Object.assign(state, { userId: "alice", companyId: "company-a", settled: true, failed: false, isLoading: false, companyListError: false, companyListReady: true, companyIds: ["company-a", "company-b"], slots: [], errorMessage: null, mobile: false, collapsed: false, props: null });
Object.assign(state, { userId: "alice", companyId: "company-a", settled: true, failed: false, isLoading: false, companyListError: false, companyListReady: true, companyIds: ["company-a", "company-b"], slots: [], errorMessage: null, mobile: false, props: null });
state.close.mockClear(); state.signOut.mockClear();
});
function register() {
@@ -95,10 +95,10 @@ describe("organization navigation replacement", () => {
expect(container.textContent).toBe("Built-in organizations");
});
it("renders one replacement, keeps host controls, and clears state across identity changes", () => {
register(); state.mobile = true; state.collapsed = true; render();
register(); state.mobile = true; render();
expect(container.textContent).toBe("Private organizations");
const host = state.props!.organizationSwitcher;
expect(host.currentCompany).toEqual({ name: "Acme", logoUrl: "/logo" }); expect(host.collapsed).toBe(true);
expect(host.currentCompany).toEqual({ name: "Acme", logoUrl: "/logo" }); expect(host.collapsed).toBe(false);
flushSync(() => host.onOpenChange(true)); expect(state.props!.organizationSwitcher.open).toBe(true);
flushSync(() => host.onNavigate()); expect(state.close).toHaveBeenCalledWith(false); expect(state.props!.organizationSwitcher.open).toBe(false);
host.onSignOut(); expect(state.signOut).toHaveBeenCalledOnce();
@@ -10,14 +10,12 @@ import { CompanyPatternIcon } from "./CompanyPatternIcon";
import { Skeleton } from "./ui/skeleton";
/** Reserve the trigger's space until its owner is known. Never flash another name. */
function OrganizationSwitcherLoading({ collapsed }: { collapsed: boolean }) {
function OrganizationSwitcherLoading() {
return <div role="status" aria-label="Loading organization" aria-busy="true"
className="flex h-9 min-w-0 flex-1 items-center gap-2 px-4">
<Skeleton className="size-5 shrink-0" />
{!collapsed && <>
<span className="min-w-0 flex-1"><Skeleton className="h-4 w-20 max-w-full" /></span>
<ChevronsUpDown className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
</>}
<span className="min-w-0 flex-1"><Skeleton className="h-4 w-20 max-w-full" /></span>
<ChevronsUpDown className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
</div>;
}
@@ -51,7 +49,7 @@ function OrganizationSwitcher({ children, settled, loading, companyId, company,
open?: boolean; onOpenChange?: (open: boolean) => void;
}) {
const [internalOpen, setInternalOpen] = useState(false);
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
const { isMobile, setSidebarOpen } = useSidebar();
const open = controlledOpen ?? internalOpen;
const setOpen = onOpenChange ?? setInternalOpen;
function closeNavigation() {
@@ -61,14 +59,14 @@ function OrganizationSwitcher({ children, settled, loading, companyId, company,
const signOut = useSignOut({ onSignedOut: closeNavigation });
const { slots, isLoading, errorMessage } = usePluginSlots({ slotTypes: ["organizationSwitcher"], companyId, enabled: settled });
if (loading || (settled && isLoading && !errorMessage)) {
return <OrganizationSwitcherLoading collapsed={collapsed && !peeking} />;
return <OrganizationSwitcherLoading />;
}
// Never choose an arbitrary winner for a replacement surface.
if (!settled || errorMessage || slots.length !== 1) return children;
const props: PluginOrganizationSwitcherProps = {
organizationSwitcher: {
currentCompany: company ? { name: company.name, logoUrl: company.logoUrl ?? null } : null,
collapsed: collapsed && !peeking, open, onOpenChange: setOpen,
collapsed: false, open, onOpenChange: setOpen,
onNavigate: closeNavigation, onSignOut: () => signOut.mutate(), signingOut: signOut.isPending,
renderIcon: (name, logoUrl, inMenu) => <CompanyPatternIcon companyName={name} logoUrl={logoUrl}
className={inMenu
+5 -6
View File
@@ -20,18 +20,17 @@ type RecentTaskGroupProps = {
selectedChild?: RecentTaskEntry;
children: ReactNode;
className?: string;
rail?: boolean;
renderChild?: (task: RecentTaskEntry) => ReactNode;
/** Invalid cyclic ancestry remains reachable as plain task rows. */
flattened?: boolean;
};
export function RecentTaskGroup(props: RecentTaskGroupProps) {
if (!props.task.subtaskCount || props.rail || props.flattened) return <>{props.children}</>;
if (!props.task.subtaskCount || props.flattened) return <>{props.children}</>;
return <ExpandableRecentTaskGroup {...props} />;
}
function ExpandableRecentTaskGroup({ task, userId, selectedChild, children, className, rail = false, renderChild }: RecentTaskGroupProps) {
function ExpandableRecentTaskGroup({ task, userId, selectedChild, children, className, renderChild }: RecentTaskGroupProps) {
const [expanded, setExpanded] = useState(true);
const [showAllLoaded, setShowAllLoaded] = useState(false);
const anchor = useRef<HTMLDivElement>(null);
@@ -49,8 +48,8 @@ function ExpandableRecentTaskGroup({ task, userId, selectedChild, children, clas
});
observer.observe(anchor.current);
return () => observer.disconnect();
}, [count, rail]);
const enabled = count > 0 && expanded && visible && !rail;
}, [count]);
const enabled = count > 0 && expanded && visible;
const query = useInfiniteQuery({
queryKey,
queryFn: ({ pageParam, signal }) => readRecentSubtasks(signal, () => issuesApi.listCompact(task.companyId, {
@@ -91,7 +90,7 @@ function ExpandableRecentTaskGroup({ task, userId, selectedChild, children, clas
const childRow = (child: RecentTaskEntry) => renderChild ? renderChild(child)
: <RecentTaskNavItem task={child} label={child.title} className={className} iconNode={<StatusIcon {...taskStatusIconProps(child)} />} />;
if (!count || rail) return <>{children}</>;
if (!count) return <>{children}</>;
return <div ref={anchor} className="min-w-0">
<div className="flex min-w-0 items-center">
<div className="min-w-0 flex-1">{children}</div>
@@ -1,111 +0,0 @@
// @vitest-environment jsdom
import { act } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SidebarProvider, useSidebar } from "../context/SidebarContext";
import { RequestCollapsedSidebar } from "./RequestCollapsedSidebar";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
let capturedValue: ReturnType<typeof useSidebar> | null = null;
function Capture() {
capturedValue = useSidebar();
return null;
}
// A tiny stand-in for "a route that brings its own sidebar". When `onRoute`
// is true it mounts <RequestCollapsedSidebar/>; flipping it to false models
// navigating away to a route that does not request a collapse.
function Harness({ onRoute }: { onRoute: boolean }) {
return (
<SidebarProvider>
<Capture />
{onRoute ? <RequestCollapsedSidebar /> : null}
</SidebarProvider>
);
}
async function render(onRoute: boolean): Promise<{ root: Root; host: HTMLDivElement }> {
const host = document.createElement("div");
document.body.appendChild(host);
const root = createRoot(host);
await act(async () => root.render(<Harness onRoute={onRoute} />));
return { root, host };
}
describe("RequestCollapsedSidebar", () => {
let active: { root: Root; host: HTMLDivElement } | null = null;
beforeEach(() => {
localStorage.clear();
capturedValue = null;
Object.defineProperty(window, "innerWidth", {
configurable: true,
writable: true,
value: 1280, // desktop: collapsed/peek are meaningful
});
Object.defineProperty(window, "matchMedia", {
configurable: true,
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
// Desktop, hover-capable pointer.
matches: query.includes("(hover: hover)"),
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
});
afterEach(async () => {
if (active) {
await act(async () => active!.root.unmount());
active.host.remove();
active = null;
}
localStorage.clear();
});
it("records the legacy route request without collapsing the global navigation", async () => {
active = await render(true);
expect(capturedValue?.routeRequestsCollapsed).toBe(true);
expect(capturedValue?.collapsed).toBe(false);
});
it("keeps the global navigation expanded when old pin APIs are called", async () => {
active = await render(true);
expect(capturedValue?.collapsed).toBe(false);
flushSync(() => capturedValue?.setCollapsed(true));
expect(capturedValue?.routeRequestsCollapsed).toBe(true);
expect(capturedValue?.collapsed).toBe(false);
});
it("clears the request on unmount, restoring the global default", async () => {
active = await render(true);
expect(capturedValue?.collapsed).toBe(false);
// Navigate away: the route (and its <RequestCollapsedSidebar/>) unmounts.
await act(async () => active!.root.render(<Harness onRoute={false} />));
expect(capturedValue?.routeRequestsCollapsed).toBe(false);
expect(capturedValue?.collapsed).toBe(false);
});
it("clears the request without persisting a retired collapsed pin", async () => {
active = await render(true);
flushSync(() => capturedValue?.setCollapsed(true));
expect(localStorage.getItem("paperclip.sidebar.collapsed")).toBeNull();
await act(async () => active!.root.render(<Harness onRoute={false} />));
expect(capturedValue?.routeRequestsCollapsed).toBe(false);
expect(capturedValue?.collapsed).toBe(false);
});
});
@@ -1,32 +0,0 @@
import { useEffect } from "react";
import { useSidebar } from "../context/SidebarContext";
/**
* Back-compat effect for routes that previously requested the app sidebar's
* retired icon rail. The request remains observable to older integrations,
* but {@link SidebarContext} keeps the global navigation expanded. Cleanup
* still clears the request when the route unmounts.
*
* Drop it anywhere inside a route's element tree:
*
* ```tsx
* function MyPluginPage() {
* return (
* <>
* <RequestCollapsedSidebar />
* …
* </>
* );
* }
* ```
*/
export function RequestCollapsedSidebar() {
const { setRouteRequestsCollapsed } = useSidebar();
useEffect(() => {
setRouteRequestsCollapsed(true);
return () => setRouteRequestsCollapsed(false);
}, [setRouteRequestsCollapsed]);
return null;
}
@@ -1,23 +1,6 @@
import { type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { SidebarNavExpandedProvider } from "./SidebarNavItem.production";
/**
* Fixed-width contextual pane that sits between the collapsed app rail and the
* main content on takeover routes (company settings, plugin `routeSidebar`).
*
* The takeover model (PAP-10695) no longer *replaces* the app `<Sidebar/>`:
* the host collapses it to its 64px rail (still peek-able) and renders the
* contextual sidebar here, yielding `[ rail 64px ][ secondary ~240px ][ content ]`.
*
* It is a dumb container — fixed `w-60`, full-height, non-shrinking, with a
* right border and its own vertical scroll — so callers just drop the
* contextual nav (or a plugin slot mount) inside as `children`.
*
* Because the pane is always 240px wide it forces the full-label presentation
* on any `SidebarNavItem` inside it, so the contextual nav stays readable even
* while the app sidebar is collapsed to its rail (PAP-10700).
*/
export function SecondarySidebar({
children,
className,
@@ -33,7 +16,7 @@ export function SecondarySidebar({
className,
)}
>
<SidebarNavExpandedProvider>{children}</SidebarNavExpandedProvider>
{children}
</div>
);
}
+1 -2
View File
@@ -1,6 +1,5 @@
import { type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { SidebarNavExpandedProvider } from "./SidebarNavItem";
/**
* Content adapter for a contextual sidebar. Depending on the route, Layout
@@ -22,7 +21,7 @@ export function SecondarySidebar({
className,
)}
>
<SidebarNavExpandedProvider>{children}</SidebarNavExpandedProvider>
{children}
</div>
);
}
+8 -30
View File
@@ -31,15 +31,12 @@ import { SidebarProjects } from "./SidebarProjects";
import { SidebarStarredProjects } from "./SidebarStarredProjects.production";
import { useDialogActions } from "../context/DialogContext";
import { useCompany } from "../context/CompanyContext";
import { useSidebar } from "../context/SidebarContext";
import { heartbeatsApi } from "../api/heartbeats";
import { instanceSettingsApi } from "../api/instanceSettings";
import { queryKeys } from "../lib/queryKeys";
import { useAttentionBadge } from "../hooks/useAttentionViews";
import { useInboxBadge } from "../hooks/useInboxBadge";
import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
import { PluginSlotOutlet } from "@/plugins/slots";
import { PluginLauncherOutlet } from "@/plugins/launchers";
import { SidebarCompanyMenu } from "./SidebarCompanyMenu.production";
@@ -51,8 +48,6 @@ export function Sidebar() {
const [workOpen, setWorkOpen] = useState(true);
const [companyOpen, setCompanyOpen] = useState(true);
const { selectedCompanyId, selectedCompany } = useCompany();
const { collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking;
const inboxBadge = useInboxBadge(selectedCompanyId);
const { data: experimentalSettings } = useQuery({
queryKey: queryKeys.instance.experimentalSettings,
@@ -124,31 +119,14 @@ export function Sidebar() {
<nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide flex flex-col gap-4 pointer-coarse:gap-3 px-3 py-2">
<div className="flex flex-col gap-0.5">
{/* New Task button aligned with nav items */}
{(() => {
const newTaskButton = (
<button
onClick={() => openNewIssue()}
data-slot="icon-button"
aria-label={rail ? "New Task" : undefined}
className="flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-foreground/80 hover:bg-accent/50 hover:text-foreground transition-colors"
>
<SquarePen className="h-4 w-4 shrink-0" />
<span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : "truncate"}>New Task</span>
</button>
);
return rail ? (
<Tooltip>
<TooltipTrigger asChild>{newTaskButton}</TooltipTrigger>
<TooltipContent side="right">New Task</TooltipContent>
</Tooltip>
) : (
newTaskButton
);
})()}
{/* Search moved out of the header so the workspace name keeps the
width; a nav row also keeps search reachable from the
collapsed rail, where the old header icon was dropped entirely.
Cmd/Ctrl+K remains the keyboard path (command palette). */}
<button
onClick={() => openNewIssue()}
data-slot="icon-button"
className="flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-foreground/80 hover:bg-accent/50 hover:text-foreground transition-colors"
>
<SquarePen className="h-4 w-4 shrink-0" />
<span className="truncate">New Task</span>
</button>
<SidebarNavItem to="/search" label="Search" icon={Search} />
<SidebarNavItem to="/dashboard" label="Dashboard" icon={LayoutDashboard} liveCount={liveRunCount} />
<SidebarNavItem
-21
View File
@@ -59,11 +59,6 @@ vi.mock("../context/CompanyContext", () => ({
const mockSidebar = vi.hoisted(() => ({
isMobile: false,
setSidebarOpen: vi.fn(),
collapsed: false,
collapseLocked: false,
peeking: false,
toggleCollapsed: vi.fn(),
setCollapsed: vi.fn(),
}));
vi.mock("../context/SidebarContext", () => ({
@@ -164,9 +159,6 @@ describe("Sidebar", () => {
mockHeartbeatsApi.liveRunsForCompany.mockResolvedValue([]);
mockAttentionApi.list.mockResolvedValue({ items: [] });
mockSidebar.isMobile = false;
mockSidebar.collapsed = false;
mockSidebar.collapseLocked = false;
mockSidebar.peeking = false;
mockInboxBadge.inbox = 0;
mockInboxBadge.failedRuns = 0;
});
@@ -326,19 +318,6 @@ describe("Sidebar", () => {
});
});
it("locks the legacy collapse control while a secondary sidebar forces the rail", async () => {
mockSidebar.collapseLocked = true;
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableStreamlinedUi: false });
const root = await renderSidebar();
expect(container.querySelector('button[aria-label="Collapse sidebar"]')).toBeNull();
expect(container.querySelector('button[aria-label="Expand sidebar"]')).toBeNull();
flushSync(() => {
root.unmount();
});
});
it("renders plugin sidebar slots in Work below Workspaces", async () => {
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: true });
const root = await renderSidebar();
+9 -32
View File
@@ -38,7 +38,6 @@ import { useAgentChatNavigation } from "@/hooks/useAgentChatNavigation";
import { SidebarRecentTasks } from "./SidebarRecentTasks";
import { useDialogActions } from "../context/DialogContext";
import { useCompany } from "../context/CompanyContext";
import { useSidebar } from "../context/SidebarContext";
import { heartbeatsApi } from "../api/heartbeats";
import { instanceSettingsApi } from "../api/instanceSettings";
import { queryKeys } from "../lib/queryKeys";
@@ -46,8 +45,7 @@ import { useAttentionBadge } from "../hooks/useAttentionViews";
import { useInboxBadge } from "../hooks/useInboxBadge";
import { useStreamlinedUiEnabled } from "../hooks/useStreamlinedUiEnabled";
import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
import { cn } from "../lib/utils";
import { PluginSlotOutlet } from "@/plugins/slots";
import { PluginLauncherOutlet } from "@/plugins/launchers";
import { SidebarCompanyMenu } from "./SidebarCompanyMenu";
@@ -68,9 +66,7 @@ function ClassicSidebar({ children }: { children?: ReactNode }) {
const [workOpen, setWorkOpen] = useState(true);
const [organizationOpen, setOrganizationOpen] = useState(true);
const { selectedCompanyId, selectedCompany } = useCompany();
const { collapsed, peeking } = useSidebar();
const { enabled: streamlinedUiEnabled } = useStreamlinedUiEnabled();
const rail = collapsed && !peeking;
const inboxBadge = useInboxBadge(selectedCompanyId);
const { data: experimentalSettings } = useQuery({
queryKey: queryKeys.instance.experimentalSettings,
@@ -149,33 +145,14 @@ function ClassicSidebar({ children }: { children?: ReactNode }) {
<nav className={primarySidebarStyles.nav}>
<div className={primarySidebarStyles.group}>
{/* New Task button aligned with nav items */}
{(() => {
const newTaskButton = (
<button
onClick={() => openNewIssue()}
data-slot="icon-button"
aria-label={rail ? "New Task" : undefined}
className={cn(
"flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
)}
>
<SquarePen className="h-4 w-4 shrink-0" />
<span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : "truncate"}>New Task</span>
</button>
);
return rail ? (
<Tooltip>
<TooltipTrigger asChild>{newTaskButton}</TooltipTrigger>
<TooltipContent side="right">New Task</TooltipContent>
</Tooltip>
) : (
newTaskButton
);
})()}
{/* Search moved out of the header so the workspace name keeps the
width; a nav row also keeps search reachable from the
collapsed rail, where the old header icon was dropped entirely.
Cmd/Ctrl+K remains the keyboard path (command palette). */}
<button
onClick={() => openNewIssue()}
data-slot="icon-button"
className="flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
>
<SquarePen className="h-4 w-4 shrink-0" />
<span className="truncate">New Task</span>
</button>
<SidebarNavItem to="/search" label="Search" icon={Search} />
<SidebarNavItem to="/dashboard" label="Dashboard" icon={LayoutDashboard} liveCount={liveRunCount} />
{!combinedInboxTasks ? (
@@ -22,7 +22,7 @@ import { useSidebar } from "../context/SidebarContext";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
import { cn } from "../lib/utils";
import { ThemeToggle } from "./ThemeToggle";
import { SidebarServerInfo } from "./SidebarServerInfo";
@@ -141,8 +141,7 @@ export function SidebarAccountMenu({
!hidesCompanyPage(hiddenSettings, "company.members") &&
!hidesCompanyPage(hiddenSettings, "company.invites");
const [internalOpen, setInternalOpen] = useState(false);
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking;
const { isMobile, setSidebarOpen } = useSidebar();
const open = controlledOpen ?? internalOpen;
const stagingCommit = useStagingCommit(open);
const setOpen = onOpenChange ?? setInternalOpen;
@@ -170,14 +169,14 @@ export function SidebarAccountMenu({
return (
<div className="border-t border-r border-border bg-background px-3 py-2">
<div className={cn("flex items-center gap-0.5", !rail && "px-2")}>
<div className="flex items-center gap-0.5 px-2">
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button
type="button"
className={cn(
"flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-accent/50 hover:text-foreground",
rail ? "w-full px-3 py-2" : "flex-1 px-2 py-1.5",
"flex-1 px-2 py-1.5",
)}
aria-label="Open account menu"
>
@@ -185,7 +184,7 @@ export function SidebarAccountMenu({
{session?.user.image ? <AvatarImage src={session.user.image} alt={displayName} /> : null}
<AvatarFallback>{initials}</AvatarFallback>
</Avatar>
<span className={cn("min-w-0 flex-1 truncate", rail && SIDEBAR_RAIL_HIDDEN_LABEL)}>{displayName}</span>
<span className="min-w-0 flex-1 truncate">{displayName}</span>
</button>
</PopoverTrigger>
<PopoverContent
@@ -276,7 +275,7 @@ export function SidebarAccountMenu({
</div>
</PopoverContent>
</Popover>
{!rail && !isCloud ? (
{!isCloud ? (
<Tooltip>
<TooltipTrigger asChild>
<a
+6 -11
View File
@@ -24,7 +24,7 @@ import { Popover, PopoverTrigger } from "@/components/ui/popover";
import { FlyoutContent, FlyoutHeader, FlyoutOptions } from "@/components/ui/flyout";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
import { cn } from "../lib/utils";
import { ThemeToggle } from "./ThemeToggle";
import { SidebarServerInfo } from "./SidebarServerInfo";
import { TruncatedText } from "./TruncatedText";
@@ -37,9 +37,6 @@ interface SidebarAccountMenuProps {
deploymentMode?: DeploymentMode;
open?: boolean;
onOpenChange?: (open: boolean) => void;
/** Contextual navigation occupies a full sidebar even if the saved global nav mode is collapsed. */
forceExpanded?: boolean;
/** Optional local shadow preview; the shared token remains the default. */
shadow?: CSSProperties["boxShadow"];
}
@@ -121,7 +118,6 @@ export function SidebarAccountMenu({
deploymentMode,
open: controlledOpen,
onOpenChange,
forceExpanded = false,
shadow,
}: SidebarAccountMenuProps) {
const cloud = useCloudInstance();
@@ -145,8 +141,7 @@ export function SidebarAccountMenu({
!hidesCompanyPage(hiddenSettings, "company.members") &&
!hidesCompanyPage(hiddenSettings, "company.invites");
const [internalOpen, setInternalOpen] = useState(false);
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking && !forceExpanded;
const { isMobile, setSidebarOpen } = useSidebar();
const open = controlledOpen ?? internalOpen;
const stagingCommit = useStagingCommit(open);
const setOpen = onOpenChange ?? setInternalOpen;
@@ -174,14 +169,14 @@ export function SidebarAccountMenu({
return (
<div data-sidebar-account="" className="bg-border/50 px-3 py-2 dark:bg-muted">
<div className={cn("flex items-center gap-0.5", !rail && "px-2")}>
<div className="flex items-center gap-0.5 px-2">
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button
type="button"
className={cn(
"flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
rail ? "w-full px-3 py-2" : "flex-1 px-2 py-1.5",
"flex-1 px-2 py-1.5",
)}
aria-label="Open account menu"
>
@@ -189,7 +184,7 @@ export function SidebarAccountMenu({
{session?.user.image ? <AvatarImage src={session.user.image} alt={displayName} /> : null}
<AvatarFallback>{initials}</AvatarFallback>
</Avatar>
<TruncatedText className={cn("min-w-0 flex-1 truncate", rail && SIDEBAR_RAIL_HIDDEN_LABEL)}>{displayName}</TruncatedText>
<TruncatedText className="min-w-0 flex-1 truncate">{displayName}</TruncatedText>
</button>
</PopoverTrigger>
<FlyoutContent
@@ -280,7 +275,7 @@ export function SidebarAccountMenu({
</FlyoutOptions>
</FlyoutContent>
</Popover>
{!rail && !isCloud ? (
{!isCloud ? (
<Tooltip>
<TooltipTrigger asChild>
<a
+4 -31
View File
@@ -28,7 +28,7 @@ import { heartbeatsApi } from "../api/heartbeats";
import { instanceSettingsApi } from "../api/instanceSettings";
import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";
import { queryKeys } from "../lib/queryKeys";
import { cn, agentRouteRef, agentUrl, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
import { cn, agentRouteRef, agentUrl } from "../lib/utils";
import { useAgentOrder } from "../hooks/useAgentOrder";
import {
isStarred,
@@ -58,7 +58,6 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { Agent } from "@paperclipai/shared";
/**
@@ -116,7 +115,6 @@ function SidebarAgentItem({
leaving,
onLeaveAgent,
onPauseResume,
rail,
runCount,
setSidebarOpen,
builtInStatus,
@@ -132,7 +130,6 @@ function SidebarAgentItem({
leaving: boolean;
onLeaveAgent: (agent: Agent) => void;
onPauseResume: (agent: Agent, action: "pause" | "resume") => void;
rail: boolean;
runCount: number;
setSidebarOpen: (open: boolean) => void;
builtInStatus?: BuiltInAgentStatus;
@@ -157,13 +154,6 @@ function SidebarAgentItem({
? "Invalid org chain"
: pauseResumeLabel;
const showBuiltInLifecycle = builtInStatus === "needs_setup" || builtInStatus === "pending_approval";
const trailingLabel = [
showBuiltInLifecycle ? `Built-in agent ${builtInStatus.replace(/_/g, " ")}` : null,
hasInvalidOrgChain ? "Invalid reporting chain" : null,
].filter(Boolean).join(", ") || undefined;
// C11 (DECISION-SHEET.md): the row itself is a SidebarNavItem, so agent rows
// share the nav-row chrome (type, active state, rail tooltip, live dot).
const navItem = (
<SidebarNavItem
to={href}
@@ -188,18 +178,12 @@ function SidebarAgentItem({
</span>
) : undefined
}
trailingLabel={trailingLabel}
liveAccessory={
agent.pauseReason === "budget" ? <BudgetSidebarMarker title="Agent paused by budget" /> : undefined
}
/>
);
// Rail: the star/menu overlays are hidden, so render the nav item bare (it
// supplies its own rail tooltip) and let it fill the column like every other
// rail row.
if (rail) return navItem;
return (
<div className="group/agent relative flex items-center">
{navItem}
@@ -304,8 +288,7 @@ export function SidebarAgents({ streamlined = false }: { streamlined?: boolean }
const { selectedCompanyId } = useCompany();
const primary = usePrimaryAgentPresentation(selectedCompanyId);
const { openNewAgent } = useDialogActions();
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking;
const { isMobile, setSidebarOpen } = useSidebar();
const { pushToast } = useToastActions();
const location = useLocation();
@@ -625,7 +608,6 @@ export function SidebarAgents({ streamlined = false }: { streamlined?: boolean }
leaving={agentLeaving(agent)}
onLeaveAgent={leaveAgent}
onPauseResume={(targetAgent, action) => pauseResumeAgent.mutate({ agent: targetAgent, action })}
rail={rail}
runCount={liveCountByAgent.get(agent.id) ?? 0}
setSidebarOpen={setSidebarOpen}
builtInStatus={builtInStatusByAgentId.get(agent.id)}
@@ -664,28 +646,19 @@ export function SidebarAgents({ streamlined = false }: { streamlined?: boolean }
{showSeeAllLink && (() => {
// Deliberately NOT a SidebarNavItem: this is a quiet muted affordance
// (plain Link) that must not adopt nav-row active-route highlighting.
const seeAllLink = (
return (
<Link
to="/agents/all"
state={SIDEBAR_SCROLL_RESET_STATE}
aria-label={rail ? "See all agents" : undefined}
onClick={() => {
if (isMobile) setSidebarOpen(false);
}}
className="flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
>
<Users className="shrink-0 h-4 w-4" />
<span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : undefined}>See all agents</span>
<span>See all agents</span>
</Link>
);
return rail ? (
<Tooltip>
<TooltipTrigger asChild>{seeAllLink}</TooltipTrigger>
<TooltipContent side="right">See all agents</TooltipContent>
</Tooltip>
) : (
seeAllLink
);
})()}
</SidebarSection>
);
-43
View File
@@ -7,7 +7,6 @@ import type { Agent, ResourceMemberships } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SidebarAgents } from "./SidebarAgents";
import { queryKeys } from "../lib/queryKeys";
import { TooltipProvider } from "@/components/ui/tooltip";
const mockAgentsApi = vi.hoisted(() => ({
list: vi.fn(),
@@ -39,7 +38,6 @@ const mockResourceMembershipsApi = vi.hoisted(() => ({
const mockOpenNewAgent = vi.hoisted(() => vi.fn());
const mockPushToast = vi.hoisted(() => vi.fn());
const mockSetSidebarOpen = vi.hoisted(() => vi.fn());
const mockSidebarState = vi.hoisted(() => ({ collapsed: false, peeking: false }));
vi.mock("@/lib/router", () => ({
Link: ({ children, to, ...props }: { children: ReactNode; to: string }) => (
@@ -85,8 +83,6 @@ vi.mock("../context/SidebarContext", () => ({
useSidebar: () => ({
isMobile: false,
setSidebarOpen: mockSetSidebarOpen,
collapsed: mockSidebarState.collapsed,
peeking: mockSidebarState.peeking,
}),
}));
@@ -219,8 +215,6 @@ describe("SidebarAgents", () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
mockSidebarState.collapsed = false;
mockSidebarState.peeking = false;
container = document.createElement("div");
document.body.appendChild(container);
root = null;
@@ -330,23 +324,6 @@ describe("SidebarAgents", () => {
await flushReact();
}
async function renderRailSidebarAgents() {
mockSidebarState.collapsed = true;
const currentRoot = createRoot(container);
root = currentRoot;
await act(async () => {
currentRoot.render(
<QueryClientProvider client={queryClient}>
<TooltipProvider>
<SidebarAgents streamlined />
</TooltipProvider>
</QueryClientProvider>,
);
});
await flushReact();
}
it.each(["agent", "section"])("finishes deferred %s menu focus cleanup before DOM teardown", async (menu) => {
await renderSidebarAgents();
if (menu === "agent") await openAgentMenu();
@@ -391,26 +368,6 @@ describe("SidebarAgents", () => {
expect(mockBuiltInAgentsApi.list).toHaveBeenCalledWith("company-1");
});
it("renders icon-only agent rows with tooltips and no row actions in the rail", async () => {
mockAgentsApi.list.mockResolvedValue([makeAgent({ id: "agent-a", name: "Alpha", urlKey: "alpha" })]);
await renderRailSidebarAgents();
// The agent name is preserved in the a11y tree but kept in flow (zero-width,
// clipped) so the row stays 1:1 tall with the expanded state (PAP-10676); the
// row links become tooltip triggers and the per-row actions dropdown is dropped.
const nameSpan = Array.from(container.querySelectorAll("span")).find((el) => el.textContent === "Alpha");
expect(nameSpan?.className).not.toContain("sr-only");
expect(nameSpan?.className).toContain("w-0");
expect(nameSpan?.className).toContain("overflow-hidden");
const agentLink = container.querySelector('a[href^="/agents/"]:not([href="/agents/all"])');
expect(agentLink?.parentElement?.getAttribute("data-slot")).toBe("tooltip-trigger");
expect(container.querySelector('button[aria-label="Open actions for Alpha"]')).toBeNull();
// The section header collapses to a divider (no caret / section menu).
expect(container.querySelector('button[aria-label="Agents section actions"]')).toBeNull();
});
it("pins starred agents at the top without subheadings and dedupes them from the recent list", async () => {
mockAgentsApi.list.mockResolvedValue([
makeAgent({ id: "agent-a", name: "Alpha", urlKey: "alpha" }),
+4 -31
View File
@@ -28,7 +28,7 @@ import { heartbeatsApi } from "../api/heartbeats";
import { instanceSettingsApi } from "../api/instanceSettings";
import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";
import { queryKeys } from "../lib/queryKeys";
import { cn, agentRouteRef, agentUrl, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
import { cn, agentRouteRef, agentUrl } from "../lib/utils";
import { useAgentOrder } from "../hooks/useAgentOrder";
import {
isStarred,
@@ -58,7 +58,6 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { Agent } from "@paperclipai/shared";
/**
@@ -116,7 +115,6 @@ function SidebarAgentItem({
leaving,
onLeaveAgent,
onPauseResume,
rail,
runCount,
setSidebarOpen,
builtInStatus,
@@ -132,7 +130,6 @@ function SidebarAgentItem({
leaving: boolean;
onLeaveAgent: (agent: Agent) => void;
onPauseResume: (agent: Agent, action: "pause" | "resume") => void;
rail: boolean;
runCount: number;
setSidebarOpen: (open: boolean) => void;
builtInStatus?: BuiltInAgentStatus;
@@ -157,13 +154,6 @@ function SidebarAgentItem({
? "Invalid org chain"
: pauseResumeLabel;
const showBuiltInLifecycle = builtInStatus === "needs_setup" || builtInStatus === "pending_approval";
const trailingLabel = [
showBuiltInLifecycle ? `Built-in agent ${builtInStatus.replace(/_/g, " ")}` : null,
hasInvalidOrgChain ? "Invalid reporting chain" : null,
].filter(Boolean).join(", ") || undefined;
// C11 (DECISION-SHEET.md): the row itself is a SidebarNavItem, so agent rows
// share the nav-row chrome (type, active state, rail tooltip, live dot).
const navItem = (
<SidebarNavItem
to={href}
@@ -188,18 +178,12 @@ function SidebarAgentItem({
</span>
) : undefined
}
trailingLabel={trailingLabel}
liveAccessory={
agent.pauseReason === "budget" ? <BudgetSidebarMarker title="Agent paused by budget" /> : undefined
}
/>
);
// Rail: the star/menu overlays are hidden, so render the nav item bare (it
// supplies its own rail tooltip) and let it fill the column like every other
// rail row.
if (rail) return navItem;
return (
<div className="group/agent relative flex items-center">
{navItem}
@@ -304,8 +288,7 @@ export function SidebarAgents({ streamlined = false }: { streamlined?: boolean }
const { selectedCompanyId } = useCompany();
const primary = usePrimaryAgentPresentation(selectedCompanyId);
const { openNewAgent } = useDialogActions();
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking;
const { isMobile, setSidebarOpen } = useSidebar();
const { pushToast } = useToastActions();
const location = useLocation();
@@ -625,7 +608,6 @@ export function SidebarAgents({ streamlined = false }: { streamlined?: boolean }
leaving={agentLeaving(agent)}
onLeaveAgent={leaveAgent}
onPauseResume={(targetAgent, action) => pauseResumeAgent.mutate({ agent: targetAgent, action })}
rail={rail}
runCount={liveCountByAgent.get(agent.id) ?? 0}
setSidebarOpen={setSidebarOpen}
builtInStatus={builtInStatusByAgentId.get(agent.id)}
@@ -664,28 +646,19 @@ export function SidebarAgents({ streamlined = false }: { streamlined?: boolean }
{showSeeAllLink && (() => {
// Deliberately NOT a SidebarNavItem: this is a quiet muted affordance
// (plain Link) that must not adopt nav-row active-route highlighting.
const seeAllLink = (
return (
<Link
to="/agents/all"
state={SIDEBAR_SCROLL_RESET_STATE}
aria-label={rail ? "See all agents" : undefined}
onClick={() => {
if (isMobile) setSidebarOpen(false);
}}
className="flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-muted-foreground transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
>
<Users className="shrink-0 h-4 w-4" />
<span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : undefined}>See all agents</span>
<span>See all agents</span>
</Link>
);
return rail ? (
<Tooltip>
<TooltipTrigger asChild>{seeAllLink}</TooltipTrigger>
<TooltipContent side="right">See all agents</TooltipContent>
</Tooltip>
) : (
seeAllLink
);
})()}
</SidebarSection>
);
@@ -38,7 +38,7 @@ import { useHiddenSettings } from "@/hooks/useHiddenSettings";
import { useCompanyOrder } from "@/hooks/useCompanyOrder";
import { useSignOut } from "@/hooks/useSignOut";
import { queryKeys } from "@/lib/queryKeys";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "@/lib/utils";
import { cn } from "@/lib/utils";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { useSidebar } from "../context/SidebarContext";
import { CompanyPatternIcon } from "./CompanyPatternIcon";
@@ -159,8 +159,7 @@ function BuiltinCompanyMenu({ open: controlledOpen, onOpenChange }: SidebarCompa
const { companies, selectedCompany, setSelectedCompanyId, companyListUnavailable, retryCompanies } =
useCompany();
const { openOnboarding } = useDialogActions();
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking;
const { isMobile, setSidebarOpen } = useSidebar();
const location = useLocation();
const navigate = useNavigate();
const open = controlledOpen ?? internalOpen;
@@ -280,16 +279,13 @@ function BuiltinCompanyMenu({ open: controlledOpen, onOpenChange }: SidebarCompa
the nav to buy that width. A name that still
truncates stays hover-recoverable via title. */}
<span
className={cn(
"min-w-0 truncate text-sm font-bold text-foreground",
rail && SIDEBAR_RAIL_HIDDEN_LABEL,
)}
className="min-w-0 truncate text-sm font-bold text-foreground"
title={currentName ?? undefined}
>
{currentName ?? `Select ${switcherNoun}`}
</span>
</span>
{!rail && <ChevronsUpDown className="size-3.5 shrink-0 text-muted-foreground" />}
<ChevronsUpDown className="size-3.5 shrink-0 text-muted-foreground" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
+4 -8
View File
@@ -38,7 +38,7 @@ import { useHiddenSettings } from "@/hooks/useHiddenSettings";
import { useCompanyOrder } from "@/hooks/useCompanyOrder";
import { useSignOut } from "@/hooks/useSignOut";
import { queryKeys } from "@/lib/queryKeys";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "@/lib/utils";
import { cn } from "@/lib/utils";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { useSidebar } from "../context/SidebarContext";
import { CompanyPatternIcon } from "./CompanyPatternIcon";
@@ -163,8 +163,7 @@ function BuiltinCompanyMenu({ open: controlledOpen, onOpenChange, showChevron =
const { companies, selectedCompany, setSelectedCompanyId, companyListUnavailable, retryCompanies } =
useCompany();
const { openOnboarding } = useDialogActions();
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking;
const { isMobile, setSidebarOpen } = useSidebar();
const location = useLocation();
const navigate = useNavigate();
const open = controlledOpen ?? internalOpen;
@@ -285,16 +284,13 @@ function BuiltinCompanyMenu({ open: controlledOpen, onOpenChange, showChevron =
truncates stays hover-recoverable via title. */}
<TruncatedText
marqueeResetKey={open}
className={cn(
"min-w-0 truncate text-sm font-bold text-foreground",
rail && SIDEBAR_RAIL_HIDDEN_LABEL,
)}
className="min-w-0 truncate text-sm font-bold text-foreground"
title={currentName ?? undefined}
>
{currentName ?? `Select ${switcherNoun}`}
</TruncatedText>
</span>
{!rail && showChevron && <ChevronsUpDown className="size-3.5 shrink-0 text-muted-foreground" />}
{showChevron && <ChevronsUpDown className="size-3.5 shrink-0 text-muted-foreground" />}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
+9 -102
View File
@@ -1,37 +1,11 @@
import { createContext, useContext, type ReactNode } from "react";
import type { ReactNode } from "react";
import { NavLink } from "@/lib/router";
import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
import { cn } from "../lib/utils";
import { useSidebar } from "../context/SidebarContext";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { LucideIcon } from "lucide-react";
import { Badge } from "@/components/ui/badge";
/**
* Forces the full-label (non-rail) presentation for any `SidebarNavItem`
* rendered beneath it, regardless of the global `useSidebar().collapsed` state.
*
* Takeover routes (PAP-10695) collapse the app `<Sidebar/>` to its 64px rail
* and render the contextual nav in a fixed 240px `SecondarySidebar`. That pane
* is always wide enough for labels, but its `SidebarNavItem` children still
* read the *global* `collapsed=true` and would otherwise render icon-only —
* leaving the settings nav unreadable (PAP-10700). Wrapping the pane in this
* provider decouples its items from the global rail collapse.
*/
const SidebarNavExpandedContext = createContext(false);
export function SidebarNavExpandedProvider({ children }: { children: ReactNode }) {
return (
<SidebarNavExpandedContext.Provider value={true}>
{children}
</SidebarNavExpandedContext.Provider>
);
}
export function useSidebarNavExpanded() {
return useContext(SidebarNavExpandedContext);
}
interface SidebarNavItemProps {
to: string;
label: string;
@@ -47,10 +21,6 @@ interface SidebarNavItemProps {
labelClassName?: string;
badge?: number;
badgeTone?: "default" | "danger" | "warning";
/**
* Accessible noun for the numeric badge when collapsed to the rail, where the
* count is rendered as a dot (e.g. `badgeLabel="unread"` → "Inbox, 28 unread").
*/
badgeLabel?: string;
textBadge?: string;
textBadgeTone?: "default" | "amber";
@@ -63,8 +33,6 @@ interface SidebarNavItemProps {
active?: boolean;
/** Rendered after the label, before the right-aligned status cluster. */
trailing?: ReactNode;
/** Accessible text for `trailing` status content, surfaced in the collapsed rail (where `trailing` is hidden). */
trailingLabel?: string;
/** Rendered inside the right-aligned status cluster, before the live dot. */
liveAccessory?: ReactNode;
}
@@ -86,40 +54,17 @@ export function SidebarNavItem({
liveCount,
active,
trailing,
trailingLabel,
liveAccessory,
}: SidebarNavItemProps) {
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
// A fixed-width contextual pane (SecondarySidebar) forces full labels even
// when the global app sidebar is collapsed to its rail (PAP-10700).
const forceExpanded = useSidebarNavExpanded();
// The icon-only rail presentation only applies when pinned collapsed and not
// peeking; a peek/expanded panel — or an expanded contextual pane — restores
// the full label + badge.
const rail = collapsed && !peeking && !forceExpanded;
const { isMobile, setSidebarOpen } = useSidebar();
const hasBadge = badge != null && badge > 0;
const hasLive = liveCount != null && liveCount > 0;
// Accessible text equivalent for the collapsed dot indicator. The visible
// label is `sr-only` in the rail, so the count must be surfaced here.
const railStatusText = hasLive
? `${liveCount} live`
: hasBadge
? `${badge}${badgeLabel ? ` ${badgeLabel}` : ""}`
: alert
? "attention needed"
: undefined;
const railAriaLabel = !rail || (!railStatusText && !trailingLabel)
? undefined
: `${label}${railStatusText ? `, ${railStatusText}` : ""}${trailingLabel ? `, ${trailingLabel}` : ""}`;
const link = (
return (
<NavLink
to={to}
state={SIDEBAR_SCROLL_RESET_STATE}
end={end}
aria-label={railAriaLabel}
onClick={() => { if (isMobile) setSidebarOpen(false); }}
className={({ isActive }) =>
cn(
@@ -140,31 +85,10 @@ export function SidebarNavItem({
{alert && (
<span className="absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-red-500 shadow-(--shadow-extract-12)" aria-hidden="true" />
)}
{/* Collapsed rail: numeric badge / live count collapse to a dot on the
icon. The icon markup is untouched so it stays pixel-aligned. */}
{rail && !alert && hasLive && (
<span className="absolute -right-0.5 -top-0.5 flex h-2 w-2" aria-hidden="true">
<span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75" />
<span className="relative inline-flex h-2 w-2 rounded-full bg-blue-600 dark:bg-blue-400 shadow-(--shadow-extract-12)" />
</span>
)}
{rail && !alert && !hasLive && hasBadge && (
<span
className={cn(
"absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-extract-12)",
badgeTone === "danger"
? "bg-red-600"
: badgeTone === "warning"
? "bg-amber-500"
: "bg-primary",
)}
aria-hidden="true"
/>
)}
</span>
<span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : cn("min-w-0 flex-1 truncate", labelClassName)}>{label}</span>
{!rail && trailing}
{!rail && textBadge && (
<span className={cn("min-w-0 flex-1 truncate", labelClassName)}>{label}</span>
{trailing}
{textBadge && (
<Badge variant="ghost"
className={cn(
"ml-auto px-1.5 text-(length:--text-nano) leading-none",
@@ -176,7 +100,7 @@ export function SidebarNavItem({
{textBadge}
</Badge>
)}
{!rail && (hasLive || liveAccessory) && (
{(hasLive || liveAccessory) && (
<span className="ml-auto flex items-center gap-1.5">
{liveAccessory}
{hasLive && (
@@ -190,7 +114,7 @@ export function SidebarNavItem({
)}
</span>
)}
{!rail && hasBadge && (
{hasBadge && (
<Badge variant="ghost"
className={cn(
"ml-auto px-1.5 leading-none",
@@ -206,21 +130,4 @@ export function SidebarNavItem({
)}
</NavLink>
);
if (!rail) return link;
// The tooltip wraps a plain block element rather than the NavLink directly:
// Radix `asChild` (Slot) drops React Router's *function* className, which would
// strip `flex` off the <a> and render it as a block — the in-flow label would
// then stack under the icon and the row would grow. Anchoring the tooltip to a
// wrapper keeps the <a> rendering normally (flex), so the row stays 1:1 with
// the expanded state and the icon never moves (PAP-10676).
return (
<Tooltip>
<TooltipTrigger asChild>
<div>{link}</div>
</TooltipTrigger>
<TooltipContent side="right">{label}</TooltipContent>
</Tooltip>
);
}
+1 -83
View File
@@ -5,14 +5,12 @@ import type { ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Inbox } from "lucide-react";
import { SidebarNavItem, SidebarNavExpandedProvider } from "./SidebarNavItem";
import { SidebarNavItem } from "./SidebarNavItem";
import { TooltipProvider } from "@/components/ui/tooltip";
const sidebarState = vi.hoisted(() => ({
isMobile: false,
setSidebarOpen: () => {},
collapsed: false,
peeking: false,
}));
vi.mock("@/lib/router", () => ({
@@ -43,8 +41,6 @@ describe("SidebarNavItem", () => {
let root: Root;
beforeEach(() => {
sidebarState.collapsed = false;
sidebarState.peeking = false;
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
@@ -114,82 +110,4 @@ describe("SidebarNavItem", () => {
expect(classTokens(link())).not.toContain("hover:bg-background");
});
it("clips the label (kept in flow for 1:1 row height) and collapses the badge to a dot in the rail", () => {
sidebarState.collapsed = true;
render(<SidebarNavItem to="/inbox" label="Inbox" icon={Inbox} badge={28} badgeLabel="unread" />);
// The label stays in the DOM/a11y tree (not display:none) so screen readers
// still announce it. Unlike sr-only it is kept IN FLOW (zero-width, clipped,
// transparent) so it still contributes its line-height — that keeps the row
// exactly as tall as the expanded state, so the icon never shifts (PAP-10676).
const label = Array.from(container.querySelectorAll("span")).find((el) => el.textContent === "Inbox");
expect(label).toBeTruthy();
expect(label?.className).not.toContain("sr-only");
expect(classTokens(label)).toContain("w-0");
expect(classTokens(label)).toContain("overflow-hidden");
// The numeric count is no longer rendered as text; it is a dot with an
// accessible text equivalent on the link.
expect(container.textContent).not.toContain("28 ");
expect(link().getAttribute("aria-label")).toBe("Inbox, 28 unread");
// Tooltip wraps the row; the trigger is the wrapper element so the NavLink's
// own flex className is preserved (PAP-10676), with the <a> nested inside it.
expect(link().parentElement?.getAttribute("data-slot")).toBe("tooltip-trigger");
});
it("surfaces the trailing status label in the rail aria-label", () => {
sidebarState.collapsed = true;
render(
<SidebarNavItem
to="/agents/codexcoder"
label="CodexCoder"
icon={Inbox}
trailing={<span aria-label="Invalid reporting chain" />}
trailingLabel="Invalid reporting chain"
/>,
);
// The trailing warning is hidden in the rail, so its text equivalent must
// ride on the link's accessible name.
expect(link().getAttribute("aria-label")).toBe("CodexCoder, Invalid reporting chain");
});
it("keeps the full presentation while peeking even when collapsed", () => {
sidebarState.collapsed = true;
sidebarState.peeking = true;
render(<SidebarNavItem to="/inbox" label="Inbox" icon={Inbox} badge={28} badgeLabel="unread" />);
const label = Array.from(container.querySelectorAll("span")).find((el) => el.textContent === "Inbox");
expect(label?.className).not.toContain("sr-only");
expect(container.textContent).toContain("28");
expect(link().getAttribute("aria-label")).toBeNull();
});
it("forces the full label inside an expanded contextual pane even when globally collapsed", () => {
// The takeover preserves the user's saved global collapse preference while
// replacing its contents. The provider keeps the contextual navigation
// readable without changing that preference.
sidebarState.collapsed = true;
render(
<SidebarNavExpandedProvider>
<SidebarNavItem to="/inbox" label="Inbox" icon={Inbox} badge={28} badgeLabel="unread" />
</SidebarNavExpandedProvider>,
);
const label = Array.from(container.querySelectorAll("span")).find((el) => el.textContent === "Inbox");
expect(classTokens(label)).not.toContain("w-0");
expect(classTokens(label)).toContain("flex-1");
// Full numeric badge, no rail aria-label, no tooltip wrapper.
expect(container.textContent).toContain("28");
expect(link().getAttribute("aria-label")).toBeNull();
expect(link().parentElement?.getAttribute("data-slot")).not.toBe("tooltip-trigger");
});
it("surfaces the live count in the rail aria-label", () => {
sidebarState.collapsed = true;
render(<SidebarNavItem to="/dashboard" label="Dashboard" icon={Inbox} liveCount={3} />);
expect(link().getAttribute("aria-label")).toBe("Dashboard, 3 live");
});
});
+10 -101
View File
@@ -1,37 +1,13 @@
import { createContext, useContext, type ReactNode } from "react";
import type { ReactNode } from "react";
import { NavLink } from "@/lib/router";
import type { IssueNavigationPrefetchHandlers } from "@/hooks/useIssueNavigationPrefetch";
import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
import { cn } from "../lib/utils";
import { useSidebar } from "../context/SidebarContext";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { LucideIcon } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { TruncatedText } from "./TruncatedText";
/**
* Forces the full-label (non-rail) presentation for any `SidebarNavItem`
* rendered beneath it, regardless of the global `useSidebar().collapsed` state.
*
* Contextual takeover routes replace the global navigation inside the same
* sidebar shell. The user's saved global collapse preference can still be
* `collapsed=true`, so this provider keeps contextual navigation readable
* without mutating that preference.
*/
const SidebarNavExpandedContext = createContext(false);
export function SidebarNavExpandedProvider({ children }: { children: ReactNode }) {
return (
<SidebarNavExpandedContext.Provider value={true}>
{children}
</SidebarNavExpandedContext.Provider>
);
}
export function useSidebarNavExpanded() {
return useContext(SidebarNavExpandedContext);
}
interface SidebarNavItemProps {
to: string;
label: string;
@@ -47,10 +23,6 @@ interface SidebarNavItemProps {
labelClassName?: string;
badge?: number;
badgeTone?: "default" | "danger" | "warning";
/**
* Accessible noun for the numeric badge when collapsed to the rail, where the
* count is rendered as a dot (e.g. `badgeLabel="unread"` → "Inbox, 28 unread").
*/
badgeLabel?: string;
textBadge?: string;
textBadgeTone?: "default" | "amber";
@@ -63,8 +35,6 @@ interface SidebarNavItemProps {
active?: boolean;
/** Rendered after the label, before the right-aligned status cluster. */
trailing?: ReactNode;
/** Accessible text for `trailing` status content, surfaced in the collapsed rail (where `trailing` is hidden). */
trailingLabel?: string;
/** Rendered inside the right-aligned status cluster, before the live dot. */
liveAccessory?: ReactNode;
/** Extra link handlers, such as a task's open-intent prefetch. */
@@ -88,42 +58,19 @@ export function SidebarNavItem({
liveCount,
active,
trailing,
trailingLabel,
liveAccessory,
linkHandlers,
}: SidebarNavItemProps) {
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
// A contextual takeover forces full labels even when the saved global app
// sidebar preference is collapsed.
const forceExpanded = useSidebarNavExpanded();
// The icon-only rail presentation only applies when pinned collapsed and not
// peeking; a peek/expanded panel — or a contextual takeover — restores
// the full label + badge.
const rail = collapsed && !peeking && !forceExpanded;
const { isMobile, setSidebarOpen } = useSidebar();
const hasBadge = badge != null && badge > 0;
const hasLive = liveCount != null && liveCount > 0;
const showIconSlot = Boolean(iconNode || Icon || alert || (rail && (hasLive || hasBadge)));
const showIconSlot = Boolean(iconNode || Icon || alert);
// Accessible text equivalent for the collapsed dot indicator. The visible
// label is `sr-only` in the rail, so the count must be surfaced here.
const railStatusText = hasLive
? `${liveCount} live`
: hasBadge
? `${badge}${badgeLabel ? ` ${badgeLabel}` : ""}`
: alert
? "attention needed"
: undefined;
const railAriaLabel = !rail || (!railStatusText && !trailingLabel)
? undefined
: `${label}${railStatusText ? `, ${railStatusText}` : ""}${trailingLabel ? `, ${trailingLabel}` : ""}`;
const link = (
return (
<NavLink
to={to}
state={SIDEBAR_SCROLL_RESET_STATE}
end={end}
aria-label={railAriaLabel}
{...linkHandlers}
onClick={() => { if (isMobile) setSidebarOpen(false); }}
className={({ isActive }) =>
@@ -150,32 +97,11 @@ export function SidebarNavItem({
aria-hidden="true"
/>
)}
{/* Collapsed rail: numeric badge / live count collapse to a dot on the
icon. The icon markup is untouched so it stays pixel-aligned. */}
{rail && !alert && hasLive && (
<span className="absolute -right-0.5 -top-0.5 flex h-2 w-2" aria-hidden="true">
<span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75" />
<span className="relative inline-flex h-2 w-2 rounded-full bg-blue-600 dark:bg-blue-400 shadow-(--shadow-sidebar-icon-badge)" />
</span>
)}
{rail && !alert && !hasLive && hasBadge && (
<span
className={cn(
"absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-sidebar-icon-badge)",
badgeTone === "danger"
? "bg-red-600"
: badgeTone === "warning"
? "bg-amber-500"
: "bg-primary",
)}
aria-hidden="true"
/>
)}
</span>
) : null}
<TruncatedText className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : cn("min-w-0 flex-1 truncate", labelClassName)}>{label}</TruncatedText>
{!rail && trailing}
{!rail && textBadge && (
<TruncatedText className={cn("min-w-0 flex-1 truncate", labelClassName)}>{label}</TruncatedText>
{trailing}
{textBadge && (
<Badge variant="ghost"
className={cn(
"ml-auto px-1.5 text-(length:--text-nano) leading-none",
@@ -187,7 +113,7 @@ export function SidebarNavItem({
{textBadge}
</Badge>
)}
{!rail && (hasLive || liveAccessory) && (
{(hasLive || liveAccessory) && (
<span className="ml-auto flex shrink-0 items-center gap-1.5 whitespace-nowrap">
{liveAccessory}
{hasLive && (
@@ -201,7 +127,7 @@ export function SidebarNavItem({
)}
</span>
)}
{!rail && hasBadge && (
{hasBadge && (
<Badge variant="ghost"
aria-label={badgeLabel ? `${badge} ${badgeLabel}` : undefined}
className={cn(
@@ -218,21 +144,4 @@ export function SidebarNavItem({
)}
</NavLink>
);
if (!rail) return link;
// The tooltip wraps a plain block element rather than the NavLink directly:
// Radix `asChild` (Slot) drops React Router's *function* className, which would
// strip `flex` off the <a> and render it as a block — the in-flow label would
// then stack under the icon and the row would grow. Anchoring the tooltip to a
// wrapper keeps the <a> rendering normally (flex), so the row stays 1:1 with
// the expanded state and the icon never moves (PAP-10676).
return (
<Tooltip>
<TooltipTrigger asChild>
<div>{link}</div>
</TooltipTrigger>
<TooltipContent side="right">{label}</TooltipContent>
</Tooltip>
);
}
+1 -40
View File
@@ -7,7 +7,6 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Project, ResourceMemberships } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SidebarProjects } from "./SidebarProjects";
import { TooltipProvider } from "@/components/ui/tooltip";
const mockProjectsApi = vi.hoisted(() => ({
list: vi.fn(),
@@ -29,7 +28,7 @@ const mockOpenNewProject = vi.hoisted(() => vi.fn());
const mockPushToast = vi.hoisted(() => vi.fn());
const mockSetSidebarOpen = vi.hoisted(() => vi.fn());
const mockPersistOrder = vi.hoisted(() => vi.fn());
const mockSidebarState = vi.hoisted(() => ({ isMobile: false, collapsed: false, peeking: false }));
const mockSidebarState = vi.hoisted(() => ({ isMobile: false }));
const mockPointerState = vi.hoisted(() => ({ fine: true }));
vi.mock("@/lib/router", () => ({
@@ -77,8 +76,6 @@ vi.mock("../context/SidebarContext", () => ({
useSidebar: () => ({
isMobile: mockSidebarState.isMobile,
setSidebarOpen: mockSetSidebarOpen,
collapsed: mockSidebarState.collapsed,
peeking: mockSidebarState.peeking,
}),
}));
@@ -246,8 +243,6 @@ describe("SidebarProjects", () => {
});
localStorage.clear();
mockSidebarState.isMobile = false;
mockSidebarState.collapsed = false;
mockSidebarState.peeking = false;
mockPointerState.fine = true;
Object.defineProperty(window, "matchMedia", {
writable: true,
@@ -347,40 +342,6 @@ describe("SidebarProjects", () => {
await flushReact();
}
async function renderRailSidebarProjects() {
mockSidebarState.collapsed = true;
const currentRoot = createRoot(container);
root = currentRoot;
await act(async () => {
currentRoot.render(
<QueryClientProvider client={queryClient}>
<TooltipProvider>
<SidebarProjects />
</TooltipProvider>
</QueryClientProvider>,
);
});
await flushReact();
}
it("renders icon-only project rows with tooltips and no row actions in the rail", async () => {
await renderRailSidebarProjects();
// Project names stay in the a11y tree but kept in flow (zero-width, clipped)
// so rows stay 1:1 tall with the expanded state (PAP-10676); rows become
// tooltip triggers and the per-row actions dropdown is dropped.
const nameSpan = Array.from(container.querySelectorAll("span")).find((el) => el.textContent === "Bravo");
expect(nameSpan?.className).not.toContain("sr-only");
expect(nameSpan?.className).toContain("w-0");
expect(nameSpan?.className).toContain("overflow-hidden");
const projectLink = container.querySelector('a[href^="/projects/"]');
expect(projectLink?.parentElement?.getAttribute("data-slot")).toBe("tooltip-trigger");
expect(container.querySelector('button[aria-label="Open actions for Bravo"]')).toBeNull();
// The section header collapses to a divider (no section menu trigger).
expect(container.querySelector('button[aria-label="Projects section actions"]')).toBeNull();
});
it("keeps top mode in curated order and renders plugin project slots", async () => {
await renderSidebarProjects();
+8 -30
View File
@@ -18,7 +18,7 @@ import { useSidebar } from "../context/SidebarContext";
import { authApi } from "../api/auth";
import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";
import { queryKeys } from "../lib/queryKeys";
import { cn, projectRouteRef, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
import { cn, projectRouteRef } from "../lib/utils";
import { useProjectOrder } from "../hooks/useProjectOrder";
import { resourceMembershipState, useResourceMembershipMutation, useResourceMemberships } from "../hooks/useResourceMemberships";
import { useProjectExternalObjectSummary } from "../hooks/useIssueExternalObjects";
@@ -33,7 +33,6 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { PluginSlotMount, usePluginSlots } from "@/plugins/slots";
import {
getProjectSortModeStorageKey,
@@ -62,7 +61,6 @@ type ProjectItemProps = {
isMobile: boolean;
project: Project;
projectSidebarSlots: ProjectSidebarSlot[];
rail: boolean;
setSidebarOpen: (open: boolean) => void;
onLeaveProject: (project: Project) => void;
leaving?: boolean;
@@ -117,7 +115,6 @@ function ProjectItem({
isMobile,
project,
projectSidebarSlots,
rail,
setSidebarOpen,
onLeaveProject,
leaving = false,
@@ -145,33 +142,18 @@ function ProjectItem({
)}
>
<ProjectTile color={project.color ?? null} icon={project.icon ?? null} size="xs" />
<span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : "flex-1 truncate"}>{project.name}</span>
{!rail && project.visibility === "private" ? <Lock className="size-3.5 shrink-0 text-muted-foreground" aria-label="Private project" /> : null}
{!rail ? <ExternalObjectStatusSummary summary={externalObjectsSummary} compact /> : null}
{!rail && project.pauseReason === "budget" ? <BudgetSidebarMarker title="Project paused by budget" /> : null}
<span className="flex-1 truncate">{project.name}</span>
{project.visibility === "private" ? <Lock className="size-3.5 shrink-0 text-muted-foreground" aria-label="Private project" /> : null}
<ExternalObjectStatusSummary summary={externalObjectsSummary} compact />
{project.pauseReason === "budget" ? <BudgetSidebarMarker title="Project paused by budget" /> : null}
</NavLink>
);
return (
<div className="flex flex-col gap-0.5">
<div className="group/project relative flex items-center">
{rail ? (
// Anchor the tooltip to a wrapper, not the NavLink: Radix `asChild`
// (Slot) drops React Router's function className, which would strip
// `flex` off the <a> and let the in-flow label stack under the icon,
// growing the row. Keeping the <a> out of Slot preserves a 1:1 row
// height with the expanded state so the icon never moves (PAP-10676).
<Tooltip>
<TooltipTrigger asChild>
<div className="min-w-0 flex-1">{link}</div>
</TooltipTrigger>
<TooltipContent side="right">{project.name}</TooltipContent>
</Tooltip>
) : (
link
)}
{link}
{!rail && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
@@ -201,9 +183,8 @@ function ProjectItem({
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
{!rail && projectSidebarSlots.length > 0 && (
{projectSidebarSlots.length > 0 && (
<div className="ml-5 flex flex-col gap-0.5">
{projectSidebarSlots.map((slot) => (
<PluginSlotMount
@@ -257,8 +238,7 @@ export function SidebarProjects() {
const [open, setOpen] = useState(true);
const { selectedCompany, selectedCompanyId } = useCompany();
const { openNewProject } = useDialogActions();
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking;
const { isMobile, setSidebarOpen } = useSidebar();
const fineReorderPointer = useFineReorderPointer();
const location = useLocation();
@@ -400,7 +380,6 @@ export function SidebarProjects() {
isMobile={isMobile}
project={project}
projectSidebarSlots={projectSidebarSlots}
rail={rail}
setSidebarOpen={setSidebarOpen}
onLeaveProject={leaveProject}
leaving={projectLeaving(project)}
@@ -448,7 +427,6 @@ export function SidebarProjects() {
isMobile={isMobile}
project={project}
projectSidebarSlots={projectSidebarSlots}
rail={rail}
setSidebarOpen={setSidebarOpen}
onLeaveProject={leaveProject}
leaving={projectLeaving(project)}
@@ -49,8 +49,6 @@ vi.mock("@/lib/router", () => ({
}));
vi.mock("@/context/SidebarContext", () => ({
useSidebar: () => ({
collapsed: false,
peeking: false,
isMobile: false,
setSidebarOpen: vi.fn(),
}),
+44 -53
View File
@@ -7,7 +7,6 @@ import { queryKeys } from "@/lib/queryKeys";
import { useRecentTasks } from "@/hooks/useRecentTasks";
import { useRecentTaskOpenWarmup } from "@/hooks/useRecentTaskOpenWarmup";
import { useAccountIdentity } from "@/api/companies-query";
import { useSidebar } from "@/context/SidebarContext";
import { useOptionalToastActions } from "@/context/ToastContext";
import {
recordRecentTask,
@@ -80,8 +79,6 @@ export function SidebarRecentTasks({
companyId: string | null | undefined;
liveIssueIds: ReadonlySet<string>;
}) {
const { collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking;
const { userId, settled } = useAccountIdentity();
if (!companyId || !settled) return null;
@@ -92,7 +89,6 @@ export function SidebarRecentTasks({
companyId={companyId}
userId={userId}
liveIssueIds={liveIssueIds}
rail={rail}
/>
);
}
@@ -101,12 +97,10 @@ function RecentTasksList({
companyId,
userId,
liveIssueIds,
rail,
}: {
companyId: string;
userId: string | null;
liveIssueIds: ReadonlySet<string>;
rail: boolean;
}) {
const { entries } = useRecentTasks({ companyId, userId });
const { pathname } = useLocation();
@@ -260,62 +254,59 @@ function RecentTasksList({
iconNode={entry.displayStatus === "monitoring" && !liveIssueIds.has(entry.id) ? <StatusIcon {...taskStatusIconProps(entry)} /> : undefined}
trailing={entry.status === "in_review" && entry.externalConversationState === "waiting"
? <span className="text-xs text-muted-foreground">Idle</span> : undefined}
trailingLabel={entry.status === "in_review" && entry.externalConversationState === "waiting" ? "Idle" : undefined}
className={rail ? undefined : "sidebar-action-link pointer-coarse:pr-8"}
className="sidebar-action-link pointer-coarse:pr-8"
liveCount={liveIssueIds.has(entry.id) ? 1 : undefined}
/>
{!rail ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label={`More actions for ${entry.title}`}
className="sidebar-action-menu absolute right-2 top-(--pct-50) z-10 -translate-y-(--pct-50) text-muted-foreground pointer-events-none opacity-0 transition-opacity hover:bg-sidebar-accent dark:hover:bg-sidebar-accent hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 pointer-coarse:pointer-events-auto pointer-coarse:opacity-100 pointer-coarse:before:hidden group-hover/recent-task:pointer-events-auto group-hover/recent-task:opacity-100 group-focus-within/recent-task:pointer-events-auto group-focus-within/recent-task:opacity-100 data-[state=open]:pointer-events-auto data-[state=open]:bg-sidebar-accent data-[state=open]:text-foreground data-[state=open]:opacity-100"
>
<MoreHorizontal aria-hidden="true" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
side="right"
align="start"
className="w-(--profile-popover-width) rounded-xl p-1.5 shadow-(--shadow-profile-popover)"
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label={`More actions for ${entry.title}`}
className="sidebar-action-menu absolute right-2 top-(--pct-50) z-10 -translate-y-(--pct-50) text-muted-foreground pointer-events-none opacity-0 transition-opacity hover:bg-sidebar-accent dark:hover:bg-sidebar-accent hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 pointer-coarse:pointer-events-auto pointer-coarse:opacity-100 pointer-coarse:before:hidden group-hover/recent-task:pointer-events-auto group-hover/recent-task:opacity-100 group-focus-within/recent-task:pointer-events-auto group-focus-within/recent-task:opacity-100 data-[state=open]:pointer-events-auto data-[state=open]:bg-sidebar-accent data-[state=open]:text-foreground data-[state=open]:opacity-100"
>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
onSelect={() => beginRename(entry)}
>
<Pencil aria-hidden="true" />
Rename
</DropdownMenuItem>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
disabled={pendingAction !== null}
onSelect={() => void archiveTask(entry)}
>
<Archive aria-hidden="true" />
Archive
</DropdownMenuItem>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
disabled={pendingAction !== null}
onSelect={() => void toggleTaskPause(entry)}
>
<RefreshCw aria-hidden="true" />
Pause/Restart
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : null}
<MoreHorizontal aria-hidden="true" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
side="right"
align="start"
className="w-(--profile-popover-width) rounded-xl p-1.5 shadow-(--shadow-profile-popover)"
>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
onSelect={() => beginRename(entry)}
>
<Pencil aria-hidden="true" />
Rename
</DropdownMenuItem>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
disabled={pendingAction !== null}
onSelect={() => void archiveTask(entry)}
>
<Archive aria-hidden="true" />
Archive
</DropdownMenuItem>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
disabled={pendingAction !== null}
onSelect={() => void toggleTaskPause(entry)}
>
<RefreshCw aria-hidden="true" />
Pause/Restart
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
);
return (
<>
<SidebarSection label="Recent Tasks">
{entries.filter(entry => rail || !hierarchy.nestedIds.has(entry.id)).map((entry) => (
<RecentTaskGroup key={entry.id} task={entry} userId={userId} rail={rail} flattened={hierarchy.flattenedIds.has(entry.id)}
{entries.filter(entry => !hierarchy.nestedIds.has(entry.id)).map((entry) => (
<RecentTaskGroup key={entry.id} task={entry} userId={userId} flattened={hierarchy.flattenedIds.has(entry.id)}
selectedChild={hierarchy.selectedChild?.parentId === entry.id ? hierarchy.selectedChild : undefined} renderChild={renderTaskRow}>
{renderTaskRow(entry)}
</RecentTaskGroup>
-82
View File
@@ -5,13 +5,10 @@ import type { ReactNode } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SidebarSection } from "./SidebarSection";
import { SidebarNavExpandedProvider } from "./SidebarNavItem";
import { Plus } from "lucide-react";
const sidebarState = vi.hoisted(() => ({
isMobile: false,
collapsed: false,
peeking: false,
}));
vi.mock("@/lib/router", () => ({
@@ -59,8 +56,6 @@ describe("SidebarSection", () => {
beforeEach(() => {
sidebarState.isMobile = false;
sidebarState.collapsed = false;
sidebarState.peeking = false;
container = document.createElement("div");
document.body.appendChild(container);
root = null;
@@ -163,30 +158,6 @@ describe("SidebarSection", () => {
expect(staticLabelControl?.getAttribute("class")).not.toContain("focus-visible:bg-accent/50");
});
it("keeps section labels visible inside an expanded contextual pane", async () => {
sidebarState.collapsed = true;
const currentRoot = createRoot(container);
root = currentRoot;
await act(async () => {
currentRoot.render(
<SidebarNavExpandedProvider>
<SidebarSection label="Settings">
<a href="/settings">General</a>
</SidebarSection>
</SidebarNavExpandedProvider>,
);
});
await flushReact();
const settingsLabel = Array.from(container.querySelectorAll("span"))
.find((element) => element.textContent === "Settings");
expect(settingsLabel).toBeTruthy();
expect(settingsLabel?.getAttribute("class")).toContain("uppercase");
expect(container.querySelector(".bg-border\\/60")).toBeNull();
});
it("keeps the header action outside the label menu hit area", async () => {
const onAction = vi.fn();
const currentRoot = createRoot(container);
@@ -291,59 +262,6 @@ describe("SidebarSection", () => {
expect(onAction).toHaveBeenCalledTimes(1);
});
it("replaces the header with a divider and drops the caret in the collapsed rail", async () => {
sidebarState.collapsed = true;
const currentRoot = createRoot(container);
root = currentRoot;
await act(async () => {
currentRoot.render(
<SidebarSection
label="Projects"
collapsible={{ open: true, onOpenChange: vi.fn() }}
menu={{
ariaLabel: "Projects section actions",
actions: [{ type: "item", label: "Browse projects", href: "/projects" }],
}}
>
<a href="/projects">Projects</a>
</SidebarSection>,
);
});
await flushReact();
// The clipped header text is gone; the caret/menu trigger is not rendered.
expect(container.querySelector('button[aria-label="Collapse Projects"]')).toBeNull();
expect(container.querySelector('button[aria-label="Projects section actions"]')).toBeNull();
// The label is preserved in the a11y tree (sr-only) and the items still render.
const label = Array.from(container.querySelectorAll("span"))
.find((element) => element.textContent === "Projects");
expect(label?.className).toContain("sr-only");
expect(container.querySelector('a[href="/projects"]')).toBeTruthy();
});
it("restores the full header while peeking even when collapsed", async () => {
sidebarState.collapsed = true;
sidebarState.peeking = true;
const currentRoot = createRoot(container);
root = currentRoot;
await act(async () => {
currentRoot.render(
<SidebarSection label="Projects" collapsible={{ open: true, onOpenChange: vi.fn() }}>
<a href="/projects">Projects</a>
</SidebarSection>,
);
});
await flushReact();
const label = Array.from(container.querySelectorAll("span"))
.find((element) => element.textContent === "Projects");
expect(label?.className).not.toContain("sr-only");
expect(container.querySelector('button[aria-label="Collapse Projects"]')).toBeTruthy();
});
it("keeps section header controls visible on mobile", async () => {
sidebarState.isMobile = true;
const currentRoot = createRoot(container);
-27
View File
@@ -18,7 +18,6 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";
import { useSidebarNavExpanded } from "./SidebarNavItem";
type SidebarSectionIcon = ComponentType<{ className?: string }>;
@@ -190,34 +189,8 @@ export function SidebarSection({
menu,
headerAction,
}: SidebarSectionProps) {
const { collapsed, peeking } = useSidebar();
const forceExpanded = useSidebarNavExpanded();
const rail = collapsed && !peeking && !forceExpanded;
const content = <div className="flex flex-col gap-0.5 mt-0.5">{children}</div>;
// Collapsed rail: the section header would only show a clipped sliver of its
// label, so replace it with a thin divider. The label stays in the a11y tree,
// per-section carets/menus are dropped (no room + no toggle target in the
// rail), and the items always render so their icons stay reachable.
//
// The header wrapper mirrors the expanded header's vertical footprint exactly
// (outer `px-3 py-1.5 pointer-coarse:py-1` + inner `min-h-6`) so item icons land
// at the identical y-position in both states — no movement on collapse/expand
// (PAP-10676). The divider is vertically centered within that same row.
if (rail) {
return (
<div>
<div className="px-3 py-1.5 pointer-coarse:py-1">
<div className="flex min-h-6 items-center">
<span className="sr-only">{label}</span>
<div className="h-px w-full bg-border/60" aria-hidden="true" />
</div>
</div>
{content}
</div>
);
}
if (collapsible) {
return (
<Collapsible open={collapsible.open} onOpenChange={collapsible.onOpenChange}>
+5 -77
View File
@@ -4,9 +4,7 @@ import {
useMemo,
useRef,
useState,
type FocusEventHandler,
type KeyboardEvent,
type MouseEventHandler,
type PointerEvent,
type ReactNode,
} from "react";
@@ -17,14 +15,6 @@ const MIN_SIDEBAR_WIDTH = 208;
const MAX_SIDEBAR_WIDTH = 420;
const SIDEBAR_WIDTH_STEP = 16;
// Collapsed icon rail. Width is chosen so the icon is *centered* in the rail,
// which keeps the active/hover highlight symmetric around it (PAP-10676):
// the icon's left edge sits at nav px-3 (12) + item px-3 (12) = 24px, so a
// matching 24px trailing margin (12 item px-3 + 12 nav px-3) yields
// 24 + 16 (icon) + 24 = 64. The icon's left edge is unchanged from the expanded
// layout, so icons stay pixel-identical across states.
export const SIDEBAR_RAIL_WIDTH = 64;
function clampSidebarWidth(width: number) {
return Math.min(MAX_SIDEBAR_WIDTH, Math.max(MIN_SIDEBAR_WIDTH, width));
}
@@ -57,49 +47,17 @@ type SidebarShellProps = {
children: ReactNode;
/** Whether the sidebar occupies space at all (mobile back-compat / hidden). */
open: boolean;
/** Pinned collapsed (rail) mode. Desktop-only; the caller gates this. */
collapsed?: boolean;
/** Ephemeral hover/focus peek. Only meaningful while collapsed. */
peeking?: boolean;
resizable?: boolean;
storageKey?: string;
className?: string;
/** Forwarded to the overlay panel so Layout can wire peek triggers. */
onPanelMouseEnter?: MouseEventHandler<HTMLDivElement>;
onPanelMouseLeave?: MouseEventHandler<HTMLDivElement>;
onPanelFocusCapture?: FocusEventHandler<HTMLDivElement>;
onPanelBlurCapture?: FocusEventHandler<HTMLDivElement>;
};
/**
* Layout shell for the desktop sidebar. Owns the persisted expanded width and
* renders two layers:
* - an in-flow spacer that reserves `reservedWidth` (rail when collapsed,
* expanded width otherwise) so content to the right only reflows on pin, and
* - an absolutely-positioned panel of `panelWidth` (rail at rest, expanded
* while peeking) that overlays content — with shadow/raised z-index — when it
* is wider than the reserved spacer.
*
* The icon-alignment guarantee comes for free: collapsing is a pure width
* change with `overflow-hidden` clipping the labels; item padding/icon markup
* are never touched, so the left-aligned icon stays pixel-identical.
*
* Opening/closing is intentionally instant (no width transition): the pin toggle
* and peek snap between rail and expanded widths so the content never appears to
* slide. Resizing the drag handle is likewise direct.
*/
export function SidebarShell({
children,
open,
collapsed = false,
peeking = false,
resizable = false,
storageKey = "paperclip.sidebar.width",
className,
onPanelMouseEnter,
onPanelMouseLeave,
onPanelFocusCapture,
onPanelBlurCapture,
}: SidebarShellProps) {
const [width, setWidth] = useState(() => readStoredSidebarWidth(storageKey));
const [isResizing, setIsResizing] = useState(false);
@@ -112,24 +70,8 @@ export function SidebarShell({
setWidth(storedWidth);
}, [storageKey]);
// Unified width function (plan §5): one code path for every pinned state.
const expandedWidth = open ? width : 0;
const reservedWidth = !open ? 0 : collapsed ? SIDEBAR_RAIL_WIDTH : expandedWidth;
const panelWidth = !open ? 0 : collapsed && !peeking ? SIDEBAR_RAIL_WIDTH : expandedWidth;
const isOverlay = panelWidth > reservedWidth;
// The drag handle can only resize the expanded width, so it is disabled while
// collapsed (the rail width is a fixed constant, not user-resizable).
const canResize = resizable && open && !collapsed;
const reservedStyle = useMemo(
() => ({ width: `${reservedWidth}px` }),
[reservedWidth],
);
const panelStyle = useMemo(
() => ({ width: `${panelWidth}px` }),
[panelWidth],
);
const canResize = resizable && open;
const sidebarStyle = useMemo(() => ({ width: open ? `${width}px` : "0px" }), [open, width]);
const commitWidth = useCallback(
(nextWidth: number) => {
@@ -195,24 +137,10 @@ export function SidebarShell({
);
return (
<div className={cn("relative h-full shrink-0", className)} style={reservedStyle}>
<div className={cn("relative h-full shrink-0", className)} style={sidebarStyle}>
<div
className={cn(
"absolute inset-y-0 left-0 flex flex-col overflow-hidden",
// Open/close is instant (PAP-10676): no width transition so the rail and
// expanded states snap without any sliding motion.
// Overlay styling only while the panel is wider than its reserved
// spacer (i.e. peeking) so it floats above content without reflow.
isOverlay
? "z-30 border-r border-border bg-background shadow-lg"
: "z-0",
)}
style={panelStyle}
data-sidebar-overlay={isOverlay ? "" : undefined}
onMouseEnter={onPanelMouseEnter}
onMouseLeave={onPanelMouseLeave}
onFocusCapture={onPanelFocusCapture}
onBlurCapture={onPanelBlurCapture}
className="absolute inset-y-0 left-0 flex flex-col overflow-hidden z-0"
style={sidebarStyle}
>
{children}
{canResize ? (
+4 -43
View File
@@ -3,7 +3,7 @@
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SidebarShell, SIDEBAR_RAIL_WIDTH } from "./SidebarShell";
import { SidebarShell } from "./SidebarShell";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
@@ -174,31 +174,12 @@ describe("SidebarShell", () => {
expect(panel().style.width).toBe("240px");
});
it("reserves only the rail width when collapsed and hides the resize handle", () => {
it("hides all sidebar width when closed", () => {
window.localStorage.setItem("test.sidebar.width", "320");
act(() => {
root.render(
<SidebarShell open collapsed resizable storageKey="test.sidebar.width">
<div>Sidebar</div>
</SidebarShell>,
);
});
// Reserved spacer and panel both collapse to the rail; content never reflows
// beyond the rail, and the rail is not user-resizable.
expect(spacer().style.width).toBe(`${SIDEBAR_RAIL_WIDTH}px`);
expect(panel().style.width).toBe(`${SIDEBAR_RAIL_WIDTH}px`);
expect(panel().getAttribute("data-sidebar-overlay")).toBeNull();
expect(handle()).toBeNull();
});
it("hides all sidebar width when closed, even if pinned collapsed", () => {
window.localStorage.setItem("test.sidebar.width", "320");
act(() => {
root.render(
<SidebarShell open={false} collapsed resizable storageKey="test.sidebar.width">
<SidebarShell open={false} resizable storageKey="test.sidebar.width">
<div>Sidebar</div>
</SidebarShell>,
);
@@ -210,27 +191,7 @@ describe("SidebarShell", () => {
expect(handle()).toBeNull();
});
it("overlays content while peeking without expanding the reserved spacer", () => {
window.localStorage.setItem("test.sidebar.width", "300");
act(() => {
root.render(
<SidebarShell open collapsed peeking storageKey="test.sidebar.width">
<div>Sidebar</div>
</SidebarShell>,
);
});
// The reserved spacer stays at the rail (no page reflow) while the panel
// grows to the expanded width and gets overlay styling.
expect(spacer().style.width).toBe(`${SIDEBAR_RAIL_WIDTH}px`);
expect(panel().style.width).toBe("300px");
expect(panel().getAttribute("data-sidebar-overlay")).toBe("");
expect(panel().className).toContain("shadow-lg");
expect(panel().className).toContain("z-30");
});
it("opens and closes instantly with no width transition (PAP-10676)", () => {
it("opens and closes instantly with no width transition", () => {
act(() => {
root.render(
<SidebarShell open>
+6 -78
View File
@@ -4,9 +4,7 @@ import {
useMemo,
useRef,
useState,
type FocusEventHandler,
type KeyboardEvent,
type MouseEventHandler,
type PointerEvent,
type ReactNode,
} from "react";
@@ -18,14 +16,6 @@ const MIN_SIDEBAR_WIDTH = 208;
const MAX_SIDEBAR_WIDTH = 420;
const SIDEBAR_WIDTH_STEP = 16;
// Collapsed icon rail. Width is chosen so the icon is *centered* in the rail,
// which keeps the active/hover highlight symmetric around it (PAP-10676):
// the icon's left edge sits at nav px-3 (12) + item px-3 (12) = 24px, so a
// matching 24px trailing margin (12 item px-3 + 12 nav px-3) yields
// 24 + 16 (icon) + 24 = 64. The icon's left edge is unchanged from the expanded
// layout, so icons stay pixel-identical across states.
export const SIDEBAR_RAIL_WIDTH = 64;
function clampSidebarWidth(width: number) {
return Math.min(MAX_SIDEBAR_WIDTH, Math.max(MIN_SIDEBAR_WIDTH, width));
}
@@ -58,49 +48,17 @@ type SidebarShellProps = {
children: ReactNode;
/** Whether the sidebar occupies space at all (mobile back-compat / hidden). */
open: boolean;
/** Pinned collapsed (rail) mode. Desktop-only; the caller gates this. */
collapsed?: boolean;
/** Ephemeral hover/focus peek. Only meaningful while collapsed. */
peeking?: boolean;
resizable?: boolean;
storageKey?: string;
className?: string;
/** Forwarded to the overlay panel so Layout can wire peek triggers. */
onPanelMouseEnter?: MouseEventHandler<HTMLDivElement>;
onPanelMouseLeave?: MouseEventHandler<HTMLDivElement>;
onPanelFocusCapture?: FocusEventHandler<HTMLDivElement>;
onPanelBlurCapture?: FocusEventHandler<HTMLDivElement>;
};
/**
* Layout shell for the desktop sidebar. Owns the persisted expanded width and
* renders two layers:
* - an in-flow spacer that reserves `reservedWidth` (rail when collapsed,
* expanded width otherwise) so content to the right only reflows on pin, and
* - an absolutely-positioned panel of `panelWidth` (rail at rest, expanded
* while peeking) that overlays content — with shadow/raised z-index — when it
* is wider than the reserved spacer.
*
* The icon-alignment guarantee comes for free: collapsing is a pure width
* change with `overflow-hidden` clipping the labels; item padding/icon markup
* are never touched, so the left-aligned icon stays pixel-identical.
*
* Opening/closing is intentionally instant (no width transition): the pin toggle
* and peek snap between rail and expanded widths so the content never appears to
* slide. Resizing the drag handle is likewise direct; only double-click reset animates.
*/
export function SidebarShell({
children,
open,
collapsed = false,
peeking = false,
resizable = false,
storageKey = "paperclip.sidebar.width",
className,
onPanelMouseEnter,
onPanelMouseLeave,
onPanelFocusCapture,
onPanelBlurCapture,
}: SidebarShellProps) {
const [width, setWidth] = useState(() => readStoredSidebarWidth(storageKey));
const [isResizing, setIsResizing] = useState(false);
@@ -116,26 +74,10 @@ export function SidebarShell({
setWidth(storedWidth);
}, [storageKey, cancelReset]);
useEffect(() => { cancelReset(); }, [open, collapsed, peeking, cancelReset]);
useEffect(() => { cancelReset(); }, [open, cancelReset]);
// Unified width function (plan §5): one code path for every pinned state.
const expandedWidth = open ? width : 0;
const reservedWidth = !open ? 0 : collapsed ? SIDEBAR_RAIL_WIDTH : expandedWidth;
const panelWidth = !open ? 0 : collapsed && !peeking ? SIDEBAR_RAIL_WIDTH : expandedWidth;
const isOverlay = panelWidth > reservedWidth;
// The drag handle can only resize the expanded width, so it is disabled while
// collapsed (the rail width is a fixed constant, not user-resizable).
const canResize = resizable && open && !collapsed;
const reservedStyle = useMemo(
() => ({ width: `${reservedWidth}px` }),
[reservedWidth],
);
const panelStyle = useMemo(
() => ({ width: `${panelWidth}px` }),
[panelWidth],
);
const canResize = resizable && open;
const sidebarStyle = useMemo(() => ({ width: open ? `${width}px` : "0px" }), [open, width]);
const commitWidth = useCallback(
(nextWidth: number, animate = false) => {
@@ -208,25 +150,11 @@ export function SidebarShell({
);
return (
<div ref={shellRef} className={cn("sidebar-shell relative h-full shrink-0", className)} style={reservedStyle}
<div ref={shellRef} className={cn("sidebar-shell relative h-full shrink-0", className)} style={sidebarStyle}
data-width-resetting={resetting && canResize && !isResizing || undefined} onTransitionEnd={onResetTransitionEnd}>
<div
className={cn(
"sidebar-shell-panel absolute inset-y-0 left-0 flex flex-col overflow-hidden",
// Open/close is instant (PAP-10676): no width transition so the rail and
// expanded states snap without any sliding motion.
// Overlay styling only while the panel is wider than its reserved
// spacer (i.e. peeking) so it floats above content without reflow.
isOverlay
? "z-30 border-r border-border bg-background shadow-lg"
: "z-0",
)}
style={panelStyle}
data-sidebar-overlay={isOverlay ? "" : undefined}
onMouseEnter={onPanelMouseEnter}
onMouseLeave={onPanelMouseLeave}
onFocusCapture={onPanelFocusCapture}
onBlurCapture={onPanelBlurCapture}
className="sidebar-shell-panel absolute inset-y-0 left-0 flex flex-col overflow-hidden z-0"
style={sidebarStyle}
>
{children}
</div>
@@ -5,7 +5,7 @@ import { Lock, Loader2, LogOut, MoreHorizontal, Star } from "lucide-react";
import { useCompany } from "../context/CompanyContext";
import { useSidebar } from "../context/SidebarContext";
import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";
import { cn, projectRouteRef, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
import { cn, projectRouteRef } from "../lib/utils";
import {
isStarred,
starredResourceIds,
@@ -23,7 +23,6 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { Project } from "@paperclipai/shared";
import { companyProjectsQuery } from "@/lib/company-projects-query";
@@ -40,8 +39,7 @@ const STAR_ROW_REVEAL =
*/
export function SidebarStarredProjects() {
const { selectedCompanyId } = useCompany();
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking;
const { isMobile, setSidebarOpen } = useSidebar();
const location = useLocation();
const { data: projects } = useQuery({
@@ -120,16 +118,16 @@ export function SidebarStarredProjects() {
}}
className={cn(
"flex min-w-0 flex-1 items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 pr-8 text-(length:--text-compact) font-medium transition-colors",
!rail && "pl-6",
"pl-6",
isActive
? "bg-accent text-foreground"
: "text-foreground/80 hover:bg-accent/50 hover:text-foreground",
)}
>
<ProjectTile color={project.color ?? null} icon={project.icon ?? null} size="xs" />
<span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : "flex-1 truncate"}>{project.name}</span>
{!rail && project.visibility === "private" ? <Lock className="size-3.5 shrink-0 text-muted-foreground" aria-label="Private project" /> : null}
{!rail && project.pauseReason === "budget" ? (
<span className="flex-1 truncate">{project.name}</span>
{project.visibility === "private" ? <Lock className="size-3.5 shrink-0 text-muted-foreground" aria-label="Private project" /> : null}
{project.pauseReason === "budget" ? (
<BudgetSidebarMarker title="Project paused by budget" />
) : null}
</NavLink>
@@ -137,18 +135,9 @@ export function SidebarStarredProjects() {
return (
<div key={project.id} className="group/starred-project relative flex items-center">
{rail ? (
<Tooltip>
<TooltipTrigger asChild>
<div className="min-w-0 flex-1">{link}</div>
</TooltipTrigger>
<TooltipContent side="right">{project.name}</TooltipContent>
</Tooltip>
) : (
link
)}
{link}
{!rail && !isMobile ? (
{!isMobile ? (
// Desktop: quiet inline unstar revealed on hover/focus.
<span className="absolute right-3 top-1/2 -translate-y-1/2">
<StarToggle
@@ -163,7 +152,7 @@ export function SidebarStarredProjects() {
</span>
) : null}
{!rail && isMobile ? (
{isMobile ? (
// Touch: explicit ⋯ menu (no hover). Star action + separated Leave.
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -13,7 +13,7 @@ const mockProjectsApi = vi.hoisted(() => ({ list: vi.fn() }));
const mockResourceMembershipsApi = vi.hoisted(() => ({ listMine: vi.fn(), updateProject: vi.fn() }));
const mockPushToast = vi.hoisted(() => vi.fn());
const mockSetSidebarOpen = vi.hoisted(() => vi.fn());
const mockSidebarState = vi.hoisted(() => ({ isMobile: false, collapsed: false, peeking: false }));
const mockSidebarState = vi.hoisted(() => ({ isMobile: false }));
vi.mock("@/lib/router", () => ({
NavLink: ({ children, className, to, ...props }: {
@@ -36,8 +36,6 @@ vi.mock("../context/SidebarContext", () => ({
useSidebar: () => ({
isMobile: mockSidebarState.isMobile,
setSidebarOpen: mockSetSidebarOpen,
collapsed: mockSidebarState.collapsed,
peeking: mockSidebarState.peeking,
}),
}));
@@ -124,8 +122,6 @@ describe("SidebarStarredProjects", () => {
beforeEach(() => {
mockSidebarState.isMobile = false;
mockSidebarState.collapsed = false;
mockSidebarState.peeking = false;
container = document.createElement("div");
document.body.appendChild(container);
root = null;
@@ -181,7 +177,7 @@ describe("SidebarStarredProjects", () => {
expect(document.body.querySelector('button[aria-label="Unstar Bravo"]')).not.toBeNull();
});
it("keeps starred projects indented only outside the collapsed rail", async () => {
it("indents starred projects", async () => {
mockProjectsApi.list.mockResolvedValue([
makeProject({ id: "project-a", name: "Alpha", urlKey: "alpha" }),
]);
@@ -190,19 +186,6 @@ describe("SidebarStarredProjects", () => {
await render();
expect(projectLink(container, "alpha")?.className).toContain("pl-6");
await act(async () => root?.unmount());
root = null;
container.innerHTML = "";
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
mockSidebarState.collapsed = true;
await render();
const railProjectLink = projectLink(container, "alpha");
expect(railProjectLink?.className).not.toContain("pl-6");
const nameSpan = Array.from(container.querySelectorAll("span")).find((el) => el.textContent === "Alpha");
expect(nameSpan?.className).toContain("w-0");
});
it("renders nothing when no projects are starred", async () => {
+9 -20
View File
@@ -5,7 +5,7 @@ import { Lock, Loader2, LogOut, MoreHorizontal, Star } from "lucide-react";
import { useCompany } from "../context/CompanyContext";
import { useSidebar } from "../context/SidebarContext";
import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";
import { cn, projectRouteRef, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
import { cn, projectRouteRef } from "../lib/utils";
import {
isStarred,
starredResourceIds,
@@ -23,7 +23,6 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { Project } from "@paperclipai/shared";
import { companyProjectsQuery } from "@/lib/company-projects-query";
@@ -40,8 +39,7 @@ const STAR_ROW_REVEAL =
*/
export function SidebarStarredProjects() {
const { selectedCompanyId } = useCompany();
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking;
const { isMobile, setSidebarOpen } = useSidebar();
const location = useLocation();
const { data: projects } = useQuery({
@@ -120,16 +118,16 @@ export function SidebarStarredProjects() {
}}
className={cn(
"flex min-w-0 flex-1 items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 pr-8 text-(length:--text-compact) font-medium transition-colors",
!rail && "pl-6",
"pl-6",
isActive
? "bg-sidebar-accent text-sidebar-accent-foreground"
: "text-foreground/80 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
)}
>
<ProjectTile color={project.color ?? null} icon={project.icon ?? null} size="xs" />
<span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : "flex-1 truncate"}>{project.name}</span>
{!rail && project.visibility === "private" ? <Lock className="size-3.5 shrink-0 text-muted-foreground" aria-label="Private project" /> : null}
{!rail && project.pauseReason === "budget" ? (
<span className="flex-1 truncate">{project.name}</span>
{project.visibility === "private" ? <Lock className="size-3.5 shrink-0 text-muted-foreground" aria-label="Private project" /> : null}
{project.pauseReason === "budget" ? (
<BudgetSidebarMarker title="Project paused by budget" />
) : null}
</NavLink>
@@ -137,18 +135,9 @@ export function SidebarStarredProjects() {
return (
<div key={project.id} className="group/starred-project relative flex items-center">
{rail ? (
<Tooltip>
<TooltipTrigger asChild>
<div className="min-w-0 flex-1">{link}</div>
</TooltipTrigger>
<TooltipContent side="right">{project.name}</TooltipContent>
</Tooltip>
) : (
link
)}
{link}
{!rail && !isMobile ? (
{!isMobile ? (
// Desktop: quiet inline unstar revealed on hover/focus.
<span className="absolute right-3 top-1/2 -translate-y-1/2">
<StarToggle
@@ -163,7 +152,7 @@ export function SidebarStarredProjects() {
</span>
) : null}
{!rail && isMobile ? (
{isMobile ? (
// Touch: explicit ⋯ menu (no hover). Star action + separated Leave.
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -20,7 +20,6 @@ vi.mock("@/context/SidebarContext", () => ({
useSidebar: () => ({ isMobile: false, setSidebarOpen: vi.fn() }),
}));
vi.mock("./SidebarNavItem", () => ({
SidebarNavExpandedProvider: ({ children }: { children: React.ReactNode }) => children,
SidebarNavItem: (props: { to: string; label: string; active?: boolean }) => {
sidebarNavItemMock(props);
return <a href={props.to} aria-current={props.active ? "page" : undefined}>{props.label}</a>;
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more