Improve live agent feedback during sandboxed runs (#8915)

## 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>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-07-02 22:21:56 -07:00
1 parent bf982c8c83
commit c48feee190
36 files changed
+1742 -88

No files matched your search

@@ -316,6 +316,9 @@ describe("agent live run routes", () => {
...run,
currentStatusMessage: "Syncing workspace to sandbox",
currentStatusUpdatedAt: new Date("2026-04-10T09:30:05.000Z"),
currentToolName: "bash",
lastAssistantSnippet: "Inspecting files",
lastEventAt: new Date("2026-04-10T09:30:06.000Z"),
}));
const res = await requestApp(
@@ -331,6 +334,9 @@ describe("agent live run routes", () => {
expect(res.body).toMatchObject({
currentStatusMessage: "Syncing workspace to sandbox",
currentStatusUpdatedAt: "2026-04-10T09:30:05.000Z",
currentToolName: "bash",
lastAssistantSnippet: "Inspecting files",
lastEventAt: "2026-04-10T09:30:06.000Z",
});
});
@@ -148,6 +148,9 @@ describeEmbeddedPostgres("heartbeat runtime state deduplication", () => {
const status = await heartbeat.recordRuntimeProgress(run, {
phase: "config_sync",
message: "Syncing workspace to sandbox",
currentToolName: "bash",
lastAssistantSnippet: "Inspecting the repository",
lastEventAt: "2026-06-24T00:00:05.000Z",
}, issueId);
expect(status).toMatchObject({
@@ -157,6 +160,9 @@ describeEmbeddedPostgres("heartbeat runtime state deduplication", () => {
runId,
phase: "config_sync",
message: "Syncing workspace to sandbox",
currentToolName: "bash",
lastAssistantSnippet: "Inspecting the repository",
lastEventAt: new Date("2026-06-24T00:00:05.000Z"),
});
expect(heartbeat.decorateActiveRunStatus({
id: runId,
@@ -166,6 +172,9 @@ describeEmbeddedPostgres("heartbeat runtime state deduplication", () => {
status: "running",
})).toMatchObject({
currentStatusMessage: "Syncing workspace to sandbox",
currentToolName: "bash",
lastAssistantSnippet: "Inspecting the repository",
lastEventAt: new Date("2026-06-24T00:00:05.000Z"),
});
expect(liveEvents).toContainEqual(expect.objectContaining({
companyId,
@@ -176,6 +185,9 @@ describeEmbeddedPostgres("heartbeat runtime state deduplication", () => {
issueId,
phase: "config_sync",
message: "Syncing workspace to sandbox",
currentToolName: "bash",
lastAssistantSnippet: "Inspecting the repository",
lastEventAt: "2026-06-24T00:00:05.000Z",
}),
}));
@@ -75,6 +75,7 @@ const fakeSandboxEnvironmentConfigSchema = z.object({
.min(1, "Fake sandbox environments require an image.")
.default("ubuntu:24.04"),
reuseLease: z.boolean().optional().default(false),
streamRunLogs: z.boolean().optional(),
}).strict();
const pluginSandboxProviderKeySchema = z.string()
@@ -89,6 +90,7 @@ const pluginSandboxEnvironmentConfigSchema = z.object({
provider: pluginSandboxProviderKeySchema,
timeoutMs: z.coerce.number().int().min(1).max(86_400_000).optional(),
reuseLease: z.boolean().optional().default(false),
streamRunLogs: z.boolean().optional(),
}).catchall(z.unknown());
const pluginEnvironmentConfigSchema = z.object({
@@ -73,6 +73,10 @@ export async function resolveEnvironmentExecutionTarget(input: {
environmentId: input.environment.id ?? null,
leaseId: input.leaseId ?? null,
timeoutMs,
// Run-log streaming defaults ON for sandbox environments so agent CLI
// output reaches the UI mid-run; `streamRunLogs: false` is an explicit
// opt-out back to batch-at-end delivery.
streamRunLogs: parsed.config.streamRunLogs !== false,
runner: input.environmentRuntime && input.lease
? {
supportsSingleStreamStdinProgress: false,
@@ -6,6 +6,7 @@ import {
MAX_HEARTBEAT_RUN_RUNTIME_STATUS_MESSAGE_CHARS,
setHeartbeatRunRuntimeStatus,
sweepExpiredHeartbeatRunRuntimeStatuses,
touchHeartbeatRunRuntimeStatus,
} from "./heartbeat-run-runtime-status.js";
describe("heartbeat run runtime status store", () => {
@@ -22,11 +23,17 @@ describe("heartbeat run runtime status store", () => {
runId: "run-1",
phase: "config_sync",
message: `Syncing workspace with apiKey: "sk-test-secret" ${"x".repeat(300)}`,
currentToolName: `bash apiKey: "sk-tool-secret" ${"x".repeat(120)}`,
lastAssistantSnippet: `Reading apiKey: "sk-snippet-secret" ${"x".repeat(300)}`,
lastEventAt: new Date("2026-06-24T00:00:05.000Z"),
updatedAt,
});
expect(status?.message).toContain("***REDACTED***");
expect(status?.message.length).toBeLessThanOrEqual(MAX_HEARTBEAT_RUN_RUNTIME_STATUS_MESSAGE_CHARS);
expect(status?.currentToolName).toContain("***REDACTED***");
expect(status?.lastAssistantSnippet).toContain("***REDACTED***");
expect(status?.lastEventAt).toEqual(new Date("2026-06-24T00:00:05.000Z"));
expect(getHeartbeatRunRuntimeStatus("run-1", {
companyId: "company-1",
issueId: "issue-1",
@@ -38,6 +45,9 @@ describe("heartbeat run runtime status store", () => {
agentId: "agent-1",
runId: "run-1",
phase: "config_sync",
currentToolName: expect.stringContaining("***REDACTED***"),
lastAssistantSnippet: expect.stringContaining("***REDACTED***"),
lastEventAt: new Date("2026-06-24T00:00:05.000Z"),
});
expect(getHeartbeatRunRuntimeStatus("run-1", { companyId: "other-company" })).toBeNull();
expect(getHeartbeatRunRuntimeStatus("run-1", {
@@ -61,6 +71,101 @@ describe("heartbeat run runtime status store", () => {
expect(getHeartbeatRunRuntimeStatus("run-1")).toBeNull();
});
it("touch refreshes timestamps while preserving the existing status context", () => {
setHeartbeatRunRuntimeStatus({
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
runId: "run-1",
phase: "run_activity",
message: "Using Bash",
currentToolName: "Bash",
lastAssistantSnippet: "Running the tests",
updatedAt: new Date("2026-06-24T00:00:00.000Z"),
lastEventAt: new Date("2026-06-24T00:00:00.000Z"),
});
const touched = touchHeartbeatRunRuntimeStatus({
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
runId: "run-1",
at: new Date("2026-06-24T00:00:45.000Z"),
});
expect(touched).toMatchObject({
runId: "run-1",
phase: "run_activity",
message: "Using Bash",
currentToolName: "Bash",
lastAssistantSnippet: "Running the tests",
updatedAt: new Date("2026-06-24T00:00:45.000Z"),
lastEventAt: new Date("2026-06-24T00:00:45.000Z"),
});
expect(getHeartbeatRunRuntimeStatus("run-1", {
companyId: "company-1",
now: new Date("2026-06-24T00:02:00.000Z"),
})).toMatchObject({ message: "Using Bash" });
});
it("touch does not move timestamps backwards", () => {
setHeartbeatRunRuntimeStatus({
companyId: "company-1",
issueId: null,
agentId: "agent-1",
runId: "run-1",
phase: "run_activity",
message: "Using Bash",
updatedAt: new Date("2026-06-24T00:01:00.000Z"),
lastEventAt: new Date("2026-06-24T00:01:00.000Z"),
});
const touched = touchHeartbeatRunRuntimeStatus({
companyId: "company-1",
issueId: null,
agentId: "agent-1",
runId: "run-1",
at: new Date("2026-06-24T00:00:30.000Z"),
});
expect(touched).toMatchObject({
updatedAt: new Date("2026-06-24T00:01:00.000Z"),
lastEventAt: new Date("2026-06-24T00:01:00.000Z"),
});
});
it("touch creates a fallback run_activity status when none is live", () => {
const created = touchHeartbeatRunRuntimeStatus({
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
runId: "run-1",
at: new Date("2026-06-24T00:00:00.000Z"),
});
expect(created).toMatchObject({
runId: "run-1",
phase: "run_activity",
message: "Receiving agent output",
updatedAt: new Date("2026-06-24T00:00:00.000Z"),
lastEventAt: new Date("2026-06-24T00:00:00.000Z"),
});
// An expired entry is replaced with a fresh fallback rather than revived.
const expiredTouch = touchHeartbeatRunRuntimeStatus({
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
runId: "run-1",
at: new Date("2026-06-24T00:05:00.000Z"),
});
expect(expiredTouch).toMatchObject({
phase: "run_activity",
message: "Receiving agent output",
updatedAt: new Date("2026-06-24T00:05:00.000Z"),
});
});
it("sweeps expired statuses without touching fresh entries", () => {
setHeartbeatRunRuntimeStatus({
companyId: "company-1",
@@ -3,6 +3,8 @@ import { redactSensitiveText } from "../redaction.js";
export const HEARTBEAT_RUN_RUNTIME_STATUS_TTL_MS = 90_000;
export const MAX_HEARTBEAT_RUN_RUNTIME_STATUS_MESSAGE_CHARS = 180;
export const MAX_HEARTBEAT_RUN_RUNTIME_TOOL_NAME_CHARS = 80;
export const MAX_HEARTBEAT_RUN_RUNTIME_ASSISTANT_SNIPPET_CHARS = 220;
export interface HeartbeatRunRuntimeStatus {
companyId: string;
@@ -12,6 +14,9 @@ export interface HeartbeatRunRuntimeStatus {
phase: HeartbeatRunStatusPhase;
message: string;
updatedAt: Date;
currentToolName: string | null;
lastAssistantSnippet: string | null;
lastEventAt: Date | null;
}
const runtimeStatusesByRunId = new Map<string, HeartbeatRunRuntimeStatus>();
@@ -20,14 +25,27 @@ function cloneStatus(status: HeartbeatRunRuntimeStatus): HeartbeatRunRuntimeStat
return {
...status,
updatedAt: new Date(status.updatedAt),
lastEventAt: status.lastEventAt ? new Date(status.lastEventAt) : null,
};
}
export function sanitizeHeartbeatRunRuntimeStatusMessage(message: string): string {
const normalized = message.replace(/\s+/g, " ").trim();
function sanitizeRuntimeStatusText(value: string, maxChars: number): string {
const normalized = value.replace(/\s+/g, " ").trim();
const redacted = redactSensitiveText(normalized);
if (redacted.length <= MAX_HEARTBEAT_RUN_RUNTIME_STATUS_MESSAGE_CHARS) return redacted;
return `${redacted.slice(0, MAX_HEARTBEAT_RUN_RUNTIME_STATUS_MESSAGE_CHARS - 3)}...`;
if (redacted.length <= maxChars) return redacted;
return `${redacted.slice(0, maxChars - 3)}...`;
}
export function sanitizeHeartbeatRunRuntimeStatusMessage(message: string): string {
return sanitizeRuntimeStatusText(message, MAX_HEARTBEAT_RUN_RUNTIME_STATUS_MESSAGE_CHARS);
}
export function sanitizeHeartbeatRunRuntimeToolName(toolName: string): string {
return sanitizeRuntimeStatusText(toolName, MAX_HEARTBEAT_RUN_RUNTIME_TOOL_NAME_CHARS);
}
export function sanitizeHeartbeatRunRuntimeAssistantSnippet(snippet: string): string {
return sanitizeRuntimeStatusText(snippet, MAX_HEARTBEAT_RUN_RUNTIME_ASSISTANT_SNIPPET_CHARS);
}
function isExpired(status: HeartbeatRunRuntimeStatus, now: Date, ttlMs: number) {
@@ -35,9 +53,15 @@ function isExpired(status: HeartbeatRunRuntimeStatus, now: Date, ttlMs: number)
}
export function setHeartbeatRunRuntimeStatus(
input: Omit<HeartbeatRunRuntimeStatus, "message" | "updatedAt"> & {
input: Omit<
HeartbeatRunRuntimeStatus,
"message" | "updatedAt" | "currentToolName" | "lastAssistantSnippet" | "lastEventAt"
> & {
message: string;
updatedAt?: Date;
currentToolName?: string | null;
lastAssistantSnippet?: string | null;
lastEventAt?: Date | null;
},
): HeartbeatRunRuntimeStatus | null {
const message = sanitizeHeartbeatRunRuntimeStatusMessage(input.message);
@@ -54,11 +78,62 @@ export function setHeartbeatRunRuntimeStatus(
phase: input.phase,
message,
updatedAt: input.updatedAt ? new Date(input.updatedAt) : new Date(),
currentToolName: input.currentToolName
? sanitizeHeartbeatRunRuntimeToolName(input.currentToolName)
: null,
lastAssistantSnippet: input.lastAssistantSnippet
? sanitizeHeartbeatRunRuntimeAssistantSnippet(input.lastAssistantSnippet)
: null,
lastEventAt: input.lastEventAt ? new Date(input.lastEventAt) : null,
};
runtimeStatusesByRunId.set(status.runId, status);
return cloneStatus(status);
}
/**
* Refresh the activity timestamps of an existing runtime status without
* discarding its message/tool context, so streamed run-log output keeps the
* "Working... / X ago" line fresh between structured events. When no live
* status exists (first output, or the previous one expired past the TTL), a
* fallback `run_activity` status is created instead.
*/
export function touchHeartbeatRunRuntimeStatus(input: {
companyId: string;
issueId: string | null;
agentId: string;
runId: string;
at?: Date;
fallbackPhase?: HeartbeatRunStatusPhase;
fallbackMessage?: string;
}): HeartbeatRunRuntimeStatus | null {
const at = input.at ?? new Date();
const existing = runtimeStatusesByRunId.get(input.runId);
if (
existing &&
!isExpired(existing, at, HEARTBEAT_RUN_RUNTIME_STATUS_TTL_MS) &&
existing.companyId === input.companyId &&
existing.agentId === input.agentId
) {
if (at.getTime() > existing.updatedAt.getTime()) {
existing.updatedAt = new Date(at);
}
if (!existing.lastEventAt || at.getTime() > existing.lastEventAt.getTime()) {
existing.lastEventAt = new Date(at);
}
return cloneStatus(existing);
}
return setHeartbeatRunRuntimeStatus({
companyId: input.companyId,
issueId: input.issueId,
agentId: input.agentId,
runId: input.runId,
phase: input.fallbackPhase ?? "run_activity",
message: input.fallbackMessage ?? "Receiving agent output",
updatedAt: at,
lastEventAt: at,
});
}
export function getHeartbeatRunRuntimeStatus(
runId: string,
expected?: {
+199 -12
View File
@@ -204,8 +204,11 @@ import { isUnsafeSessionWorkspaceCwd } from "./session-workspace-cwd.js";
import {
clearHeartbeatRunRuntimeStatus,
getHeartbeatRunRuntimeStatus,
MAX_HEARTBEAT_RUN_RUNTIME_ASSISTANT_SNIPPET_CHARS,
MAX_HEARTBEAT_RUN_RUNTIME_TOOL_NAME_CHARS,
setHeartbeatRunRuntimeStatus,
sweepExpiredHeartbeatRunRuntimeStatuses,
touchHeartbeatRunRuntimeStatus,
} from "./heartbeat-run-runtime-status.js";
import {
assertLowTrustRuntimeServicesAllowed,
@@ -266,6 +269,7 @@ export {
ACTIVE_RUN_OUTPUT_SUSPICION_THRESHOLD_MS,
} from "./recovery/service.js";
export const ACTIVE_RUN_OUTPUT_PROGRESS_FLUSH_INTERVAL_MS = 60 * 1000;
export const ACTIVE_RUN_LOG_RUNTIME_STATUS_REFRESH_INTERVAL_MS = 5 * 1000;
export const BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS = [
2 * 60 * 1000,
10 * 60 * 1000,
@@ -3985,6 +3989,9 @@ function decorateHeartbeatRunRuntimeStatus<T extends HeartbeatRunRuntimeStatusRu
): T & {
currentStatusMessage: string | null;
currentStatusUpdatedAt: Date | null;
currentToolName: string | null;
lastAssistantSnippet: string | null;
lastEventAt: Date | null;
} {
if (isHeartbeatRunTerminalStatus(run.status)) {
clearHeartbeatRunRuntimeStatus(run.id);
@@ -4007,9 +4014,41 @@ function decorateHeartbeatRunRuntimeStatus<T extends HeartbeatRunRuntimeStatusRu
...run,
currentStatusMessage: currentStatus?.message ?? null,
currentStatusUpdatedAt: currentStatus?.updatedAt ?? null,
currentToolName: currentStatus?.currentToolName ?? null,
lastAssistantSnippet: currentStatus?.lastAssistantSnippet ?? null,
lastEventAt: currentStatus?.lastEventAt ?? null,
};
}
function publishHeartbeatRunRuntimeProgress(status: {
companyId: string;
runId: string;
agentId: string;
issueId: string | null;
phase: HeartbeatRunStatusPhase;
message: string;
updatedAt: Date;
currentToolName?: string | null;
lastAssistantSnippet?: string | null;
lastEventAt?: Date | null;
}) {
publishLiveEvent({
companyId: status.companyId,
type: "heartbeat.run.progress",
payload: {
runId: status.runId,
agentId: status.agentId,
issueId: status.issueId,
phase: status.phase,
message: status.message,
currentToolName: status.currentToolName ?? null,
lastAssistantSnippet: status.lastAssistantSnippet ?? null,
lastEventAt: (status.lastEventAt ?? status.updatedAt).toISOString(),
updatedAt: status.updatedAt.toISOString(),
},
});
}
function recordHeartbeatRunRuntimeProgress(
run: Pick<typeof heartbeatRuns.$inferSelect, "id" | "companyId" | "agentId" | "status" | "contextSnapshot">,
update: RuntimeStatusUpdate,
@@ -4023,24 +4062,121 @@ function recordHeartbeatRunRuntimeProgress(
runId: run.id,
phase: update.phase as HeartbeatRunStatusPhase,
message: update.message,
currentToolName: readNonEmptyString(update.currentToolName) ?? null,
lastAssistantSnippet: readNonEmptyString(update.lastAssistantSnippet) ?? null,
lastEventAt: update.lastEventAt ? new Date(update.lastEventAt) : new Date(),
});
if (!status) return null;
publishLiveEvent({
companyId: status.companyId,
type: "heartbeat.run.progress",
payload: {
runId: status.runId,
agentId: status.agentId,
issueId: status.issueId,
phase: status.phase,
message: status.message,
updatedAt: status.updatedAt.toISOString(),
},
});
publishHeartbeatRunRuntimeProgress(status);
return status;
}
function sanitizeLiveRunProgressText(value: string, maxChars: number): string | null {
const normalized = value.replace(/\s+/g, " ").trim();
if (!normalized) return null;
const redacted = redactSensitiveText(normalized);
if (redacted.length <= maxChars) return redacted;
return `${redacted.slice(0, maxChars - 3)}...`;
}
function readLiveRunProgressString(value: unknown, maxChars: number): string | null {
return typeof value === "string" ? sanitizeLiveRunProgressText(value, maxChars) : null;
}
function readFirstLiveRunProgressString(maxChars: number, values: unknown[]): string | null {
for (const value of values) {
const text = readLiveRunProgressString(value, maxChars);
if (text) return text;
}
return null;
}
function readLiveRunToolName(payload: Record<string, unknown> | null, eventType: string): string | null {
const toolCall = parseObject(payload?.tool_call) ?? parseObject(payload?.toolCall);
const message = parseObject(payload?.message);
const direct = readFirstLiveRunProgressString(MAX_HEARTBEAT_RUN_RUNTIME_TOOL_NAME_CHARS, [
payload?.toolName,
payload?.tool_name,
payload?.tool,
payload?.name,
payload?.title,
toolCall?.name,
toolCall?.toolName,
message?.name,
message?.toolName,
]);
if (direct) return direct;
const normalizedEventType = eventType.toLowerCase();
if (!normalizedEventType.includes("tool")) return null;
return readLiveRunProgressString(eventType.replace(/[._-]+/g, " "), MAX_HEARTBEAT_RUN_RUNTIME_TOOL_NAME_CHARS);
}
function readLiveRunAssistantSnippet(
payload: Record<string, unknown> | null,
eventType: string,
message: string | null,
): string | null {
const normalizedEventType = eventType.toLowerCase();
const messagePayload = parseObject(payload?.message);
const direct = readFirstLiveRunProgressString(MAX_HEARTBEAT_RUN_RUNTIME_ASSISTANT_SNIPPET_CHARS, [
payload?.text,
payload?.delta,
payload?.text_delta,
payload?.content,
payload?.summary,
messagePayload?.text,
messagePayload?.content,
]);
if (direct) return direct;
if (
normalizedEventType.includes("assistant") ||
normalizedEventType.includes("text_delta") ||
normalizedEventType.includes("message.delta") ||
normalizedEventType.includes("message_delta")
) {
return message ? sanitizeLiveRunProgressText(message, MAX_HEARTBEAT_RUN_RUNTIME_ASSISTANT_SNIPPET_CHARS) : null;
}
return null;
}
function buildRunEventRuntimeProgress(input: {
eventType: string;
message: string | null;
payload: Record<string, unknown> | null;
at: Date;
}) {
const normalizedEventType = input.eventType.toLowerCase();
if (normalizedEventType === "lifecycle" || normalizedEventType === "adapter.invoke") {
return null;
}
const currentToolName = readLiveRunToolName(input.payload, input.eventType);
const lastAssistantSnippet = readLiveRunAssistantSnippet(input.payload, input.eventType, input.message);
const fallbackMessage =
readLiveRunProgressString(input.message, MAX_HEARTBEAT_RUN_RUNTIME_ASSISTANT_SNIPPET_CHARS) ??
sanitizeLiveRunProgressText(
input.eventType.replace(/[._-]+/g, " "),
MAX_HEARTBEAT_RUN_RUNTIME_ASSISTANT_SNIPPET_CHARS,
);
const message =
currentToolName
? `Using ${currentToolName}`
: lastAssistantSnippet ?? fallbackMessage;
if (!message) return null;
return {
phase: "run_activity" as const,
message,
currentToolName,
lastAssistantSnippet,
lastEventAt: input.at,
};
}
export function buildPaperclipTaskMarkdown(input: {
issue: {
id: string;
@@ -6552,6 +6688,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
payload?: Record<string, unknown>;
},
) {
const eventAt = new Date();
const currentUserRedactionOptions = await getCurrentUserRedactionOptions();
const sanitizedMessage = event.message
? redactCurrentUserText(event.message, currentUserRedactionOptions)
@@ -6563,6 +6700,13 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
const sanitizedPayload = secretSanitizedPayload
? redactCurrentUserValue(secretSanitizedPayload, currentUserRedactionOptions)
: secretSanitizedPayload;
const issueId = readRuntimeStatusIssueIdCandidate(run) ?? null;
const progress = buildRunEventRuntimeProgress({
eventType: event.eventType,
message: sanitizedMessage ?? null,
payload: sanitizedPayload ?? null,
at: eventAt,
});
await db.insert(heartbeatRunEvents).values({
companyId: run.companyId,
@@ -6583,15 +6727,34 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
payload: {
runId: run.id,
agentId: run.agentId,
issueId,
seq,
eventType: event.eventType,
stream: event.stream ?? null,
level: event.level ?? null,
color: event.color ?? null,
message: sanitizedMessage ?? null,
currentToolName: progress?.currentToolName ?? null,
lastAssistantSnippet: progress?.lastAssistantSnippet ?? null,
lastEventAt: (progress?.lastEventAt ?? eventAt).toISOString(),
payload: sanitizedPayload ?? null,
},
});
if (progress && isHeartbeatRunRuntimeStatusActive(run.status)) {
const status = setHeartbeatRunRuntimeStatus({
companyId: run.companyId,
issueId,
agentId: run.agentId,
runId: run.id,
phase: progress.phase,
message: progress.message,
updatedAt: eventAt,
currentToolName: progress.currentToolName,
lastAssistantSnippet: progress.lastAssistantSnippet,
lastEventAt: progress.lastEventAt,
});
if (status) publishHeartbeatRunRuntimeProgress(status);
}
}
async function nextRunEventSeq(runId: string) {
@@ -10489,6 +10652,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
let stderrExcerpt = "";
let outputSeq = Number(run.lastOutputSeq ?? 0);
let lastOutputFlushAt: Date | null = run.lastOutputAt ?? null;
let lastLogRuntimeStatusTouchMs = 0;
const outputProgressState: {
pending: {
at: Date;
@@ -10629,6 +10793,28 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
};
await flushOutputProgress();
// Streamed CLI output is real run activity: keep the in-memory
// runtime status ("Working... / X ago") fresh between structured
// events so sandbox runs with mid-run log streaming never show a
// minutes-stale timestamp. Throttled to avoid churning the live
// event stream on every 250ms tail chunk.
const logActivityAt = new Date(ts);
if (
isHeartbeatRunRuntimeStatusActive(run.status) &&
logActivityAt.getTime() - lastLogRuntimeStatusTouchMs >=
ACTIVE_RUN_LOG_RUNTIME_STATUS_REFRESH_INTERVAL_MS
) {
lastLogRuntimeStatusTouchMs = logActivityAt.getTime();
const touchedStatus = touchHeartbeatRunRuntimeStatus({
companyId: run.companyId,
issueId,
agentId: run.agentId,
runId: run.id,
at: logActivityAt,
});
if (touchedStatus) publishHeartbeatRunRuntimeProgress(touchedStatus);
}
const payloadChunk =
sanitizedChunk.length > MAX_LIVE_LOG_CHUNK_BYTES
? sanitizedChunk.slice(sanitizedChunk.length - MAX_LIVE_LOG_CHUNK_BYTES)
@@ -10640,6 +10826,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
payload: {
runId: run.id,
agentId: run.agentId,
issueId,
ts,
stream,
chunk: payloadChunk,