From 0eaeb94564d857d2875754e7ae775d43f12fa8eb Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 2 Jul 2026 05:14:52 -0700 Subject: [PATCH] Address macroscope + cursor follow-up review findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ClaudeAdapter: dedupe workflow agents/phases by index (last write wins) before applying entry caps, so repeated slot updates cannot exhaust the cap and freeze later agents stale; restrict sessionUrl to http(s) so a hostile tool result cannot smuggle a javascript: href - workflowUi: guard sessionUrl scheme again at both anchor render sites (defense in depth for payloads persisted before the adapter filter) - Ingestion: JSON-encode the (threadId, taskId) tuple in stable workflow activity ids to remove delimiter-ambiguity collisions - workflow-logic: order same-timestamp activities by provider sequence then lifecycle rank so task.completed can never apply before its task.started - WorkflowPanel/Card: scope phase and agent row keys by taskId so switching runs remounts rows instead of leaking expanded transcript state and cursors across runs - workflowUi: phase progress counter counts settled (done + error) agents instead of reporting 0/1 for an errored terminal phase - client-runtime: readJournal query polls every 4s while mounted so the Logs tab picks up new results during a live run - mobile: keep workflow task.completed rows (only per-tick progress is suppressed) — with no workflow card on mobile it is the only signal a workflow finished or failed Co-Authored-By: Claude Fable 5 --- apps/mobile/src/lib/threadActivity.ts | 6 ++- .../Layers/ProviderRuntimeIngestion.test.ts | 15 ++++--- .../Layers/ProviderRuntimeIngestion.ts | 6 ++- .../src/provider/Layers/ClaudeAdapter.ts | 39 ++++++++++++++----- .../src/components/workflow/WorkflowPanel.tsx | 13 +++++-- .../components/workflow/WorkflowRunCard.tsx | 14 +++++-- .../src/components/workflow/workflowUi.tsx | 21 +++++++++- apps/web/src/workflow-logic.ts | 34 ++++++++++++++-- packages/client-runtime/src/state/workflow.ts | 4 ++ 9 files changed, 122 insertions(+), 30 deletions(-) diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 2a2437a958..8aae399ba8 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -281,11 +281,13 @@ function deriveWorkLogEntries( if (activity.kind === "task.started") continue; // Workflow snapshot/meta activities back the desktop workflow card; on // mobile they would render as ever-mutating raw rows, so skip them — - // along with the per-tick task rows the workflow owns. + // along with the per-tick progress rows the workflow owns. task.completed + // stays: with no workflow card here it is mobile's only signal that a + // workflow finished, failed, or was stopped. if (activity.kind === "task.workflow-updated") continue; if (activity.kind === "task.workflow-meta") continue; if ( - (activity.kind === "task.progress" || activity.kind === "task.completed") && + activity.kind === "task.progress" && workflowTaskIds.size > 0 && activityBelongsToWorkflow(activity, workflowTaskIds) ) { diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index f11fd8ed34..a997565c15 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -3122,7 +3122,8 @@ describe("ProviderRuntimeIngestion", () => { const thread = await waitForThread(harness.readModel, (entry) => entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.id === "workflow:thread-1:task-wf-1", + (activity: ProviderRuntimeTestActivity) => + activity.id === `workflow:${JSON.stringify(["thread-1", "task-wf-1"])}`, ), ); @@ -3132,7 +3133,8 @@ describe("ProviderRuntimeIngestion", () => { expect(perTick?.kind).toBe("task.progress"); const snapshot = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "workflow:thread-1:task-wf-1", + (activity: ProviderRuntimeTestActivity) => + activity.id === `workflow:${JSON.stringify(["thread-1", "task-wf-1"])}`, ); expect(snapshot?.kind).toBe("task.workflow-updated"); const payload = @@ -3165,11 +3167,13 @@ describe("ProviderRuntimeIngestion", () => { const thread = await waitForThread(harness.readModel, (entry) => entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.id === "workflow-meta:thread-1:task-wf-meta", + (activity: ProviderRuntimeTestActivity) => + activity.id === `workflow-meta:${JSON.stringify(["thread-1", "task-wf-meta"])}`, ), ); const meta = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "workflow-meta:thread-1:task-wf-meta", + (activity: ProviderRuntimeTestActivity) => + activity.id === `workflow-meta:${JSON.stringify(["thread-1", "task-wf-meta"])}`, ); expect(meta?.kind).toBe("task.workflow-meta"); const payload = @@ -3226,7 +3230,8 @@ describe("ProviderRuntimeIngestion", () => { const drainedThread = drained.threads.find((entry) => entry.id === ThreadId.make("thread-1")); const snapshots = drainedThread?.activities.filter( - (activity: ProviderRuntimeTestActivity) => activity.id === "workflow:thread-1:task-wf-2", + (activity: ProviderRuntimeTestActivity) => + activity.id === `workflow:${JSON.stringify(["thread-1", "task-wf-2"])}`, ); expect(snapshots).toHaveLength(1); const payload = diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 4af42f924c..5cb6c3561f 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -167,12 +167,14 @@ function maxCheckpointTurnCount( * Stable per-task activity ids: workflow snapshot/meta activities are * upserted (one projection row per run), not appended per progress tick. */ +// JSON-encode the (threadId, taskId) tuple: both are free-form strings, so a +// bare `:`-joined key would let distinct pairs collide on the upsert id. function workflowActivityId(threadId: ThreadId, taskId: string): EventId { - return EventId.make(`workflow:${threadId}:${taskId}`); + return EventId.make(`workflow:${JSON.stringify([threadId, taskId])}`); } function workflowMetaActivityId(threadId: ThreadId, taskId: string): EventId { - return EventId.make(`workflow-meta:${threadId}:${taskId}`); + return EventId.make(`workflow-meta:${JSON.stringify([threadId, taskId])}`); } function truncateDetail(value: string, limit = 180): string { diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index f62a33068c..d1eb5bba0c 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -831,8 +831,11 @@ function normalizeWorkflowProgress( if (!Array.isArray(value) || value.length === 0) { return undefined; } - const agents: Array = []; - const phases: Array = []; + // Last write wins per index: the snapshot may re-emit an agent/phase slot + // (retries, later progress), and the cap must count unique slots, not raw + // entries, or repeats would freeze later agents in a stale state. + const agentsByIndex = new Map(); + const phasesByIndex = new Map(); const logs: Array = []; for (const raw of value) { if (raw === null || typeof raw !== "object" || Array.isArray(raw)) { @@ -842,8 +845,11 @@ function normalizeWorkflowProgress( switch (entry.type) { case "workflow_agent": { const agent = normalizeWorkflowAgentEntry(entry); - if (agent && agents.length < MAX_WORKFLOW_AGENT_ENTRIES) { - agents.push(agent); + if ( + agent && + (agentsByIndex.has(agent.index) || agentsByIndex.size < MAX_WORKFLOW_AGENT_ENTRIES) + ) { + agentsByIndex.set(agent.index, agent); } break; } @@ -853,9 +859,9 @@ function normalizeWorkflowProgress( if ( index !== undefined && title !== undefined && - phases.length < MAX_WORKFLOW_PHASE_ENTRIES + (phasesByIndex.has(index) || phasesByIndex.size < MAX_WORKFLOW_PHASE_ENTRIES) ) { - phases.push({ + phasesByIndex.set(index, { type: "workflow_phase", index, title, @@ -880,7 +886,7 @@ function normalizeWorkflowProgress( // Narration is append-only upstream; keep the newest lines when clipping. const clippedLogs = logs.length > MAX_WORKFLOW_LOG_ENTRIES ? logs.slice(-MAX_WORKFLOW_LOG_ENTRIES) : logs; - const entries = [...phases, ...agents, ...clippedLogs]; + const entries = [...phasesByIndex.values(), ...agentsByIndex.values(), ...clippedLogs]; return entries.length > 0 ? entries : undefined; } @@ -893,6 +899,21 @@ function readClaudeWorkflowProgress( return normalizeWorkflowProgress(raw); } +function workflowHttpUrl(value: unknown): string | undefined { + const text = workflowString(value); + if (text === undefined) { + return undefined; + } + // Clients render this into an anchor href — restrict to web URLs so a + // hostile tool result cannot smuggle a javascript:/file: scheme through. + try { + const parsed = new URL(text); + return parsed.protocol === "https:" || parsed.protocol === "http:" ? text : undefined; + } catch { + return undefined; + } +} + function normalizeWorkflowRunHandles( toolUseResult: Record, ): WorkflowRunHandles | undefined { @@ -917,8 +938,8 @@ function normalizeWorkflowRunHandles( ...(workflowString(toolUseResult.transcriptDir) !== undefined ? { transcriptDir: workflowString(toolUseResult.transcriptDir) } : {}), - ...(workflowString(toolUseResult.sessionUrl) !== undefined - ? { sessionUrl: workflowString(toolUseResult.sessionUrl) } + ...(workflowHttpUrl(toolUseResult.sessionUrl) !== undefined + ? { sessionUrl: workflowHttpUrl(toolUseResult.sessionUrl) } : {}), ...(workflowString(toolUseResult.warning) !== undefined ? { warning: workflowString(toolUseResult.warning) } diff --git a/apps/web/src/components/workflow/WorkflowPanel.tsx b/apps/web/src/components/workflow/WorkflowPanel.tsx index 3a5aded319..b8ddca7bb0 100644 --- a/apps/web/src/components/workflow/WorkflowPanel.tsx +++ b/apps/web/src/components/workflow/WorkflowPanel.tsx @@ -30,7 +30,12 @@ import { workflowRunTitle, } from "~/workflow-logic"; import { Button } from "../ui/button"; -import { AgentRowContent, PhaseHeader, WorkflowStatusChip } from "./workflowUi"; +import { + AgentRowContent, + PhaseHeader, + WorkflowStatusChip, + safeWorkflowSessionUrl, +} from "./workflowUi"; import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; type WorkflowTabId = "run" | "script" | "logs"; @@ -199,7 +204,7 @@ function RunTab({ remote: boolean; }): ReactElement { if (remote) { - const sessionUrl = run.handles?.sessionUrl; + const sessionUrl = safeWorkflowSessionUrl(run.handles?.sessionUrl); if (sessionUrl === undefined) { return ; } @@ -223,11 +228,11 @@ function RunTab({ return (
{run.phases.map((phase) => ( -
+
{phase.agents.map((agent) => ( +
{rows.map((agent) => ( -
+
))} @@ -124,7 +130,7 @@ export function WorkflowRunCard(props: { } function RemoteRunBody({ run }: { run: WorkflowRun }): ReactElement { - const sessionUrl = run.handles?.sessionUrl; + const sessionUrl = safeWorkflowSessionUrl(run.handles?.sessionUrl); if (sessionUrl === undefined) { return (

diff --git a/apps/web/src/components/workflow/workflowUi.tsx b/apps/web/src/components/workflow/workflowUi.tsx index aa7f951911..836bdb000d 100644 --- a/apps/web/src/components/workflow/workflowUi.tsx +++ b/apps/web/src/components/workflow/workflowUi.tsx @@ -157,8 +157,27 @@ export function AgentRowContent({ // Phase header + rollup helpers // --------------------------------------------------------------------------- +/** + * Only web URLs may reach an anchor href. The server already filters the + * scheme at ingestion; this guards payloads persisted before that filter + * (and any other producer) as defense in depth. + */ +export function safeWorkflowSessionUrl(sessionUrl: string | undefined): string | undefined { + if (sessionUrl === undefined) { + return undefined; + } + try { + const parsed = new URL(sessionUrl); + return parsed.protocol === "https:" || parsed.protocol === "http:" ? sessionUrl : undefined; + } catch { + return undefined; + } +} + +/** Settled agents (done or error) — the x/y header is a progress counter, + * and an errored agent has no work remaining. */ export function phaseDoneCount(phase: WorkflowRunPhase): number { - return phase.agents.filter((agent) => agent.status === "done").length; + return phase.agents.filter((agent) => agent.status === "done" || agent.status === "error").length; } export function PhaseHeader({ phase }: { phase: WorkflowRunPhase }): ReactElement { diff --git a/apps/web/src/workflow-logic.ts b/apps/web/src/workflow-logic.ts index 8e6cb90dee..253db4edd3 100644 --- a/apps/web/src/workflow-logic.ts +++ b/apps/web/src/workflow-logic.ts @@ -300,13 +300,41 @@ export function collectWorkflowTaskIds( return taskIds; } +/** + * Millisecond timestamps collide, so equal-time activities are ordered by + * provider sequence when present, then by lifecycle rank — a task.completed + * must never be applied before the task.started that creates its run. + */ +const WORKFLOW_ACTIVITY_RANK: Record = { + "task.started": 0, + "task.workflow-meta": 1, + "task.workflow-updated": 1, + "task.completed": 2, +}; + +function compareWorkflowActivityOrder( + a: OrchestrationThreadActivity, + b: OrchestrationThreadActivity, +): number { + if (a.sequence !== undefined && b.sequence !== undefined && a.sequence !== b.sequence) { + return a.sequence - b.sequence; + } + const byTime = a.createdAt.localeCompare(b.createdAt); + if (byTime !== 0) { + return byTime; + } + const byRank = (WORKFLOW_ACTIVITY_RANK[a.kind] ?? 1) - (WORKFLOW_ACTIVITY_RANK[b.kind] ?? 1); + if (byRank !== 0) { + return byRank; + } + return a.id.localeCompare(b.id); +} + export function deriveWorkflowRuns( activities: ReadonlyArray, options?: { readonly sessionActive?: boolean | undefined }, ): WorkflowRun[] { - const ordered = [...activities].toSorted( - (a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id), - ); + const ordered = [...activities].toSorted(compareWorkflowActivityOrder); const runs = new Map(); const ensureRun = (taskId: string, activity: OrchestrationThreadActivity): MutableWorkflowRun => { diff --git a/packages/client-runtime/src/state/workflow.ts b/packages/client-runtime/src/state/workflow.ts index cf169623e5..4c679919fd 100644 --- a/packages/client-runtime/src/state/workflow.ts +++ b/packages/client-runtime/src/state/workflow.ts @@ -25,6 +25,10 @@ export function createWorkflowEnvironmentAtoms( label: "environment-data:workflow:read-journal", tag: WS_METHODS.workflowReadJournal, staleTimeMs: 5_000, + // The journal grows while a run is live and the query only mounts + // while the Logs tab is open — poll so new results appear without a + // manual refresh. + refreshIntervalMs: 4_000, }), readAgentTranscript: createEnvironmentRpcCommand(runtime, { label: "environment-data:workflow:read-agent-transcript",