mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The task view's runner turn shows a status header and a current-activity line while an agent works. > - From the claim until the agent's turn starts, that line says "Thinking", even while the run acquires its environment, restores its session or connects tools. > - The stacked pull request below this one makes the server publish each run's startup stage. > - This pull request shows "Getting ready" from message submission, then the server's stage after the claim, instead of "Thinking". It holds each shown stage briefly so fast steps do not flicker. > - The benefit is that a person can see why a turn has not started yet. ## Linked Issues or Issue Description No public issue exists. Stacked on #22953, which adds the server side. **Subsystem affected** Task chat runner turn (`ui/src/components/task-chat`), live run updates (`ui/src/context/LiveUpdatesProvider.tsx`) and `DESIGN.md`. **Problem or motivation** A cold start can spend many seconds on setup before the agent's first event. The activity line says "Thinking" for all of it, so a slow start looks like a slow model. **Proposed solution** Start a queued turn on "Getting ready", which is also the server's first stage after the claim, so the line does not change at the claim. Then name the server's startup stage until the agent's turn starts. Keep the header and the 30-second "Waiting to start" rule as they are. **Alternatives considered** A trailing debounce (show a stage only after it lasts some time). It delays every stage by the same amount and still cannot tell whether a step will continue. This change shows each stage at once and only holds a shown stage for a minimum time. ## What Changed - `run-startup-stage.ts` (new): the stage labels (`Getting ready`, `Waking up`, `Preparing workspace`, `Restoring session`, `Connecting tools`, `Starting agent`, and `Resuming session` for a resumed provider session) and `useHeldLabel`. A changed label shows at once when the current one has been visible for 500 ms. Otherwise the latest label shows when the 500 ms end, and labels in between are skipped. - `TaskChatRunnerTurn`: the current-activity line of a queued turn shows "Getting ready" instead of "Thinking", from message submission. A running (claimed) run shows the held server stage. Stages shimmer like "Thinking". Named holds (for example waiting for a provider) still win, and a turn still queued after 30 seconds with no named hold still says "Waiting to start". The header keeps "Working". "Thinking" begins when the agent's turn starts. - `TaskChatThread`: passes the live run's `startupStage` and `startupSessionResumed` to the runner turn. - `LiveUpdatesProvider`: the `heartbeat.run.startup_stage` event patches cached runs. It drops unknown stages and does not refetch. - `DESIGN.md`: a queued turn's activity line is now "Getting ready" instead of "Thinking", and a new paragraph next to the queued-turn rule describes the stages. ## Verification - `npx vitest run src/components/task-chat/run-startup-stage.test.ts`: labels, immediate change after the hold, the hold and skip to the latest label, the return to the default, and an undone change. - `npx vitest run src/components/TaskChatThread.test.tsx`: a claimed run shows its stage and keeps the "Working" header, a resumed session shows "Resuming session", agent activity replaces the stage, and a queued run shows no server stage. The existing admission tests now expect "Getting ready" where they expected "Thinking", and the mounted-through-startup test checks that the line stays "Getting ready" across the claim. The two tests that check for no startup feedback also reject "Getting ready". - `npx vitest run src/context/LiveUpdatesProvider.test.ts`: the event becomes a cache patch and unknown stages are dropped. - `npx vitest run src/components/TaskChatThread.test.tsx src/components/IssueChatThread.test.tsx src/components/task-chat`: 932 tests pass. `pnpm --filter @paperclipai/ui typecheck` passes. - CI runs the full suite. ## Risks - Low risk. The change is presentation only. If the server sends no stage (an older server, or after a restart), the line shows "Thinking" as before. - Queued turns now say "Getting ready" instead of "Thinking" during admission. The 30 second grace, the "Waiting to start" rule and named holds are unchanged. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits). ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
282 lines
11 KiB
TypeScript
282 lines
11 KiB
TypeScript
import type { AgentAppearance, RunStartupStage } from "@paperclipai/shared";
|
|
import { HEARTBEAT_RUN_LIST_DEFAULT_LIMIT } from "@paperclipai/shared";
|
|
import type { IssueRecoveryAction } from "@paperclipai/shared";
|
|
import type {
|
|
HeartbeatRun,
|
|
HeartbeatRunEvent,
|
|
WorkspaceOperation,
|
|
ProviderTraceFrame,
|
|
ProviderTraceMetadata,
|
|
} from "@paperclipai/shared";
|
|
import { tenantSessionRecovery } from "@/lib/tenant-session-recovery";
|
|
import { api, type RequestOptions } from "./client";
|
|
|
|
export interface RunLivenessFields {
|
|
livenessState: HeartbeatRun["livenessState"];
|
|
livenessReason: string | null;
|
|
continuationAttempt: number;
|
|
lastUsefulActionAt: string | Date | null;
|
|
nextAction: string | null;
|
|
}
|
|
|
|
export interface ActiveRunForIssue {
|
|
execution?: HeartbeatRun["execution"];
|
|
id: string;
|
|
runtimeMode?: "legacy" | "native";
|
|
wakeupRequestId?: string | null;
|
|
queuedCommentSourceWakeIds?: string[] | null;
|
|
status: string;
|
|
invocationSource: string;
|
|
triggerDetail: string | null;
|
|
contextCommentId?: string | null;
|
|
contextWakeCommentId?: string | null;
|
|
startedAt: string | Date | null;
|
|
finishedAt: string | Date | null;
|
|
createdAt: string | Date;
|
|
agentId: string;
|
|
agentName: string;
|
|
agentAppearance?: AgentAppearance | null;
|
|
avatarUrl?: string;
|
|
adapterType: string;
|
|
logBytes?: number | null;
|
|
lastOutputBytes?: number | null;
|
|
issueId?: string | null;
|
|
livenessState?: RunLivenessFields["livenessState"];
|
|
livenessReason?: string | null;
|
|
continuationAttempt?: number;
|
|
lastUsefulActionAt?: string | Date | null;
|
|
nextAction?: string | null;
|
|
outputSilence?: HeartbeatRun["outputSilence"];
|
|
currentStatusMessage?: string | null;
|
|
currentStatusUpdatedAt?: string | Date | null;
|
|
currentToolName?: string | null;
|
|
lastAssistantSnippet?: string | null;
|
|
lastEventAt?: string | Date | null;
|
|
startupStage?: RunStartupStage | null;
|
|
startupSessionResumed?: boolean;
|
|
}
|
|
|
|
export interface LiveRunForIssue {
|
|
execution?: HeartbeatRun["execution"];
|
|
id: string;
|
|
runtimeMode?: "legacy" | "native";
|
|
wakeupRequestId?: string | null;
|
|
queuedCommentSourceWakeIds?: string[] | null;
|
|
status: string;
|
|
invocationSource: string;
|
|
triggerDetail: string | null;
|
|
contextCommentId?: string | null;
|
|
contextWakeCommentId?: string | null;
|
|
startedAt: string | null;
|
|
finishedAt: string | null;
|
|
createdAt: string;
|
|
agentId: string;
|
|
agentName: string;
|
|
agentAppearance?: AgentAppearance | null;
|
|
avatarUrl?: string;
|
|
adapterType: string;
|
|
logBytes?: number | null;
|
|
lastOutputBytes?: number | null;
|
|
issueId?: string | null;
|
|
livenessState?: RunLivenessFields["livenessState"];
|
|
livenessReason?: string | null;
|
|
continuationAttempt?: number;
|
|
lastUsefulActionAt?: string | null;
|
|
nextAction?: string | null;
|
|
outputSilence?: HeartbeatRun["outputSilence"];
|
|
currentStatusMessage?: string | null;
|
|
currentStatusUpdatedAt?: string | null;
|
|
currentToolName?: string | null;
|
|
lastAssistantSnippet?: string | null;
|
|
lastEventAt?: string | null;
|
|
startupStage?: RunStartupStage | null;
|
|
startupSessionResumed?: boolean;
|
|
}
|
|
|
|
export interface WatchdogDecisionInput {
|
|
runId: string;
|
|
decision: "snooze" | "continue" | "dismissed_false_positive";
|
|
evaluationIssueId?: string | null;
|
|
reason?: string | null;
|
|
snoozedUntil?: string | null;
|
|
}
|
|
|
|
export type RuntimeRequestKind =
|
|
| "runtime"
|
|
| "command_approval"
|
|
| "file_approval"
|
|
| "permission_approval"
|
|
| "user_input"
|
|
| "elicitation";
|
|
|
|
export type RuntimeRequestResolution =
|
|
| { action: "accept" | "accept_for_session" | "decline" | "cancel" }
|
|
| { action: "submit"; answers: Record<string, { answers: string[] }> }
|
|
| { action: "submit"; content: Record<string, unknown> }
|
|
| { action: "submit"; response: import("@paperclipai/adapter-utils").PaperclipQuestionResponse };
|
|
|
|
export interface HeartbeatRunListOptions {
|
|
latestFailuresOnly?: boolean;
|
|
summary?: boolean;
|
|
}
|
|
|
|
export interface ProviderTraceInspection {
|
|
trace: ProviderTraceMetadata | null;
|
|
entries: Array<Record<string, unknown>>;
|
|
}
|
|
|
|
export const heartbeatsApi = {
|
|
executionForIssue: (issueId: string) => api.get<{ runId: string; agentId: string; recoveryAction: IssueRecoveryAction | null; execution: HeartbeatRun["execution"] } | null>(`/issues/${issueId}/execution`),
|
|
list: (
|
|
companyId: string,
|
|
agentId?: string,
|
|
limit = HEARTBEAT_RUN_LIST_DEFAULT_LIMIT,
|
|
options: HeartbeatRunListOptions = {},
|
|
) => {
|
|
const searchParams = new URLSearchParams();
|
|
if (agentId) searchParams.set("agentId", agentId);
|
|
if (limit) searchParams.set("limit", String(limit));
|
|
if (options.summary) searchParams.set("summary", "true");
|
|
if (options.latestFailuresOnly) searchParams.set("latestFailuresOnly", "true");
|
|
const qs = searchParams.toString();
|
|
return api.get<HeartbeatRun[]>(
|
|
`/companies/${companyId}/heartbeat-runs${qs ? `?${qs}` : ""}`,
|
|
);
|
|
},
|
|
get: (runId: string) => api.get<HeartbeatRun>(`/heartbeat-runs/${runId}`),
|
|
conversationEvents: (runId: string, afterSeq = 0, limit = 200, options?: RequestOptions) =>
|
|
api.get<HeartbeatRunEvent[]>(
|
|
`/heartbeat-runs/${runId}/events?view=conversation&afterSeq=${encodeURIComponent(String(afterSeq))}&limit=${encodeURIComponent(String(limit))}`,
|
|
options,
|
|
),
|
|
taskPanelActivations: (runId: string, options?: RequestOptions) =>
|
|
api.get<Array<{ pluginKey: string; slotId: string }>>(`/heartbeat-runs/${encodeURIComponent(runId)}/events?view=plugin-panels`, options),
|
|
events: (runId: string, afterSeq = 0, limit = 200, options?: RequestOptions) =>
|
|
api.get<HeartbeatRunEvent[]>(
|
|
`/heartbeat-runs/${runId}/events?afterSeq=${encodeURIComponent(String(afterSeq))}&limit=${encodeURIComponent(String(limit))}`,
|
|
options,
|
|
),
|
|
log: (runId: string, offset = 0, limitBytes = 256000, options?: RequestOptions & { alignStartToRecord?: boolean }) =>
|
|
api.get<{
|
|
runId: string;
|
|
store: string;
|
|
logRef: string;
|
|
content: string;
|
|
nextOffset?: number;
|
|
}>(
|
|
`/heartbeat-runs/${runId}/log?offset=${encodeURIComponent(String(offset))}&limitBytes=${encodeURIComponent(String(limitBytes))}${options?.alignStartToRecord ? "&alignStartToRecord=true" : ""}`,
|
|
options,
|
|
),
|
|
workspaceOperations: (runId: string) =>
|
|
api.get<WorkspaceOperation[]>(
|
|
`/heartbeat-runs/${runId}/workspace-operations`,
|
|
),
|
|
providerTrace: (runId: string) =>
|
|
api.get<ProviderTraceInspection>(`/heartbeat-runs/${runId}/provider-trace`),
|
|
providerTraceMetadata: (companyId: string, runIds: string[]) => {
|
|
const params = new URLSearchParams({ runIds: runIds.slice(0, 100).join(",") });
|
|
return api.get<ProviderTraceMetadata[]>(
|
|
`/companies/${companyId}/provider-traces?${params.toString()}`,
|
|
);
|
|
},
|
|
revealProviderTraceFrame: (runId: string, frameId: number) =>
|
|
api.post<ProviderTraceFrame>(
|
|
`/heartbeat-runs/${runId}/provider-trace/frames/${frameId}/reveal`,
|
|
{},
|
|
),
|
|
deleteProviderTrace: (runId: string) =>
|
|
api.delete<{ ok: true }>(`/heartbeat-runs/${runId}/provider-trace`),
|
|
downloadProviderTrace: async (runId: string): Promise<Blob> => {
|
|
const response = await fetch(
|
|
`/api/heartbeat-runs/${runId}/provider-trace/download`,
|
|
{
|
|
credentials: "include",
|
|
headers: { Accept: "application/x-ndjson" },
|
|
},
|
|
);
|
|
if (!response.ok) {
|
|
const body = (await response.json().catch(() => null)) as {
|
|
error?: string;
|
|
} | null;
|
|
const recovery = tenantSessionRecovery.recoverIfNeeded(response.status, body);
|
|
if (recovery) return recovery;
|
|
throw new Error(
|
|
body?.error ?? `Trace download failed: ${response.status}`,
|
|
);
|
|
}
|
|
return response.blob();
|
|
},
|
|
workspaceOperationLog: (
|
|
operationId: string,
|
|
offset = 0,
|
|
limitBytes = 256000,
|
|
) =>
|
|
api.get<{
|
|
operationId: string;
|
|
store: string;
|
|
logRef: string;
|
|
content: string;
|
|
nextOffset?: number;
|
|
}>(
|
|
`/workspace-operations/${operationId}/log?offset=${encodeURIComponent(String(offset))}&limitBytes=${encodeURIComponent(String(limitBytes))}`,
|
|
),
|
|
cancel: async (runId: string, options?: { cancellationRequestId: string }) => {
|
|
const run = await api.post<HeartbeatRun | null>(`/heartbeat-runs/${runId}/cancel`, options ?? {});
|
|
if (options && run?.status !== "cancelled") {
|
|
const value = run?.resultJson?.nativeCancellation;
|
|
const intent = value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
|
const pending = run?.id === runId && intent?.schema === "paperclip.native-cancellation.v1"
|
|
&& intent.runId === runId && intent.companyId === run.companyId
|
|
&& intent.intentId === `native-cancellation:${options.cancellationRequestId}` && intent.scope === "run"
|
|
&& intent.dispatchState === "pending" && intent.dispatched === false
|
|
&& typeof intent.intentAuditId === "string" && intent.intentAuditId.length > 0;
|
|
if (!pending) throw new Error("Stop was not accepted because the run changed.");
|
|
}
|
|
return run;
|
|
},
|
|
resolveRuntimeRequest: (input: {
|
|
runId: string;
|
|
requestId: string;
|
|
turnId: string;
|
|
requestKind: RuntimeRequestKind;
|
|
resolution: RuntimeRequestResolution;
|
|
}) =>
|
|
api.post<{ accepted: true; commandId: string }>(
|
|
`/heartbeat-runs/${input.runId}/runtime-requests/${encodeURIComponent(input.requestId)}/resolve`,
|
|
{
|
|
turnId: input.turnId,
|
|
requestKind: input.requestKind,
|
|
resolution: input.resolution,
|
|
},
|
|
),
|
|
recordWatchdogDecision: (input: WatchdogDecisionInput) =>
|
|
api.post(`/heartbeat-runs/${input.runId}/watchdog-decisions`, {
|
|
decision: input.decision,
|
|
evaluationIssueId: input.evaluationIssueId ?? null,
|
|
reason: input.reason ?? null,
|
|
snoozedUntil: input.snoozedUntil ?? null,
|
|
}),
|
|
liveRunsForIssue: (issueId: string) =>
|
|
api.get<LiveRunForIssue[]>(`/issues/${issueId}/live-runs`),
|
|
activeRunForIssue: (issueId: string) =>
|
|
api.get<ActiveRunForIssue | null>(`/issues/${issueId}/active-run`),
|
|
liveRunsForCompany: (
|
|
companyId: string,
|
|
options?: number | { minCount?: number; limit?: number; distinctTasks?: boolean },
|
|
) => {
|
|
const searchParams = new URLSearchParams();
|
|
if (typeof options === "number") {
|
|
searchParams.set("minCount", String(options));
|
|
} else if (options) {
|
|
if (options.minCount)
|
|
searchParams.set("minCount", String(options.minCount));
|
|
if (options.limit) searchParams.set("limit", String(options.limit));
|
|
if (options.distinctTasks) searchParams.set("distinctTasks", "true");
|
|
}
|
|
const qs = searchParams.toString();
|
|
return api.get<LiveRunForIssue[]>(
|
|
`/companies/${companyId}/live-runs${qs ? `?${qs}` : ""}`,
|
|
);
|
|
},
|
|
};
|