mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 01:24:30 +01:00
feat(ui): name a run's startup stage instead of Thinking (#22956)
## 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>
This commit is contained in:
1 parent
76e3b7e172
commit
1a726eaccf
9 files changed
+274
-18
No files matched your search
@@ -147,14 +147,23 @@ recipient for a later draft must not change the response already starting.
|
||||
Runtime discovery must not replace the turn with a generic spinner or a
|
||||
"run started" receipt. Queued and running headers use the same spacing.
|
||||
|
||||
A queued turn shows the same `Working` header and shimmering `Thinking` activity
|
||||
as a running turn, starting at message submission. Keep specific server holds,
|
||||
such as `Waiting for maintenance`, agent setup, or another open task of the same
|
||||
routine, visible during admission. Admission normally starts a run within seconds,
|
||||
A queued turn shows the same `Working` header as a running turn, with a
|
||||
shimmering `Getting ready` activity line, starting at message submission. Keep
|
||||
specific server holds, such as `Waiting for maintenance`, agent setup, or another
|
||||
open task of the same routine, visible during admission. Admission normally starts a run within seconds,
|
||||
so this startup feedback lasts at most 30 seconds: a turn still queued after that
|
||||
with no named hold says `Waiting to start`, without spinner or shimmer.
|
||||
A queued turn's hold is named once, in the turn header; the turn body adds no
|
||||
second line for it.
|
||||
Once the run is claimed and until its agent's turn starts, the
|
||||
current-activity slot names the run's startup stage. The claim continues
|
||||
`Getting ready` without a change, then the stage moves on to `Waking up`,
|
||||
`Preparing workspace`, `Restoring session`, `Connecting tools` or
|
||||
`Starting agent` (`Resuming session` when the provider resumed a saved
|
||||
session). The header keeps `Working`. A stage shimmers like `Thinking`, because
|
||||
work is in progress. Show each stage at once, and keep a shown stage for at
|
||||
least 500 ms; a change during that time shows the latest stage when it ends.
|
||||
`Thinking` begins when the agent's turn starts, and agent activity replaces it.
|
||||
A run that waits for one of its agent's concurrency slots is a hold too: show
|
||||
`Waiting for <agent> · N slots max · P of Q in line · Configure` (the shared
|
||||
`AgentQueueWait` component) with no spinner or elapsed timer, link Configure to the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AgentAppearance } from "@paperclipai/shared";
|
||||
import type { AgentAppearance, RunStartupStage } from "@paperclipai/shared";
|
||||
import { HEARTBEAT_RUN_LIST_DEFAULT_LIMIT } from "@paperclipai/shared";
|
||||
import type { IssueRecoveryAction } from "@paperclipai/shared";
|
||||
import type {
|
||||
@@ -52,6 +52,8 @@ export interface ActiveRunForIssue {
|
||||
currentToolName?: string | null;
|
||||
lastAssistantSnippet?: string | null;
|
||||
lastEventAt?: string | Date | null;
|
||||
startupStage?: RunStartupStage | null;
|
||||
startupSessionResumed?: boolean;
|
||||
}
|
||||
|
||||
export interface LiveRunForIssue {
|
||||
@@ -87,6 +89,8 @@ export interface LiveRunForIssue {
|
||||
currentToolName?: string | null;
|
||||
lastAssistantSnippet?: string | null;
|
||||
lastEventAt?: string | null;
|
||||
startupStage?: RunStartupStage | null;
|
||||
startupSessionResumed?: boolean;
|
||||
}
|
||||
|
||||
export interface WatchdogDecisionInput {
|
||||
|
||||
@@ -14,6 +14,7 @@ import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { ConnectivityProvider, createConnectivityStore } from "@/lib/connectivity";
|
||||
import { INITIAL_TRANSCRIPT_REVEAL_BUDGET_MS, TaskChatThread } from "./TaskChatThread";
|
||||
import { STARTUP_LABEL_MIN_DISPLAY_MS } from "./task-chat/run-startup-stage";
|
||||
import { IssueChatThread } from "./IssueChatThread";
|
||||
import { TaskChatAgentIdentity, TaskTranscriptAgents } from "./task-chat/TaskChatBubble";
|
||||
import type {
|
||||
@@ -604,10 +605,11 @@ it("shows activity during admission and clears it when the saved follow-up enter
|
||||
show(false);
|
||||
expect(container.textContent).toContain("Confirm the existing result.");
|
||||
expect(container.textContent).toContain("Working");
|
||||
expect(container.textContent).toContain("Thinking");
|
||||
expect(container.textContent).toContain("Getting ready");
|
||||
expect(container.textContent).not.toContain("Queued");
|
||||
show(true);
|
||||
expect(container.textContent).not.toContain("Thinking");
|
||||
expect(container.textContent).not.toContain("Getting ready");
|
||||
expect(container.textContent).not.toContain("Working");
|
||||
});
|
||||
|
||||
@@ -636,7 +638,7 @@ it.each((["task", "legacy"] as const).flatMap(surface =>
|
||||
await act(async () => { send!.click(); });
|
||||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||||
expect(container.textContent).toContain("Working");
|
||||
expect(container.textContent).toContain("Thinking");
|
||||
expect(container.textContent).toContain("Getting ready");
|
||||
expect(container.textContent).not.toContain("Queued");
|
||||
const identity = container.querySelector('[data-testid="task-chat-agent-identity"]');
|
||||
render(<Component {...props} composerDisabledReason="Could not load task pause state." />);
|
||||
@@ -776,6 +778,7 @@ it.each((["task", "legacy"] as const).flatMap(surface => [
|
||||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||||
expect(container.querySelector('[data-testid="task-chat-agent-identity"]')).toBeNull();
|
||||
expect(container.textContent).not.toContain("Thinking");
|
||||
expect(container.textContent).not.toContain("Getting ready");
|
||||
expect(container.textContent).not.toContain("Taking longer than usual");
|
||||
});
|
||||
|
||||
@@ -808,7 +811,7 @@ it.each([null, "previous-agent"].flatMap(previousAgentId => ["paperclip_runner",
|
||||
await act(async () => acknowledge());
|
||||
expect(container.querySelector('[data-testid="task-chat-agent-identity"]')).toBe(identity);
|
||||
expect(container.textContent).toContain("Working");
|
||||
expect(container.textContent).toContain("Thinking");
|
||||
expect(container.textContent).toContain("Getting ready");
|
||||
expect(container.textContent).not.toContain("Queued");
|
||||
// Choosing a recipient for the next draft does not change the sent request.
|
||||
await act(async () => container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-assignee"]')!.click());
|
||||
@@ -1785,23 +1788,24 @@ describe("TaskChatThread runtime transcript selection", () => {
|
||||
const activity = container.querySelector('[data-testid="task-chat-current-activity-label"]');
|
||||
expect(identity?.textContent).toBe("Runner");
|
||||
expect(identity?.querySelector("svg, img")).not.toBeNull();
|
||||
expect(activity?.textContent).toBe("Thinking");
|
||||
expect(activity?.textContent).toBe("Getting ready");
|
||||
|
||||
renderThread(props);
|
||||
expect(container.querySelector('[data-testid="task-chat-agent-identity"]')).toBe(identity);
|
||||
expect(container.querySelector('[data-testid="task-chat-runner-identity-row"]')).toBe(header);
|
||||
expect(container.querySelector('[data-testid="task-chat-current-activity-label"]')).toBe(activity);
|
||||
|
||||
// The server's first stage after the claim is getting_ready, so the line does not change.
|
||||
for (const startup of [
|
||||
{ ...run, runtimeMode: undefined, status: "queued", startedAt: null },
|
||||
{ ...run, runtimeMode: "legacy" as const, currentStatusMessage: "run started" },
|
||||
run,
|
||||
{ ...run, runtimeMode: "legacy" as const, currentStatusMessage: "run started", startupStage: "getting_ready" as const },
|
||||
{ ...run, startupStage: "getting_ready" as const },
|
||||
]) {
|
||||
renderThread({ ...props, activeRun: startup });
|
||||
expect(container.querySelector('[data-testid="task-chat-agent-identity"]')).toBe(identity);
|
||||
expect(container.querySelector('[data-testid="task-chat-runner-identity-row"]')).toBe(header);
|
||||
expect(container.querySelector('[data-testid="task-chat-current-activity-label"]')).toBe(activity);
|
||||
expect(activity?.textContent).toBe("Thinking");
|
||||
expect(activity?.textContent).toBe("Getting ready");
|
||||
expect(header?.textContent).toContain("Working");
|
||||
expect(container.textContent).not.toContain("Queued");
|
||||
expect(container.querySelector('[data-testid="task-chat-live-run-pill"]')).toBeNull();
|
||||
@@ -1817,6 +1821,42 @@ describe("TaskChatThread runtime transcript selection", () => {
|
||||
expect(container.textContent).toContain("Thinking");
|
||||
});
|
||||
|
||||
it("names a claimed run's startup stage in the activity slot until agent activity arrives", async () => {
|
||||
const run = nativeRunningRun();
|
||||
const props = {
|
||||
comments: [], onAdd: async () => {}, issueStatus: "in_progress",
|
||||
currentUserId: "board", issueAssigneeAgentId: "agent-1",
|
||||
agentMap: new Map([["agent-1", { id: "agent-1", name: "Runner", adapterType: "paperclip_runner", icon: "code" } as Agent]]),
|
||||
};
|
||||
const activity = () => container.querySelector('[data-testid="task-chat-current-activity-label"]');
|
||||
renderThread({ ...props, activeRun: { ...run, startupStage: "connecting_tools" } });
|
||||
expect(activity()?.textContent).toBe("Connecting tools");
|
||||
// The stage is the activity line; the header keeps its usual Working status.
|
||||
expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toContain("Working");
|
||||
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, STARTUP_LABEL_MIN_DISPLAY_MS + 50)); });
|
||||
renderThread({ ...props, activeRun: { ...run, startupStage: "starting_agent", startupSessionResumed: true } });
|
||||
expect(activity()?.textContent).toBe("Resuming session");
|
||||
|
||||
nativeTranscriptState.transcriptByRun.set(run.id, [
|
||||
{ kind: "thinking", ts: "2026-08-25T18:00:01.000Z", text: "", lifecycle: "started", itemId: "reasoning-1" },
|
||||
]);
|
||||
renderThread({ ...props, activeRun: { ...run, startupStage: "starting_agent" } });
|
||||
expect(container.textContent).not.toContain("Starting agent");
|
||||
expect(container.textContent).not.toContain("Resuming session");
|
||||
});
|
||||
|
||||
it("does not name a startup stage for a queued run", () => {
|
||||
const run = nativeRunningRun();
|
||||
renderThread({
|
||||
comments: [], onAdd: async () => {}, issueStatus: "in_progress",
|
||||
currentUserId: "board", issueAssigneeAgentId: "agent-1",
|
||||
agentMap: new Map([["agent-1", { id: "agent-1", name: "Runner", adapterType: "paperclip_runner", icon: "code" } as Agent]]),
|
||||
activeRun: { ...run, status: "queued", startedAt: null, startupStage: "connecting_tools" },
|
||||
});
|
||||
expect(container.textContent).not.toContain("Connecting tools");
|
||||
});
|
||||
|
||||
it.each([false, true].flatMap(mobile => ["streamed", "late", "absent"].map(reply => ({ mobile, reply }))))(
|
||||
"keeps report fallbacks behind complete terminal history ($reply, mobile=$mobile)",
|
||||
({ mobile, reply }) => {
|
||||
|
||||
@@ -3518,6 +3518,8 @@ export function TaskChatThread(props: TaskChatThreadProps) {
|
||||
agent={tailAgent ?? (tailAgentId ? { id: tailAgentId } : undefined)}
|
||||
items={tailItems}
|
||||
preparationLabel={optimisticRunnerStartup && submissionTakingLonger ? "Taking longer than usual…" : undefined}
|
||||
startupStage={liveRun?.id === tailRunId ? liveRun.startupStage : null}
|
||||
startupSessionResumed={liveRun?.id === tailRunId && liveRun.startupSessionResumed === true}
|
||||
allowSummaryFallback={!paperclipRunnerTail ||
|
||||
terminalHydratedRunIds.has(tailRunId ?? "") ||
|
||||
tailEntries.some((entry) => entry.kind === "run_terminal")}
|
||||
|
||||
@@ -5,7 +5,8 @@ import { WAITING_TO_START_LABEL, useWaitingToStart } from "./useWaitingToStart";
|
||||
import { McpAppTurnViews, mcpAppRunRefreshKey } from "@/components/mcp-app/McpAppTurnViews";
|
||||
import { ToolCallProgressRunProvider } from "./tool-call-progress";
|
||||
import { useRef, type ReactNode } from "react";
|
||||
import type { ExecutionProjection } from "@paperclipai/shared";
|
||||
import type { ExecutionProjection, RunStartupStage } from "@paperclipai/shared";
|
||||
import { RUN_STARTUP_STAGE_LABELS, runStartupStageLabel, useHeldLabel } from "./run-startup-stage";
|
||||
import { useSecondTick } from "@/hooks/useSecondTick";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type {
|
||||
@@ -115,14 +116,30 @@ function RunnerTurnStatus({
|
||||
);
|
||||
}
|
||||
|
||||
function RunnerCurrentActivityTail({ status, waitingLabel }: { status: string; waitingLabel?: string | null }) {
|
||||
function RunnerCurrentActivityTail({ status, waitingLabel, startupLabel }: {
|
||||
status: string;
|
||||
waitingLabel?: string | null;
|
||||
/** The claimed run's startup step; work in progress, so it shimmers like Thinking. */
|
||||
startupLabel?: string | null;
|
||||
}) {
|
||||
const shimmer = useTaskChatShimmer("working");
|
||||
const heldStartupLabel = useHeldLabel(waitingLabel ? null : startupLabel ?? null);
|
||||
if (isTerminalRunStatus(status)) return null;
|
||||
return <div className="mt-2 flex min-h-8 min-w-0 items-center gap-2 px-1 py-1 text-xs text-muted-foreground" data-testid="task-chat-current-activity" data-turn-position="tail">
|
||||
<span className={cn(!waitingLabel && shimmer && "shimmer-text shimmer-text-muted")} aria-live="polite" data-testid="task-chat-current-activity-label">{waitingLabel ?? "Thinking"}</span>
|
||||
<span className={cn(!waitingLabel && shimmer && "shimmer-text shimmer-text-muted")} aria-live="polite" data-testid="task-chat-current-activity-label">{waitingLabel ?? heldStartupLabel ?? "Thinking"}</span>
|
||||
</div>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A queued turn is getting ready from submission, which is also the first
|
||||
* stage the server reports once it claims the run, so the line does not change
|
||||
* at the claim. A claimed run names its current stage until the agent works.
|
||||
*/
|
||||
function runnerStartupLabel(status: string, stage: RunStartupStage | null, sessionResumed: boolean): string | null {
|
||||
if (status === "queued") return RUN_STARTUP_STAGE_LABELS.getting_ready;
|
||||
return status === "running" ? runStartupStageLabel(stage, sessionResumed) : null;
|
||||
}
|
||||
|
||||
interface RunnerHeaderProps {
|
||||
runId?: string | null;
|
||||
agentName?: string | null;
|
||||
@@ -172,6 +189,8 @@ export function TaskChatRunnerTurn({
|
||||
status,
|
||||
execution,
|
||||
preparationLabel,
|
||||
startupStage = null,
|
||||
startupSessionResumed = false,
|
||||
startedAtMs,
|
||||
finishedAtMs,
|
||||
activityUnavailable = false,
|
||||
@@ -192,6 +211,9 @@ export function TaskChatRunnerTurn({
|
||||
execution?: ExecutionProjection | null;
|
||||
/** Presentation only while Send/Retry admission has no run yet. */
|
||||
preparationLabel?: string;
|
||||
/** The claimed run's current startup step, until its agent turn starts. */
|
||||
startupStage?: RunStartupStage | null;
|
||||
startupSessionResumed?: boolean;
|
||||
startedAtMs: number | null;
|
||||
finishedAtMs?: number | null;
|
||||
activityUnavailable?: boolean;
|
||||
@@ -339,7 +361,8 @@ export function TaskChatRunnerTurn({
|
||||
</div>
|
||||
) : null}
|
||||
{!final && currentActivityItems.length === 0 && !(status === "queued" && runId && (waitingLabel || agentQueueWaitFor({ status, execution })))
|
||||
? <RunnerCurrentActivityTail status={status} waitingLabel={waitingLabel} /> : null}
|
||||
? <RunnerCurrentActivityTail status={status} waitingLabel={waitingLabel}
|
||||
startupLabel={runnerStartupLabel(status, startupStage, startupSessionResumed)} /> : null}
|
||||
</div></ToolCallProgressRunProvider></TaskChatShimmerScope>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, createElement } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { RUN_STARTUP_STAGES } from "@paperclipai/shared";
|
||||
import {
|
||||
RUN_STARTUP_STAGE_LABELS,
|
||||
runStartupStageLabel,
|
||||
STARTUP_LABEL_MIN_DISPLAY_MS,
|
||||
useHeldLabel,
|
||||
} from "./run-startup-stage";
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const unmounts: Array<() => void> = [];
|
||||
afterEach(() => {
|
||||
for (const unmount of unmounts.splice(0)) unmount();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function renderHeldLabel(initial: string | null) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const root = createRoot(host);
|
||||
const result = { current: null as string | null };
|
||||
let label = initial;
|
||||
function Harness() { result.current = useHeldLabel(label); return null; }
|
||||
const rerender = (next: string | null) => { label = next; act(() => root.render(createElement(Harness))); };
|
||||
unmounts.push(() => { act(() => root.unmount()); host.remove(); });
|
||||
rerender(initial);
|
||||
return { result, rerender };
|
||||
}
|
||||
|
||||
it("names every startup stage and the resumed session", () => {
|
||||
for (const stage of RUN_STARTUP_STAGES) expect(RUN_STARTUP_STAGE_LABELS[stage]).toBeTruthy();
|
||||
expect(runStartupStageLabel("starting_environment")).toBe("Waking up");
|
||||
expect(runStartupStageLabel("connecting_tools")).toBe("Connecting tools");
|
||||
expect(runStartupStageLabel("starting_agent")).toBe("Starting agent");
|
||||
expect(runStartupStageLabel("starting_agent", true)).toBe("Resuming session");
|
||||
expect(runStartupStageLabel("preparing_workspace", true)).toBe("Preparing workspace");
|
||||
expect(runStartupStageLabel(null)).toBeNull();
|
||||
});
|
||||
|
||||
it("shows a changed label at once after the minimum time", () => {
|
||||
vi.useFakeTimers();
|
||||
const { result, rerender } = renderHeldLabel("Getting ready");
|
||||
act(() => { vi.advanceTimersByTime(STARTUP_LABEL_MIN_DISPLAY_MS); });
|
||||
rerender("Waking up");
|
||||
expect(result.current).toBe("Waking up");
|
||||
});
|
||||
|
||||
it("holds a fresh label, then skips to the latest one", () => {
|
||||
vi.useFakeTimers();
|
||||
const { result, rerender } = renderHeldLabel("Getting ready");
|
||||
act(() => { vi.advanceTimersByTime(100); });
|
||||
rerender("Waking up");
|
||||
rerender("Preparing workspace");
|
||||
expect(result.current).toBe("Getting ready");
|
||||
act(() => { vi.advanceTimersByTime(STARTUP_LABEL_MIN_DISPLAY_MS - 101); });
|
||||
expect(result.current).toBe("Getting ready");
|
||||
act(() => { vi.advanceTimersByTime(1); });
|
||||
expect(result.current).toBe("Preparing workspace");
|
||||
});
|
||||
|
||||
it("holds the last stage before returning to the default", () => {
|
||||
vi.useFakeTimers();
|
||||
const { result, rerender } = renderHeldLabel("Starting agent");
|
||||
rerender(null);
|
||||
expect(result.current).toBe("Starting agent");
|
||||
act(() => { vi.advanceTimersByTime(STARTUP_LABEL_MIN_DISPLAY_MS); });
|
||||
expect(result.current).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the shown label when a change is undone within the hold", () => {
|
||||
vi.useFakeTimers();
|
||||
const { result, rerender } = renderHeldLabel("Getting ready");
|
||||
rerender("Waking up");
|
||||
rerender("Getting ready");
|
||||
act(() => { vi.advanceTimersByTime(STARTUP_LABEL_MIN_DISPLAY_MS * 2); });
|
||||
expect(result.current).toBe("Getting ready");
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { RunStartupStage } from "@paperclipai/shared";
|
||||
|
||||
/** The startup step a claimed run is on, in the words the board shows. */
|
||||
export const RUN_STARTUP_STAGE_LABELS: Readonly<Record<RunStartupStage, string>> = {
|
||||
getting_ready: "Getting ready",
|
||||
starting_environment: "Waking up",
|
||||
preparing_workspace: "Preparing workspace",
|
||||
restoring_session: "Restoring session",
|
||||
connecting_tools: "Connecting tools",
|
||||
starting_agent: "Starting agent",
|
||||
};
|
||||
|
||||
export function runStartupStageLabel(
|
||||
stage: RunStartupStage | null | undefined,
|
||||
sessionResumed = false,
|
||||
): string | null {
|
||||
if (!stage) return null;
|
||||
if (stage === "starting_agent" && sessionResumed) return "Resuming session";
|
||||
return RUN_STARTUP_STAGE_LABELS[stage] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long a shown label stays before the next one replaces it. Startup steps
|
||||
* often take a few milliseconds, so a shorter hold would flicker.
|
||||
*/
|
||||
export const STARTUP_LABEL_MIN_DISPLAY_MS = 500;
|
||||
|
||||
/**
|
||||
* Shows a changed label at once when the current one has been visible for the
|
||||
* minimum time. Otherwise it waits out the rest of that time and then shows
|
||||
* the latest label, skipping any that came and went in between. Nothing is
|
||||
* delayed by a prediction of how long a step will last.
|
||||
*/
|
||||
export function useHeldLabel(label: string | null, minDisplayMs = STARTUP_LABEL_MIN_DISPLAY_MS): string | null {
|
||||
const [shown, setShown] = useState(label);
|
||||
const shownAtRef = useRef(Date.now());
|
||||
// Once the hold has passed, show the change in this render, not a later one.
|
||||
const holdPassed = label !== shown && Date.now() - shownAtRef.current >= minDisplayMs;
|
||||
useEffect(() => {
|
||||
if (label === shown) return;
|
||||
const remainingMs = minDisplayMs - (Date.now() - shownAtRef.current);
|
||||
const show = () => {
|
||||
shownAtRef.current = Date.now();
|
||||
setShown(label);
|
||||
};
|
||||
if (remainingMs <= 0) {
|
||||
show();
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(show, remainingMs);
|
||||
return () => clearTimeout(timer);
|
||||
}, [label, shown, minDisplayMs]);
|
||||
return holdPassed ? label : shown;
|
||||
}
|
||||
@@ -579,6 +579,29 @@ describe("LiveUpdatesProvider issue invalidation", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("patches a run's startup stage and drops unknown stages", () => {
|
||||
const read = (stage: unknown, sessionResumed?: unknown) =>
|
||||
__liveUpdatesTestUtils.readRunLiveStatusPatchFromPayload(
|
||||
{ runId: "run-1", agentId: "agent-1", issueId: "issue-1", stage, sessionResumed },
|
||||
"2026-04-06T12:00:09.000Z",
|
||||
"heartbeat.run.startup_stage",
|
||||
);
|
||||
expect(read("connecting_tools")).toEqual({
|
||||
runId: "run-1", agentId: "agent-1", issueId: "issue-1",
|
||||
startupStage: "connecting_tools", startupSessionResumed: false,
|
||||
});
|
||||
expect(read("starting_agent", true)).toMatchObject({ startupStage: "starting_agent", startupSessionResumed: true });
|
||||
expect(read(null)).toMatchObject({ startupStage: null });
|
||||
expect(read("made_up_stage")).toMatchObject({ startupStage: null });
|
||||
|
||||
const client = new QueryClient();
|
||||
client.setQueryData(queryKeys.liveRuns("company-1"), [{ id: "run-1", status: "running", startupStage: "getting_ready" }]);
|
||||
__liveUpdatesTestUtils.applyRunLiveStatusPatchToCaches(client, "company-1", "/", read("restoring_session")!);
|
||||
expect(client.getQueryData(queryKeys.liveRuns("company-1"))).toEqual([
|
||||
expect.objectContaining({ startupStage: "restoring_session", startupSessionResumed: false }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses the heartbeat event timestamp for run event status patches", () => {
|
||||
expect(
|
||||
__liveUpdatesTestUtils.readRunLiveStatusPatchFromPayload(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { LiveTranscriptInterests, DISCONNECTED_TRANSCRIPT_STREAM } from "../lib/live-transcript-interests";
|
||||
import { resolveAgentAppearance, TASK_IDENTITY_CHANGED_FIELD, issueActivityChangesTaskIdentity } from "@paperclipai/shared";
|
||||
import { RUN_STARTUP_STAGES, resolveAgentAppearance, TASK_IDENTITY_CHANGED_FIELD, issueActivityChangesTaskIdentity, type RunStartupStage } from "@paperclipai/shared";
|
||||
import { getPageVisibility, usePageVisibility } from "../lib/page-visibility";
|
||||
import { createLiveQueryRecovery } from "../lib/live-query-recovery";
|
||||
import { isLiveReconciledQuery } from "../lib/live-reconcile";
|
||||
@@ -667,6 +667,8 @@ interface RunLiveStatusPatch {
|
||||
currentToolName?: string | null;
|
||||
lastAssistantSnippet?: string | null;
|
||||
lastEventAt?: string | null;
|
||||
startupStage?: RunStartupStage | null;
|
||||
startupSessionResumed?: boolean;
|
||||
}
|
||||
|
||||
function hasPatchKey<K extends keyof RunLiveStatusPatch>(
|
||||
@@ -698,6 +700,12 @@ function applyRunLiveStatusPatch<T extends ActiveRunForIssue | LiveRunForIssue>(
|
||||
...(hasPatchKey(patch, "lastEventAt")
|
||||
? { lastEventAt: patch.lastEventAt }
|
||||
: {}),
|
||||
...(hasPatchKey(patch, "startupStage")
|
||||
? { startupStage: patch.startupStage }
|
||||
: {}),
|
||||
...(hasPatchKey(patch, "startupSessionResumed")
|
||||
? { startupSessionResumed: patch.startupSessionResumed }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -738,6 +746,15 @@ function readRunLiveStatusPatchFromPayload(
|
||||
return patch;
|
||||
}
|
||||
|
||||
if (eventType === "heartbeat.run.startup_stage") {
|
||||
const stage = readString(payload.stage);
|
||||
patch.startupStage = stage && (RUN_STARTUP_STAGES as readonly string[]).includes(stage)
|
||||
? stage as RunStartupStage
|
||||
: null;
|
||||
patch.startupSessionResumed = payload.sessionResumed === true;
|
||||
return patch;
|
||||
}
|
||||
|
||||
if (eventType === "heartbeat.run.log" || eventType === "heartbeat.run.activity") {
|
||||
patch.lastEventAt = readString(payload.ts) ?? eventCreatedAt;
|
||||
return patch;
|
||||
@@ -2168,7 +2185,9 @@ function handleLiveEvent(
|
||||
liveStatusPatch,
|
||||
)
|
||||
: false;
|
||||
if (event.type === "heartbeat.run.log" || event.type === "heartbeat.run.activity") {
|
||||
// The startup stage only patches cached runs; the next run read carries it too.
|
||||
if (event.type === "heartbeat.run.log" || event.type === "heartbeat.run.activity"
|
||||
|| event.type === "heartbeat.run.startup_stage") {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user