mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-27 19:35:13 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A core part of that experience is watching active agent runs without dropping into raw logs first > - Local and sandbox-backed adapters already record useful run output, progress, and tool activity > - But active issue threads could sit visually stale while the agent was syncing workspaces, tailing sandbox output, or emitting incremental tool-call updates > - Operators need timely, human-readable progress while preserving the raw transcript underneath > - This pull request streams sandbox run-log progress into runtime status, keeps visible issue threads refreshed, and folds repeated ACPX tool updates into stable transcript cards > - The benefit is that long-running agent work becomes easier to supervise without changing the task/comment control-plane model ## Linked Issues or Issue Description No public GitHub issue exists for this exact change. Problem/motivation: - During long-running sandboxed agent work, the issue UI can appear idle even though the agent is actively syncing, running tools, or producing incremental output. - Operators need realtime feedback at the issue-thread layer, not only after opening raw logs or waiting for the final heartbeat result. - Related public context: #1808 previously added live-run status dots to Projects; #4362 touches heartbeat wakeup behavior but is not a duplicate of this runtime/UI feedback change. ## What Changed - Added sandbox run-log streaming support and defaulted sandbox-capable local adapters into the richer live-feedback path. - Surfaced environment/sandbox sync progress through heartbeat runtime status with bounded, redacted snippets. - Added live issue-thread cache patching so visible active runs update as progress events arrive. - Folded repeated ACPX `tool_call` updates into one transcript card instead of stacking duplicate cards. - Updated adapter docs and added focused regression coverage for sandbox log streaming, runtime status, ACPX parsing, live updates, transcript rendering, and issue chat messages. ## Verification - `pnpm install --frozen-lockfile` - `pnpm exec vitest run ui/src/context/LiveUpdatesProvider.test.ts` - `pnpm exec vitest run server/src/services/heartbeat-run-runtime-status.test.ts server/src/__tests__/heartbeat-runtime-state.test.ts ui/src/context/LiveUpdatesProvider.test.ts` - `pnpm exec vitest run packages/adapter-utils/src/execution-target-sandbox.test.ts packages/adapter-utils/src/sandbox-managed-runtime.test.ts server/src/services/heartbeat-run-runtime-status.test.ts server/src/__tests__/agent-live-run-routes.test.ts server/src/__tests__/heartbeat-runtime-state.test.ts packages/adapters/acpx-local/src/ui/parse-stdout.test.ts ui/src/context/LiveUpdatesProvider.test.ts ui/src/components/transcript/RunTranscriptView.test.tsx ui/src/lib/issue-chat-messages.test.ts ui/src/components/IssueChatThread.test.tsx` - GitHub PR workflow on head `8397953e7b41ccd42e5d9457ee7e4dfb996e4ec5`: `verify`, build, typecheck/release-registry, e2e, general shards, serialized server shards, and canary dry run passed. - Greptile Review on head `8397953e7b41ccd42e5d9457ee7e4dfb996e4ec5`: Confidence Score 5/5, no unresolved review threads. ## Risks - Live issue-thread cache patching could miss an edge case for a route shape not covered by tests. - Surfacing active-run snippets needs continued care around redaction; this PR keeps snippets bounded and adds redaction-focused coverage. - More frequent active-run UI refreshes could expose performance issues on very large issue threads, though updates are scoped to visible run/query caches. ## Model Used OpenAI GPT-5 via Codex, operating as a tool-enabled coding agent with shell, git, and repository-editing capabilities. Context window size is not exposed in this runtime. ## 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>
279 lines
10 KiB
TypeScript
279 lines
10 KiB
TypeScript
import path from "node:path";
|
|
import { StringDecoder } from "node:string_decoder";
|
|
import type { CommandManagedRuntimeRunner } from "./command-managed-runtime.js";
|
|
import { preferredShellForSandbox, shellCommandArgs } from "./sandbox-shell.js";
|
|
import { shellQuote } from "./ssh.js";
|
|
|
|
// Sandbox providers execute commands through batch RPCs, so agent CLI output
|
|
// normally only reaches the host when the process exits. This module streams
|
|
// that output during the run instead: `wrapCommand` tees the CLI's
|
|
// stdout/stderr into log files under the bridge runtime directory inside the
|
|
// sandbox, and a host-side poll loop tails those files (byte offsets +
|
|
// base64 transport, mirroring the callback-bridge queue client) and emits
|
|
// incremental `onLog` chunks through the existing run-log pipeline.
|
|
|
|
const SANDBOX_EXEC_CHANNEL_ENV = "PAPERCLIP_SANDBOX_EXEC_CHANNEL";
|
|
const SANDBOX_EXEC_CHANNEL_BRIDGE = "bridge";
|
|
|
|
const DEFAULT_TAIL_POLL_INTERVAL_MS = 250;
|
|
const DEFAULT_TAIL_MAX_CHUNK_BYTES = 64 * 1024;
|
|
const DEFAULT_TAIL_TICK_TIMEOUT_MS = 15_000;
|
|
const DEFAULT_TAIL_MAX_CONSECUTIVE_FAILURES = 3;
|
|
|
|
const TAIL_MARKER_STDOUT = "__PAPERCLIP_RUN_LOG_STDOUT__";
|
|
const TAIL_MARKER_STDERR = "__PAPERCLIP_RUN_LOG_STDERR__";
|
|
const TAIL_MARKER_END = "__PAPERCLIP_RUN_LOG_END__";
|
|
|
|
export type SandboxRunLogSink = (stream: "stdout" | "stderr", chunk: string) => Promise<void>;
|
|
|
|
export interface SandboxRunLogTailHandle {
|
|
/**
|
|
* Wrap the agent CLI invocation in a shell script that tees stdout/stderr
|
|
* into tailable log files while preserving the original streams (the
|
|
* provider result must keep the full stdout for adapter parsing) and the
|
|
* original exit code.
|
|
*/
|
|
wrapCommand(command: string, args: string[]): { command: string; args: string[] };
|
|
/** Start the host-side poll loop that tails the log files via the runner. */
|
|
start(onLog: SandboxRunLogSink): void;
|
|
/**
|
|
* Stop the poll loop and emit any bytes of the final batched output that
|
|
* were not already streamed. Emitting the suffix past the streamed byte
|
|
* offset both dedupes the final batch and guarantees full coverage when
|
|
* the tail loop degraded mid-run.
|
|
*/
|
|
finish(finalBatch: { stdout: string; stderr: string }): Promise<void>;
|
|
/** Stop the poll loop without emitting anything further (error path). */
|
|
abort(): Promise<void>;
|
|
}
|
|
|
|
export interface SandboxRunLogTailFactory {
|
|
create(): SandboxRunLogTailHandle;
|
|
}
|
|
|
|
export interface SandboxRunLogTailFactoryOptions {
|
|
runner: CommandManagedRuntimeRunner;
|
|
remoteCwd: string;
|
|
/** Remote directory the log files live in (bridge queue `logs/` dir). */
|
|
logsDir: string;
|
|
shellCommand?: "bash" | "sh" | null;
|
|
pollIntervalMs?: number | null;
|
|
maxChunkBytesPerTick?: number | null;
|
|
tickTimeoutMs?: number | null;
|
|
maxConsecutiveFailures?: number | null;
|
|
}
|
|
|
|
function normalizePositiveInt(value: number | null | undefined, fallback: number): number {
|
|
return typeof value === "number" && Number.isFinite(value) && value > 0
|
|
? Math.trunc(value)
|
|
: fallback;
|
|
}
|
|
|
|
interface TailStreamState {
|
|
stream: "stdout" | "stderr";
|
|
logFile: string;
|
|
offset: number;
|
|
decoder: StringDecoder;
|
|
}
|
|
|
|
function decodeBase64Section(lines: string[]): Buffer {
|
|
const joined = lines.join("").replace(/\s+/g, "");
|
|
if (joined.length === 0) return Buffer.alloc(0);
|
|
return Buffer.from(joined, "base64");
|
|
}
|
|
|
|
export function createSandboxRunLogTailFactory(
|
|
options: SandboxRunLogTailFactoryOptions,
|
|
): SandboxRunLogTailFactory {
|
|
const shellCommand = preferredShellForSandbox(options.shellCommand);
|
|
const pollIntervalMs = normalizePositiveInt(options.pollIntervalMs, DEFAULT_TAIL_POLL_INTERVAL_MS);
|
|
const maxChunkBytes = normalizePositiveInt(options.maxChunkBytesPerTick, DEFAULT_TAIL_MAX_CHUNK_BYTES);
|
|
const tickTimeoutMs = normalizePositiveInt(options.tickTimeoutMs, DEFAULT_TAIL_TICK_TIMEOUT_MS);
|
|
const maxConsecutiveFailures = normalizePositiveInt(
|
|
options.maxConsecutiveFailures,
|
|
DEFAULT_TAIL_MAX_CONSECUTIVE_FAILURES,
|
|
);
|
|
|
|
let sequence = 0;
|
|
|
|
function createHandle(): SandboxRunLogTailHandle {
|
|
sequence += 1;
|
|
const baseName = `run-${sequence}`;
|
|
const stdoutLog = path.posix.join(options.logsDir, `${baseName}-stdout.log`);
|
|
const stderrLog = path.posix.join(options.logsDir, `${baseName}-stderr.log`);
|
|
const statusFile = path.posix.join(options.logsDir, `${baseName}-status`);
|
|
|
|
const streams: [TailStreamState, TailStreamState] = [
|
|
{ stream: "stdout", logFile: stdoutLog, offset: 0, decoder: new StringDecoder("utf8") },
|
|
{ stream: "stderr", logFile: stderrLog, offset: 0, decoder: new StringDecoder("utf8") },
|
|
];
|
|
|
|
let sink: SandboxRunLogSink | null = null;
|
|
let stopped = false;
|
|
let degraded = false;
|
|
let loopPromise: Promise<void> | null = null;
|
|
let wakeSleep: (() => void) | null = null;
|
|
|
|
function sleep(ms: number): Promise<void> {
|
|
return new Promise((resolve) => {
|
|
const timer = setTimeout(() => {
|
|
wakeSleep = null;
|
|
resolve();
|
|
}, ms);
|
|
wakeSleep = () => {
|
|
clearTimeout(timer);
|
|
wakeSleep = null;
|
|
resolve();
|
|
};
|
|
});
|
|
}
|
|
|
|
function buildTickScript(): string {
|
|
const lines: string[] = [`printf '%s\\n' ${shellQuote(TAIL_MARKER_STDOUT)}`];
|
|
for (const state of streams) {
|
|
if (state.stream === "stderr") {
|
|
lines.push(`printf '%s\\n' ${shellQuote(TAIL_MARKER_STDERR)}`);
|
|
}
|
|
lines.push(
|
|
`if [ -f ${shellQuote(state.logFile)} ]; then tail -c +${state.offset + 1} ${shellQuote(state.logFile)} | head -c ${maxChunkBytes} | base64; fi`,
|
|
);
|
|
}
|
|
lines.push(`printf '%s\\n' ${shellQuote(TAIL_MARKER_END)}`);
|
|
return lines.join("\n");
|
|
}
|
|
|
|
function parseTickOutput(stdout: string): { stdout: Buffer; stderr: Buffer } | null {
|
|
const lines = stdout.split(/\r?\n/);
|
|
const stdoutIndex = lines.indexOf(TAIL_MARKER_STDOUT);
|
|
const stderrIndex = lines.indexOf(TAIL_MARKER_STDERR);
|
|
const endIndex = lines.indexOf(TAIL_MARKER_END);
|
|
if (stdoutIndex < 0 || stderrIndex < stdoutIndex || endIndex < stderrIndex) {
|
|
return null;
|
|
}
|
|
return {
|
|
stdout: decodeBase64Section(lines.slice(stdoutIndex + 1, stderrIndex)),
|
|
stderr: decodeBase64Section(lines.slice(stderrIndex + 1, endIndex)),
|
|
};
|
|
}
|
|
|
|
async function emitBytes(state: TailStreamState, bytes: Buffer): Promise<void> {
|
|
if (bytes.length === 0) return;
|
|
state.offset += bytes.length;
|
|
const text = state.decoder.write(bytes);
|
|
if (text.length > 0 && sink) {
|
|
await sink(state.stream, text);
|
|
}
|
|
}
|
|
|
|
async function tick(): Promise<void> {
|
|
const result = await options.runner.execute({
|
|
command: shellCommand,
|
|
args: shellCommandArgs(buildTickScript()),
|
|
cwd: options.remoteCwd,
|
|
env: { [SANDBOX_EXEC_CHANNEL_ENV]: SANDBOX_EXEC_CHANNEL_BRIDGE },
|
|
timeoutMs: tickTimeoutMs,
|
|
});
|
|
if (result.timedOut || (result.exitCode ?? 1) !== 0) {
|
|
throw new Error(
|
|
`Run log tail tick failed (exit ${result.exitCode ?? "null"}${result.timedOut ? ", timed out" : ""}).`,
|
|
);
|
|
}
|
|
const sections = parseTickOutput(result.stdout);
|
|
if (!sections) {
|
|
throw new Error("Run log tail tick returned unparseable output.");
|
|
}
|
|
await emitBytes(streams[0], sections.stdout);
|
|
await emitBytes(streams[1], sections.stderr);
|
|
}
|
|
|
|
async function loop(): Promise<void> {
|
|
let consecutiveFailures = 0;
|
|
while (!stopped) {
|
|
await sleep(pollIntervalMs);
|
|
if (stopped) break;
|
|
try {
|
|
await tick();
|
|
consecutiveFailures = 0;
|
|
} catch {
|
|
consecutiveFailures += 1;
|
|
if (consecutiveFailures >= maxConsecutiveFailures) {
|
|
degraded = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
async function stopLoop(): Promise<void> {
|
|
stopped = true;
|
|
wakeSleep?.();
|
|
if (loopPromise) {
|
|
await loopPromise.catch(() => undefined);
|
|
loopPromise = null;
|
|
}
|
|
}
|
|
|
|
return {
|
|
wrapCommand(command, args) {
|
|
const quotedInvocation = [command, ...args].map(shellQuote).join(" ");
|
|
// Tee stdout/stderr into tailable log files while keeping both
|
|
// streams flowing to the provider result. fd 3 carries the real
|
|
// stdout out of the inner group so stderr can ride the inner pipe
|
|
// into its own tee. The exit status survives the pipeline through
|
|
// the status file.
|
|
const script = [
|
|
`out_log=${shellQuote(stdoutLog)}`,
|
|
`err_log=${shellQuote(stderrLog)}`,
|
|
`status_file=${shellQuote(statusFile)}`,
|
|
`mkdir -p ${shellQuote(options.logsDir)}`,
|
|
`: > "$out_log"`,
|
|
`: > "$err_log"`,
|
|
`rm -f "$status_file"`,
|
|
`{`,
|
|
` { ${quotedInvocation} 3>&-; printf '%s' "$?" > "$status_file"; } 2>&1 1>&3 | tee -a "$err_log" >&2`,
|
|
`} 3>&1 | tee -a "$out_log"`,
|
|
`if [ -s "$status_file" ]; then exit "$(cat "$status_file")"; fi`,
|
|
`exit 1`,
|
|
].join("\n");
|
|
return { command: shellCommand, args: shellCommandArgs(script) };
|
|
},
|
|
start(onLog) {
|
|
if (loopPromise || stopped) return;
|
|
sink = onLog;
|
|
loopPromise = loop();
|
|
},
|
|
async finish(finalBatch) {
|
|
await stopLoop();
|
|
if (!sink) return;
|
|
for (const state of streams) {
|
|
const finalBytes = Buffer.from(
|
|
state.stream === "stdout" ? finalBatch.stdout : finalBatch.stderr,
|
|
"utf8",
|
|
);
|
|
if (finalBytes.length > state.offset) {
|
|
const text = state.decoder.write(finalBytes.subarray(state.offset));
|
|
if (text.length > 0) {
|
|
await sink(state.stream, text);
|
|
}
|
|
}
|
|
const rest = state.decoder.end();
|
|
if (rest.length > 0) {
|
|
await sink(state.stream, rest);
|
|
}
|
|
}
|
|
if (degraded) {
|
|
await sink(
|
|
"stderr",
|
|
"[paperclip] Run log streaming degraded during the run; remaining output was delivered at completion.\n",
|
|
);
|
|
}
|
|
},
|
|
async abort() {
|
|
await stopLoop();
|
|
},
|
|
};
|
|
}
|
|
|
|
return { create: createHandle };
|
|
}
|