mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-21 16:27:18 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Governed MCP access spans contracts, runtime enforcement, adapters, UI surfaces, and operator verification > - The parity reference PR #9534 is too large for effective automated or human review > - The feature therefore needs a linear stack whose individual diffs stay below the 100-file review limit > - This pull request is split 6/8 and focuses on UI API, shared components, and Tools/Profile surfaces > - The benefit is a standalone, testable review boundary while preserving byte-for-byte parity at the top of the stack ## Linked Issues or Issue Description - Related parity reference: #9534 - Problem: Operators need typed clients and administration surfaces that compile independently before navigation exposes them. - Proposed solution: Adds UI APIs, hooks, libraries, shared components, Tools/Profiles pages, and the plugin settings consumer required by the new company-scoped API. - Alternatives considered: keeping #9534 as one 403-file review, or rewriting the feature to manufacture seams; both were rejected in favor of path extraction plus compile-driven boundary moves. - Roadmap alignment: this advances the existing governed MCP/tool-access work already represented by #9534; it does not introduce a separate roadmap initiative. - Stack position: base branch is `pap10341-split/05-runtime-integration`. - Merge policy: merge bottom-up, in order, only after the complete eight-PR stack has been reviewed and the top-of-stack parity gate remains empty. - Requested review: UXDesigner sanity pass on Tools/Profile surfaces; Greptile on every PR. ## What Changed - Adds UI APIs, hooks, libraries, shared components, Tools/Profiles pages, and the plugin settings consumer required by the new company-scoped API. - Keeps this PR below 100 changed files and independently typecheckable. - Preserves the final tree from #9534 when combined with the other seven stack levels. ## Verification - `pnpm typecheck` - `pnpm check:token-gates` — all gates clean - Focused UI Vitest run with `NODE_ENV=test` — 28 files, 183 tests passed ## Risks - Large dead-code UI additions can drift from activation routes; PR 7 supplies the registration layer and top-level parity catches omissions. - Stack risk: merging out of order can expose incomplete layers; mitigate by following the documented bottom-up merge policy. - Parity risk: later edits to an intermediate branch can drift from #9534; mitigate by re-running the empty top-of-stack diff before merge. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - OpenAI Codex, exact model ID `gpt-5.4`; runtime-managed context window; medium reasoning with repository, shell, Git, GitHub CLI, and code-execution tools enabled. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] Internal references are omitted except the execution-plan link explicitly required for this coordinated split stack - [x] My branch name describes the change and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge ## Stack Coordination - Internal execution plan: [PAP-13874](/PAP/issues/PAP-13874#document-plan) - Parity reference: #9534 - Stack: #9556 → #9557 → #9558 → #9559 → #9560 → #9561 → #9562 → #9563 - Merge bottom-up only after full-stack review and an empty parity diff at #9563. ## UI Evidence QA captured these from the live Garden MCP split stack at 1440px and verified clean rendering:    --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
164 lines
5.7 KiB
TypeScript
164 lines
5.7 KiB
TypeScript
import { getPageVisibility, getVisibilityHeaderValue } from "@/lib/page-visibility";
|
|
|
|
const BASE = "/api";
|
|
|
|
export class ApiError extends Error {
|
|
status: number;
|
|
body: unknown;
|
|
|
|
constructor(message: string, status: number, body: unknown) {
|
|
super(message);
|
|
this.name = "ApiError";
|
|
this.status = status;
|
|
this.body = body;
|
|
}
|
|
}
|
|
|
|
export interface RequestOptions {
|
|
/** Abort signal wired through to `fetch` and coalescing (per-caller). */
|
|
signal?: AbortSignal;
|
|
}
|
|
|
|
function abortError(): DOMException {
|
|
return new DOMException("The operation was aborted.", "AbortError");
|
|
}
|
|
|
|
/**
|
|
* Non-authoritative observability hints (PAP-12556 / Phase 1). The server treats
|
|
* these as scheduling/telemetry only and never as security signals.
|
|
*/
|
|
function applyObservabilityHeaders(headers: Headers) {
|
|
if (headers.has("X-Paperclip-Tab-Visible")) return; // caller override wins
|
|
const visibility = getPageVisibility();
|
|
headers.set("X-Paperclip-Tab-Visible", getVisibilityHeaderValue(visibility));
|
|
if (typeof window !== "undefined" && window.location) {
|
|
headers.set("X-Paperclip-Route", window.location.pathname);
|
|
}
|
|
}
|
|
|
|
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
|
const headers = new Headers(init?.headers ?? undefined);
|
|
const body = init?.body;
|
|
if (!(body instanceof FormData) && !headers.has("Content-Type")) {
|
|
headers.set("Content-Type", "application/json");
|
|
}
|
|
applyObservabilityHeaders(headers);
|
|
|
|
const res = await fetch(`${BASE}${path}`, {
|
|
headers,
|
|
credentials: "include",
|
|
...init,
|
|
});
|
|
if (!res.ok) {
|
|
const errorBody = await res.json().catch(() => null);
|
|
throw new ApiError(
|
|
(errorBody as { error?: string } | null)?.error ?? `Request failed: ${res.status}`,
|
|
res.status,
|
|
errorBody,
|
|
);
|
|
}
|
|
if (res.status === 204) return undefined as T;
|
|
return res.json();
|
|
}
|
|
|
|
// --- In-tab request coalescing for identical safe GETs -----------------------
|
|
//
|
|
// Multiple callers issuing the same GET while one is in flight share a single
|
|
// underlying fetch. Each caller keeps its own abort semantics: aborting one
|
|
// caller only cancels the shared fetch when *every* caller has aborted.
|
|
// Mutations are never coalesced.
|
|
|
|
interface InflightGet {
|
|
promise: Promise<unknown>;
|
|
controller: AbortController;
|
|
refs: Set<symbol>;
|
|
}
|
|
|
|
const inflightGets = new Map<string, InflightGet>();
|
|
|
|
function coalescedGet<T>(path: string, options?: RequestOptions): Promise<T> {
|
|
const signal = options?.signal;
|
|
if (signal?.aborted) return Promise.reject(abortError());
|
|
|
|
let entry = inflightGets.get(path);
|
|
if (!entry) {
|
|
const controller = new AbortController();
|
|
const promise = request<T>(path, { method: "GET", signal: controller.signal });
|
|
const created: InflightGet = { promise, controller, refs: new Set() };
|
|
// Clear the shared entry once settled so later calls issue a fresh request.
|
|
promise.then(
|
|
() => {
|
|
if (inflightGets.get(path) === created) inflightGets.delete(path);
|
|
},
|
|
() => {
|
|
if (inflightGets.get(path) === created) inflightGets.delete(path);
|
|
},
|
|
);
|
|
inflightGets.set(path, created);
|
|
entry = created;
|
|
}
|
|
|
|
const activeEntry = entry;
|
|
const ref = Symbol("caller");
|
|
activeEntry.refs.add(ref);
|
|
|
|
const releaseRef = () => {
|
|
if (!activeEntry.refs.delete(ref)) return;
|
|
// Last caller gone before the fetch settled → abort the shared request.
|
|
if (activeEntry.refs.size === 0 && inflightGets.get(path) === activeEntry) {
|
|
inflightGets.delete(path);
|
|
activeEntry.controller.abort();
|
|
}
|
|
};
|
|
|
|
return new Promise<T>((resolve, reject) => {
|
|
const onAbort = () => {
|
|
signal?.removeEventListener("abort", onAbort);
|
|
releaseRef();
|
|
reject(abortError());
|
|
};
|
|
if (signal) signal.addEventListener("abort", onAbort);
|
|
|
|
activeEntry.promise.then(
|
|
(value) => {
|
|
signal?.removeEventListener("abort", onAbort);
|
|
activeEntry.refs.delete(ref);
|
|
resolve(value as T);
|
|
},
|
|
(err) => {
|
|
signal?.removeEventListener("abort", onAbort);
|
|
activeEntry.refs.delete(ref);
|
|
reject(err);
|
|
},
|
|
);
|
|
});
|
|
}
|
|
|
|
/** Test-only: number of in-flight coalesced GET keys. */
|
|
export function __inflightGetCount(): number {
|
|
return inflightGets.size;
|
|
}
|
|
|
|
function isRequestOptions(value: unknown): value is RequestOptions {
|
|
return typeof value === "object" && value !== null && "signal" in value;
|
|
}
|
|
|
|
export const api = {
|
|
get: <T>(path: string, options?: RequestOptions) => coalescedGet<T>(path, options),
|
|
post: <T>(path: string, body: unknown, options?: RequestOptions) =>
|
|
request<T>(path, { method: "POST", body: JSON.stringify(body), signal: options?.signal }),
|
|
postForm: <T>(path: string, body: FormData, options?: RequestOptions) =>
|
|
request<T>(path, { method: "POST", body, signal: options?.signal }),
|
|
put: <T>(path: string, body: unknown, options?: RequestOptions) =>
|
|
request<T>(path, { method: "PUT", body: JSON.stringify(body), signal: options?.signal }),
|
|
patch: <T>(path: string, body: unknown, options?: RequestOptions) =>
|
|
request<T>(path, { method: "PATCH", body: JSON.stringify(body), signal: options?.signal }),
|
|
delete: <T>(path: string, bodyOrOptions?: unknown, options?: RequestOptions) => {
|
|
const requestOptions = isRequestOptions(bodyOrOptions) ? bodyOrOptions : options;
|
|
const body = bodyOrOptions === undefined || isRequestOptions(bodyOrOptions) ? undefined : JSON.stringify(bodyOrOptions);
|
|
return request<T>(path, { method: "DELETE", ...(body === undefined ? {} : { body }), signal: requestOptions?.signal });
|
|
},
|
|
deleteWithBody: <T>(path: string, body: unknown, options?: RequestOptions) =>
|
|
request<T>(path, { method: "DELETE", body: JSON.stringify(body), signal: options?.signal }),
|
|
};
|