mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-30 05:16:50 +01:00
## Thinking Path > - Paperclip should show live agent output without repeating presentation work for every view. > - Execution, acknowledgements and durable checkpoints must remain independent of browser interest. > - The server already owns authorization and redaction at delivery. > - A shared browser connection can declare which visible runs need full transcripts. > - Catch-up must handle subscription races, disconnects, terminal output and slow consumers. > - This PR delivers the backend and UI contract together without a database migration. ## Linked Issues or Issue Description **What existing behavior does this improve?** Visible transcript consumers receive recoverable output through one shared browser connection. **Current behavior** Independent views can create duplicate connections, presentation work and recurring history reads. A subscription race or filtered native history can lose the saved tail. **Proposed behavior** Negotiate run interests, subscribe before catch-up and retain independent canonical recovery cursors. Keep lightweight lifecycle and attention events available without full transcript delivery. PR 4 of #17097 → #17439 → #17455 → #17456. The runtime feature is independent of hot-upgrade recovery; the stack order is for review convenience. ## What Changed - Add additive WebSocket capability negotiation, replacement interests, revision acknowledgement and resynchronization notices. - Reference-count visible consumer interests on one company-scoped browser connection. Preserve older-client/server behavior. - Reuse canonical structural/current-user/registered-secret redaction for plugin run notifications through the same bounded delivery queue. Keep producer and uninterested streams free of recipient lookups. - Refresh application queries after the matching recovery acknowledgement, including one follow-up after an older in-flight read. Ordinary interest acknowledgements add no refresh. - Keep authorization and redaction at delivery. Browser interest cannot change harness execution, PRP ACKs, checkpoints, accounting or canonical logs. - Deduplicate by sequence and log identity. Catch up terminal output and saved tails without recurring reads during healthy negotiated streaming. - Bound delivery to 1,000 items and 1 MiB. Overflow requires resynchronization; persistent congestion closes the connection. - Preserve compact-history expansion from current master across paginated catch-up. Snapshot the original read window before React can defer its update. ## Verification On current source `f6710f0b3c`, Linux [job 122604880503](https://github.com/paperclipai/paperclip/actions/runs/40624101891/job/122604880503) executes all five run-read permission cases successfully (2.574 seconds), including grant and revocation on the same connection. Its shard passes all 2,430 cases. Current [server-shard job 122604880416](https://github.com/paperclipai/paperclip/actions/runs/40624101891/job/122604880416) has 1,513 passes, one failure and three skips: an unchanged nested-clone expiration/restore test exceeds its 15-second deadline. The preceding `5efc6c48bf` source has identical non-document bytes; [its corresponding job 122601359272](https://github.com/paperclipai/paperclip/actions/runs/40623017917/job/122601359272) passes all 21 nested-clone cases, including that case in 9.505 seconds. The exact timing cause is unproven. The single diagnostic [retry job 122609332597](https://github.com/paperclipai/paperclip/actions/runs/40624101891/job/122609332597) passes all 21 nested-clone cases (61.316 seconds), including the formerly timed-out case in 7.003 seconds, and all 1,514 shard cases (three skips). The failure remains recorded; no timeout or assertion was changed. After the server squash merge and qualification retarget, all 50 focused server cases and all 91 focused UI cases pass again, with both typechecks and token gates. Runner vendor preparation rebuilds current master inputs before those tests. This source needs fresh CI and reviews; prior CI and browser receipts do not qualify it by inference. Current candidate `f6710f0b3c` now targets master `6987c2f20b`, after merged #17097, #17439 and #17455. Its diff contains only transcript delivery and its documentation. It adds no database migration. Retargeting changes only the evidence document; all production and test code is byte-identical to `5efc6c48bf`. On the eighth integration, all 50 focused server delivery cases and all 91 focused UI cases pass, with both typechecks and token gates. The following 35-case receipt belongs to the earlier delivery correction. Four low-queue authorization/decoration stall variants and the late-rejection case fail before correction. They now verify the five-second read deadline, old and negotiated clients, revisions that cannot reset the deadline, unaffected sibling connections, rejected late results, and timer cleanup. The first combined toast run has four loopback EPERM failures and 31 passes; its permitted repeat passes all 35. Earlier 28-case evidence excluded the toast file. The permission correction requires the current HTTP company-scope transcript permission, plus task access, for both native events and legacy logs. Prior Linux source `49a8783e9b`, job 122549913643, executes all five run-read cases, including grant/revocation on the same connection, successfully. That source placed this file in server shard 11; later shard assignments can differ and must be checked against their actual inventories. The older `405bedd189` receipt retains a separate scheduled-retry teardown race and inherited fixture collision; neither is waived. The new head must pass again in Linux CI. The seven extracted stream-recovery tests preserve their assertions. All 39 related legacy/native cases, UI typecheck and token gates pass after restoring the initially missed fixture helper. Earlier full workspace build/typecheck and Chrome journeys at `445a76563c` cover two views, company switches, reconnect, terminal catch-up, reload and zero recurring healthy transcript reads. Those browser receipts are historical source evidence and do not qualify this new head by inference. The [qualification record](https://github.com/paperclipai/paperclip/blob/f6710f0b3c84c6fdb2021df67206261b446dfc97/doc/plans/2026-10-22-hot-upgrade-qualification.md) retains exact earlier UI/history, source-boundary and cleanup failures with their fixes and limits. The workload-cost test preserves bounds and authorization callback counts for zero interests, one viewer, multiple browsers and a slow viewer. Its socket congestion is simulated. It measures neither SQL nor network costs. Current permission checks and the final hosted active-agent/viewer matrix remain unmeasured; no production savings are claimed. Fresh exact-head CI, legacy status, completed Greptile 5/5, resolved feedback and ordinary merge eligibility remain required. The earlier recipient corrections pass all 47 registry/plugin/delivery/WebSocket/toast cases and all 174 UI provider/recovery/interest cases, both typechecks and token gates on source `b202e59a25`. A real bus/host-service test registers a synthetic run secret through the production registry and reproduces its raw notification before the fix; native/legacy/final notifications now redact it, disposal prevents late worker notification. A later P1 review reproduces lost final notifications on settings-read and secret-resolution failure. Both cases fail before correction. Any delivery failure or subscription timeout now sends one content-free stream error and removes the plugin subscription. It never changes the agent execution or run status. Later events start no new redaction reads. The final integrated six-file server lane passes all 50 cases, with server typecheck and token gates. Existing browser delivery behavior is unchanged. Storage and secret-provider seams are scripted. Two real React Query/provider regressions first miss a run during resync; both now refresh after the valid replacement ACK, including pending-read and stale-scope cases. The prerequisite qualification batch passes all 118 cases and E2E typecheck after master integration. Fresh CI, security scan and reviews remain pending on this head. The contribution-rule review correction removes 104 explanatory comments introduced by this slice and keeps the ordering, deadline and plugin-delivery explanations in the delivery document. Existing comments and functional test/lint directives remain. All edited source files have identical parsed non-comment tokens before and after the change. All 50 server delivery cases and all 91 cases in six affected UI suites pass, along with token gates. The new head requires fresh CI, security and review. ## Risks A slow or disconnected viewer must resynchronize from authorized canonical history. It may see a display gap until catch-up completes. Company changes and revoked access must remove delivery interests. This slice adds no database migration and cannot change execution or recovery authority. Full transcript delivery evaluates current company-scope permission per delivery. Active plugin recipients also perform canonical redaction reads; viewer-load database costs on this final source remain unmeasured. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository tools and code execution. The runtime does not expose a more specific model ID or context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [ ] 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>
189 lines
13 KiB
JavaScript
189 lines
13 KiB
JavaScript
#!/usr/bin/env node
|
|
// Deterministic provider only. The production Rust runner, tool authority, and
|
|
// authenticated MCP gateway still execute every tool and enforce access.
|
|
import { randomUUID } from 'node:crypto';
|
|
import { readFileSync } from 'node:fs';
|
|
import { join, resolve } from 'node:path';
|
|
import { createInterface } from 'node:readline';
|
|
if (process.argv.includes('--version')) { console.log('codex-cli 0.115.0 (in-feed fixture)'); process.exit(0); }
|
|
let threadId = `fixture-${randomUUID()}`;
|
|
let turnId, toolSequence = 0, declined = false;
|
|
let helloProbe = false;
|
|
const recoveryFixture = process.env.PAPERCLIP_RECOVERY_FIXTURE === "1";
|
|
let currentObjective = "";
|
|
let emitCeoLineage = false;
|
|
let completionContract = { revision: "1", criterionIds: ["objective"] };
|
|
const pending = new Map();
|
|
const send = (value) => process.stdout.write(`${JSON.stringify(value)}\n`);
|
|
const call = (tool, args) => new Promise((resolve, reject) => {
|
|
const id = `connection-tool-${++toolSequence}`;
|
|
pending.set(id, { resolve, reject });
|
|
send({ id, method: 'item/tool/call', params: { threadId, turnId, callId: id, tool, arguments: args } });
|
|
});
|
|
function unwrap(result) {
|
|
const texts = result?.contentItems ?? result?.content ?? [];
|
|
for (const item of texts) {
|
|
try { const parsed = JSON.parse(item.text); return parsed.value ?? parsed; } catch {}
|
|
}
|
|
return result;
|
|
}
|
|
async function mcp(method, params = {}) {
|
|
// Native execution creates a dedicated provider home and issues a short-lived
|
|
// gateway token for this fixture run. Never load the user's normal Codex home.
|
|
if (!process.env.CODEX_HOME || !process.env.HOME
|
|
|| resolve(process.env.CODEX_HOME) !== resolve(process.env.HOME)) {
|
|
throw new Error('The fixture requires an isolated native provider home');
|
|
}
|
|
const config = readFileSync(join(process.env.CODEX_HOME, 'config.toml'), 'utf8');
|
|
const url = JSON.parse(config.match(/^url = (.+)$/m)?.[1] ?? 'null');
|
|
const authorization = JSON.parse(config.match(/Authorization = (".*?")/m)?.[1] ?? 'null');
|
|
if (!url || !authorization) throw new Error('Native continuation did not install the MCP gateway');
|
|
const endpoint = new URL(url);
|
|
if (endpoint.protocol !== 'http:' || !['127.0.0.1', 'localhost', '[::1]'].includes(endpoint.hostname)
|
|
|| endpoint.username || endpoint.password || endpoint.hash) {
|
|
throw new Error('The fixture only accepts a local native gateway');
|
|
}
|
|
const response = await fetch(endpoint, { redirect: 'error', method: 'POST', headers: { Authorization: authorization, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: ++toolSequence, method, params }) });
|
|
if (!response.ok) throw new Error(`Gateway HTTP ${response.status}`);
|
|
const text = await response.text();
|
|
const envelope = JSON.parse(text.startsWith('event:') || text.startsWith('data:') ? text.split('\n').find((line) => line.startsWith('data:')).slice(5) : text);
|
|
if (envelope.error) throw new Error(envelope.error.message);
|
|
return envelope.result;
|
|
}
|
|
async function finish(text, evidenceRef) {
|
|
return call('paperclip_finish', { schema: 'paperclip.run_result.v1', reportedWorkDisposition: 'done', summary: text,
|
|
completionClaim: { contractRevision: completionContract.revision, objectiveSatisfied: true, criteria: completionContract.criterionIds.map((criterionId) => ({ criterionId, status: 'satisfied', evidenceRefs: [evidenceRef] })), remainingWork: [] },
|
|
evidence: [{ ref: evidenceRef }], verification: [{ commandOrCheck: 'Fixture outcome', status: 'passed' }], attentionRequests: [], artifacts: [] });
|
|
}
|
|
async function execute() {
|
|
if (helloProbe) {
|
|
send({ method: 'item/completed', params: { threadId, turnId, item: { id: `answer-${turnId}`, type: 'agentMessage', phase: 'final_answer', text: 'hello' } } });
|
|
send({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status: 'completed' } } });
|
|
return;
|
|
}
|
|
if (process.argv.includes('--task-retry-fixture')) {
|
|
const text = 'The saved result is confirmed. No external publication was repeated.';
|
|
await call('report_progress', { idempotencyKey: 'saved-result-confirmation', body: text });
|
|
await finish(text, 'fixture:preserved-result');
|
|
send({ method: 'item/completed', params: { threadId, turnId, item: { id: `answer-${turnId}`, type: 'agentMessage', phase: 'final_answer', text } } });
|
|
send({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status: 'completed' } } });
|
|
return;
|
|
}
|
|
if (process.argv.includes('--completion-stream-fixture')) {
|
|
// Report completion before a deliberately slow final answer. The real
|
|
// runner and control plane must keep listening after the tool succeeds.
|
|
await finish('The fixture work is complete.', 'fixture:STREAM-42');
|
|
send({ method: 'item/completed', params: { threadId, turnId,
|
|
item: { id: `waiting-${turnId}`, type: 'agentMessage', phase: 'commentary', text: 'STREAM-42: waiting for the final answer.' } } });
|
|
// Exceed both former completion deadlines: cold (5s) and reusable (30s).
|
|
await new Promise((resolve) => setTimeout(resolve, 31_000));
|
|
const itemId = `answer-${turnId}`;
|
|
const text = 'STREAM-42: The launch has two stages. Source: https://example.invalid/launch/STREAM-42';
|
|
send({ method: 'item/started', params: { threadId, turnId, item: { id: itemId, type: 'agentMessage', phase: 'final_answer', text: '' } } });
|
|
send({ method: 'item/agentMessage/delta', params: { threadId, turnId, itemId, delta: text.slice(0, 40) } });
|
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
send({ method: 'item/agentMessage/delta', params: { threadId, turnId, itemId, delta: text.slice(40) } });
|
|
send({ method: 'item/completed', params: { threadId, turnId, item: { id: itemId, type: 'agentMessage', phase: 'final_answer', text } } });
|
|
send({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status: 'completed' } } });
|
|
return;
|
|
}
|
|
|
|
if (recoveryFixture) {
|
|
send({ method: 'item/agentMessage/delta', params: { threadId, turnId, itemId: `progress-${turnId}`, delta: 'Checking the current request and available connections.' } });
|
|
}
|
|
if (emitCeoLineage) {
|
|
const child = `child-${turnId}`;
|
|
send({ method: 'thread/started', params: { thread: { id: child, source: { subAgent: { thread_spawn: { parent_thread_id: threadId, depth: 1 } } } } } });
|
|
send({ method: 'turn/started', params: { threadId: child, turn: { id: `child-turn-${turnId}`, status: 'inProgress' } } });
|
|
send({ method: 'turn/completed', params: { threadId: child, turn: { id: `child-turn-${turnId}`, status: 'completed' } } });
|
|
await call('report_progress', { idempotencyKey: `lineage-${turnId}`, body: 'Provider child finished; root execution continues.' });
|
|
}
|
|
if (declined) {
|
|
const text = 'Connection declined. I will use the information already in this task and pursue alternatives.';
|
|
await call('report_progress', { idempotencyKey: `declined-${turnId}`, body: text });
|
|
await finish(text, 'task:declined-alternative');
|
|
send({ method: 'item/completed', params: { threadId, turnId, item: { id: `answer-${turnId}`, type: 'agentMessage', text } } });
|
|
send({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status: 'completed' } } });
|
|
return;
|
|
}
|
|
const query = recoveryFixture && /gmail/i.test(currentObjective) ? 'gmail-fixture' : 'heliotrope';
|
|
const discovery = unwrap(await call('connections_search', { query }));
|
|
const service = discovery.results?.find((item) => item.source === 'configured');
|
|
if (!service) throw new Error('Authorized Research Archive fixture was not discoverable');
|
|
const request = unwrap(await call('connection_request', { service: service.service }));
|
|
const refreshingTools = request.state === 'ready' && request.instruction?.includes('fresh continuation with updated tools is queued');
|
|
let text;
|
|
if (request.state === 'needs_user_action') {
|
|
text = 'I need access to the research archive. I can organize the launch checklist while you connect it.';
|
|
} else if (refreshingTools) {
|
|
// Follow the authority's yield instruction when authorization arrives after
|
|
// this provider session pinned its tools. The next session must do the read.
|
|
text = 'Access is ready. I will continue the archive read with the updated tools.';
|
|
} else {
|
|
await mcp('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'in-feed-fixture', version: '1' } });
|
|
const list = await mcp('tools/list');
|
|
const tool = list.tools.find((item) => (query === 'gmail-fixture' ? /gmail-fixture/.test(item.description ?? '') : /heliotrope/.test(item.description ?? '')));
|
|
if (!tool) throw new Error('Updated native tool snapshot does not contain archive_read');
|
|
const result = await mcp('tools/call', { name: tool.name, arguments: {} });
|
|
if (result.isError) throw new Error(JSON.stringify(result));
|
|
text = result.content.filter((item) => item.type === 'text').map((item) => item.text).join('\n');
|
|
if (recoveryFixture && text.includes('RECOVERY-INJECT-')) {
|
|
// An unrelated informational event must not terminate the root. The next
|
|
// event deliberately supplies the terminal failure used by recovery tests.
|
|
send({ method: 'thread/status/changed', params: { threadId: 'unrelated-fixture-thread', status: { type: 'idle' } } });
|
|
if (text.includes('RECOVERY-INJECT-UNKNOWN-WRITE')) {
|
|
send({ method: 'item/started', params: { threadId, turnId, item: { id: 'uncertain-email-write', type: 'commandExecution', command: 'send_fixture_email', status: 'inProgress' } } });
|
|
}
|
|
send({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status: 'failed', error: { code: 'fixture_checkpoint_unusable', message: 'Deterministic failed provider session after Gmail access' } } } });
|
|
return;
|
|
}
|
|
if (!text.includes(query === 'gmail-fixture' ? 'GMAIL-73' : 'HELIOTROPE-42')) throw new Error('Provider fixture value missing');
|
|
}
|
|
await call('report_progress', { idempotencyKey: `fixture-answer-${turnId}`, body: text });
|
|
if (request.state === 'ready' && !refreshingTools) await finish(text, 'mcp:archive_read');
|
|
send({ method: 'item/completed', params: { threadId, turnId, item: { id: `answer-${turnId}`, type: 'agentMessage', text } } });
|
|
send({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status: 'completed' } } });
|
|
}
|
|
createInterface({ input: process.stdin }).on('line', (line) => {
|
|
const message = JSON.parse(line);
|
|
if (!message.method && pending.has(message.id)) {
|
|
const promise = pending.get(message.id); pending.delete(message.id);
|
|
message.error ? promise.reject(new Error(message.error.message)) : promise.resolve(message.result); return;
|
|
}
|
|
const { id, method } = message;
|
|
if (method === 'initialize') send({ id, result: { user: { sessionId: threadId } } });
|
|
else if (method === 'thread/start' || method === 'thread/resume') {
|
|
if (recoveryFixture) send({ method: 'configWarning', params: { message: 'Recovery fixture startup notice before the first turn' } });
|
|
if (method === 'thread/resume' && message.params?.threadId) threadId = message.params.threadId;
|
|
if (message.params?.completionContract) completionContract = message.params.completionContract;
|
|
const model = process.argv.includes('--completion-stream-fixture') ? message.params?.model ?? 'in-feed-fixture' : 'in-feed-fixture';
|
|
send({ id, result: { model, modelProvider: 'fixture', thread: { id: threadId, sessionId: threadId } } });
|
|
}
|
|
else if (method === 'thread/read') send({ id, result: { thread: { id: threadId, turns: [] } } });
|
|
else if (method === 'turn/start') {
|
|
helloProbe = process.argv.includes('--completion-stream-fixture')
|
|
&& JSON.stringify(message.params?.input).includes('Respond only with hello. Do not use tools or inspect files.');
|
|
emitCeoLineage = JSON.stringify(message.params).includes('CEO descendant fixture');
|
|
declined = /connection_intent/.test(JSON.stringify(message.params)) && /rejected/.test(JSON.stringify(message.params));
|
|
for (const part of message.params?.input ?? []) {
|
|
try {
|
|
const outer = JSON.parse(part.text);
|
|
const envelope = typeof outer.message === "string" ? JSON.parse(outer.message) : outer;
|
|
const contract = envelope.task?.completionContract ?? envelope.completionContract;
|
|
for (const line of (envelope.task?.task?.prompt ?? envelope.task?.prompt ?? '').split('\n')) {
|
|
try { const context = JSON.parse(line); if (context.version === 1 && Array.isArray(context.messages)) currentObjective = context.objective; } catch {}
|
|
}
|
|
if (contract?.revision && contract.criteria) completionContract = { revision: contract.revision, criterionIds: contract.criteria.map((criterion) => criterion.id) };
|
|
} catch { /* Non-envelope text is ordinary task context. */ }
|
|
}
|
|
turnId = randomUUID();
|
|
send({ id, result: { turn: { id: turnId, status: 'inProgress' } } });
|
|
send({ method: 'turn/started', params: { threadId, turn: { id: turnId, status: 'inProgress' } } });
|
|
// Deliver model output on a later tick, after the runner accepts turn/start.
|
|
setTimeout(() => void execute().catch((error) => {
|
|
process.stderr.write(`In-feed fixture: ${error.message}\n`);
|
|
send({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status: 'failed', error: { message: error.message } } } });
|
|
}), 50);
|
|
} else if (id != null) send({ id, result: {} });
|
|
});
|