From e5b721efc657a610b47f164071907192e31807f2 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 2 Jul 2026 04:57:52 -0700 Subject: [PATCH] Address review findings from multi-agent review pass - WorkflowInspectionService: re-contain joined leaf files so a symlink named journal.jsonl / agent-.jsonl cannot escape the projects root (readScript already did this); add regression tests for both - Stop serializing raw fs error causes in WorkflowInspectionError - ProviderCommandReactor: surface stopTask failures as a provider.task.stop.failed activity instead of a silent log warning - ProviderService.stopTask: don't resurrect a stopped session via recovery just to stop a task - Ingestion: scope stable workflow activity ids by threadId so SDK task id reuse across threads cannot collide in the projection table - WorkflowPanel: keep polling transcripts past prior EOF ("complete" means caught-up, not finished); reuse useCopyToClipboard for the resume-command button - workflow-logic: terminalize runs left "running" when the provider session is gone; add a revision counter so timeline rows re-render on content changes even when timestamps collide Co-Authored-By: Claude Fable 5 --- .../Layers/ProviderCommandReactor.ts | 21 ++++++++-- .../Layers/ProviderRuntimeIngestion.test.ts | 10 ++--- .../Layers/ProviderRuntimeIngestion.ts | 12 +++--- .../src/provider/Layers/ProviderService.ts | 11 ++++- .../WorkflowInspectionService.test.ts | 40 +++++++++++++++++++ .../src/workflow/WorkflowInspectionService.ts | 19 +++++---- apps/web/src/components/ChatView.tsx | 10 ++++- .../components/chat/MessagesTimeline.logic.ts | 8 ++-- .../src/components/workflow/WorkflowPanel.tsx | 33 +++++---------- apps/web/src/workflow-logic.ts | 17 ++++++++ packages/contracts/src/workflow.ts | 1 - 11 files changed, 132 insertions(+), 50 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 60df8c225c..f433080749 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -1023,10 +1023,23 @@ const make = Effect.gen(function* () { }); } - yield* providerService.stopTask({ - threadId: event.payload.threadId, - taskId: event.payload.taskId, - }); + yield* providerService + .stopTask({ + threadId: event.payload.threadId, + taskId: event.payload.taskId, + }) + .pipe( + Effect.catchCause((cause) => + appendProviderFailureActivity({ + threadId: event.payload.threadId, + kind: "provider.task.stop.failed", + summary: "Background task stop failed", + detail: Cause.pretty(cause), + turnId: null, + createdAt: event.payload.createdAt, + }), + ), + ); }); const processDomainEvent = Effect.fn("processDomainEvent")(function* ( diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 7130b396bb..f11fd8ed34 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -3122,7 +3122,7 @@ describe("ProviderRuntimeIngestion", () => { const thread = await waitForThread(harness.readModel, (entry) => entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.id === "workflow:task-wf-1", + (activity: ProviderRuntimeTestActivity) => activity.id === "workflow:thread-1:task-wf-1", ), ); @@ -3132,7 +3132,7 @@ describe("ProviderRuntimeIngestion", () => { expect(perTick?.kind).toBe("task.progress"); const snapshot = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "workflow:task-wf-1", + (activity: ProviderRuntimeTestActivity) => activity.id === "workflow:thread-1:task-wf-1", ); expect(snapshot?.kind).toBe("task.workflow-updated"); const payload = @@ -3165,11 +3165,11 @@ describe("ProviderRuntimeIngestion", () => { const thread = await waitForThread(harness.readModel, (entry) => entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.id === "workflow-meta:task-wf-meta", + (activity: ProviderRuntimeTestActivity) => activity.id === "workflow-meta:thread-1:task-wf-meta", ), ); const meta = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "workflow-meta:task-wf-meta", + (activity: ProviderRuntimeTestActivity) => activity.id === "workflow-meta:thread-1:task-wf-meta", ); expect(meta?.kind).toBe("task.workflow-meta"); const payload = @@ -3226,7 +3226,7 @@ describe("ProviderRuntimeIngestion", () => { const drainedThread = drained.threads.find((entry) => entry.id === ThreadId.make("thread-1")); const snapshots = drainedThread?.activities.filter( - (activity: ProviderRuntimeTestActivity) => activity.id === "workflow:task-wf-2", + (activity: ProviderRuntimeTestActivity) => activity.id === "workflow: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 8df21f579b..4af42f924c 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -167,12 +167,12 @@ function maxCheckpointTurnCount( * Stable per-task activity ids: workflow snapshot/meta activities are * upserted (one projection row per run), not appended per progress tick. */ -function workflowActivityId(taskId: string): EventId { - return EventId.make(`workflow:${taskId}`); +function workflowActivityId(threadId: ThreadId, taskId: string): EventId { + return EventId.make(`workflow:${threadId}:${taskId}`); } -function workflowMetaActivityId(taskId: string): EventId { - return EventId.make(`workflow-meta:${taskId}`); +function workflowMetaActivityId(threadId: ThreadId, taskId: string): EventId { + return EventId.make(`workflow-meta:${threadId}:${taskId}`); } function truncateDetail(value: string, limit = 180): string { @@ -507,7 +507,7 @@ function runtimeEventToActivities( return [ progressActivity, { - id: workflowActivityId(event.payload.taskId), + id: workflowActivityId(event.threadId, event.payload.taskId), createdAt: event.createdAt, tone: "info", kind: "task.workflow-updated", @@ -527,7 +527,7 @@ function runtimeEventToActivities( case "task.workflowMeta": { return [ { - id: workflowMetaActivityId(event.payload.taskId), + id: workflowMetaActivityId(event.threadId, event.payload.taskId), createdAt: event.createdAt, tone: "info", kind: "task.workflow-meta", diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 20546ac529..03df91c07d 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -761,10 +761,13 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( schema: ProviderStopTaskInput, payload: rawInput, }); + // No recovery: a background task cannot be running without a live + // in-process session, so resurrecting one just to stop a task would be + // wasted work (and would resume the session as a side effect). const routed = yield* resolveRoutableSession({ threadId: input.threadId, operation: "ProviderService.stopTask", - allowRecovery: true, + allowRecovery: false, }); yield* Effect.annotateCurrentSpan({ "provider.operation": "stop-task", @@ -772,6 +775,12 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( "provider.thread_id": input.threadId, "provider.task_id": input.taskId, }); + if (!routed.isActive) { + return yield* toValidationError( + "ProviderService.stopTask", + "No active provider session is running for this thread.", + ); + } const adapterStopTask = routed.adapter.stopTask; if (adapterStopTask === undefined) { return yield* toValidationError( diff --git a/apps/server/src/workflow/WorkflowInspectionService.test.ts b/apps/server/src/workflow/WorkflowInspectionService.test.ts index 5dcc4884a4..410ac39412 100644 --- a/apps/server/src/workflow/WorkflowInspectionService.test.ts +++ b/apps/server/src/workflow/WorkflowInspectionService.test.ts @@ -185,6 +185,25 @@ describe("WorkflowInspectionService", () => { }).pipe(Effect.provide(NodeServices.layer)), ); + it.effect("rejects a journal.jsonl symlink that escapes the root as invalid-path", () => + Effect.gen(function* () { + const { fs, service, layout } = yield* setup; + const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-workflow-outside-" }); + const secret = NodePath.join(outside, "secret.jsonl"); + yield* fs.writeFileString(secret, JSON.stringify({ type: "started", agentId: "leak" })); + + const escapeDir = NodePath.join(layout.transcriptDir, "..", "wf_journal_escape"); + yield* fs.makeDirectory(escapeDir, { recursive: true }); + yield* Effect.promise(() => + NodeFSP.symlink(secret, NodePath.join(escapeDir, "journal.jsonl")), + ); + + const error = yield* service.readJournal({ transcriptDir: escapeDir }).pipe(Effect.flip); + assert.equal(error._tag, "WorkflowInspectionError"); + assert.equal(error.reason, "invalid-path"); + }).pipe(Effect.provide(NodeServices.layer)), + ); + it.effect("rejects a transcript dir outside the root as invalid-path", () => Effect.gen(function* () { const { fs, service } = yield* setup; @@ -295,6 +314,27 @@ describe("WorkflowInspectionService", () => { }).pipe(Effect.provide(NodeServices.layer)), ); + it.effect("rejects an agent transcript symlink that escapes the root as invalid-path", () => + Effect.gen(function* () { + const { fs, service, layout } = yield* setup; + const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-workflow-outside-" }); + const secret = NodePath.join(outside, "secret.txt"); + yield* fs.writeFileString(secret, "root:x:0:0::/root:/bin/bash"); + + const escapeDir = NodePath.join(layout.transcriptDir, "..", "wf_transcript_escape"); + yield* fs.makeDirectory(escapeDir, { recursive: true }); + yield* Effect.promise(() => + NodeFSP.symlink(secret, NodePath.join(escapeDir, "agent-leak.jsonl")), + ); + + const error = yield* service + .readAgentTranscript({ transcriptDir: escapeDir, agentId: "leak" }) + .pipe(Effect.flip); + assert.equal(error._tag, "WorkflowInspectionError"); + assert.equal(error.reason, "invalid-path"); + }).pipe(Effect.provide(NodeServices.layer)), + ); + it.effect("reports a missing transcript as not-found", () => Effect.gen(function* () { const { service, layout } = yield* setup; diff --git a/apps/server/src/workflow/WorkflowInspectionService.ts b/apps/server/src/workflow/WorkflowInspectionService.ts index c771278c49..bad1f2c39f 100644 --- a/apps/server/src/workflow/WorkflowInspectionService.ts +++ b/apps/server/src/workflow/WorkflowInspectionService.ts @@ -116,7 +116,6 @@ export const make = (options?: { readonly projectsRoot?: string }) => operation, reason: isEnoent(cause) ? "not-found" : "read-failed", detail: "Failed to resolve the workflow projects root.", - cause, }), }); @@ -127,7 +126,6 @@ export const make = (options?: { readonly projectsRoot?: string }) => operation, reason: isEnoent(cause) ? "not-found" : "read-failed", detail: "Failed to resolve the requested path.", - cause, }), }); @@ -162,7 +160,6 @@ export const make = (options?: { readonly projectsRoot?: string }) => operation, reason: isNotFoundPlatformError(cause) ? "not-found" : "read-failed", detail: "Failed to read the workflow script.", - cause, }), ), ); @@ -179,7 +176,12 @@ export const make = (options?: { readonly projectsRoot?: string }) => ) { const operation = "WorkflowInspectionService.readJournal"; const realDir = yield* resolveContained(operation, input.transcriptDir); - const journalPath = NodePath.join(realDir, "journal.jsonl"); + // Re-contain the joined leaf: a symlink named journal.jsonl inside a + // valid directory must not escape the projects root. + const journalPath = yield* resolveContained( + operation, + NodePath.join(realDir, "journal.jsonl"), + ); const raw = yield* fs.readFileString(journalPath).pipe( Effect.mapError( (cause) => @@ -187,7 +189,6 @@ export const make = (options?: { readonly projectsRoot?: string }) => operation, reason: isNotFoundPlatformError(cause) ? "not-found" : "read-failed", detail: "Failed to read the workflow journal.", - cause, }), ), ); @@ -259,7 +260,12 @@ export const make = (options?: { readonly projectsRoot?: string }) => } const realDir = yield* resolveContained(operation, input.transcriptDir); - const transcriptPath = NodePath.join(realDir, `agent-${input.agentId}.jsonl`); + // Re-contain the joined leaf: a symlink named agent-.jsonl inside + // a valid directory must not escape the projects root. + const transcriptPath = yield* resolveContained( + operation, + NodePath.join(realDir, `agent-${input.agentId}.jsonl`), + ); // v1 reads the whole file per page; acceptable for current transcript // sizes. Revisit with a streaming/seek reader if transcripts grow large. const raw = yield* fs.readFileString(transcriptPath).pipe( @@ -269,7 +275,6 @@ export const make = (options?: { readonly projectsRoot?: string }) => operation, reason: isNotFoundPlatformError(cause) ? "not-found" : "read-failed", detail: "Failed to read the agent transcript.", - cause, }), ), ); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index e89b8b4333..4bc0c53840 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1730,7 +1730,15 @@ function ChatViewContent(props: ChatViewProps) { const phase = derivePhase(activeThread?.session ?? null); const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES; const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]); - const workflowRuns = useMemo(() => deriveWorkflowRuns(threadActivities), [threadActivities]); + const workflowSessionActive = + activeThread?.session !== null && + activeThread?.session !== undefined && + activeThread.session.status !== "stopped" && + activeThread.session.status !== "error"; + const workflowRuns = useMemo( + () => deriveWorkflowRuns(threadActivities, { sessionActive: workflowSessionActive }), + [threadActivities, workflowSessionActive], + ); const activeWorkflowSurface = activeRightPanelSurface?.kind === "workflow" ? activeRightPanelSurface : null; const activeWorkflowRun = useMemo( diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index fcc57defa5..40adf7f18d 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -590,12 +590,14 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean case "workflow": { const bw = b as typeof a; - // WorkflowRun view models are rebuilt per derivation; compare the - // fields that drive rendering so unchanged runs keep row identity. + // WorkflowRun view models are rebuilt per derivation; `revision` is a + // deterministic per-run change counter, so equal revisions (and status, + // which sessionActive can flip without a new activity) mean identical + // content. return ( a.createdAt === bw.createdAt && a.workflowRun.status === bw.workflowRun.status && - a.workflowRun.updatedAt === bw.workflowRun.updatedAt + a.workflowRun.revision === bw.workflowRun.revision ); } diff --git a/apps/web/src/components/workflow/WorkflowPanel.tsx b/apps/web/src/components/workflow/WorkflowPanel.tsx index 2f0545aeb4..e191399373 100644 --- a/apps/web/src/components/workflow/WorkflowPanel.tsx +++ b/apps/web/src/components/workflow/WorkflowPanel.tsx @@ -31,6 +31,7 @@ import { } from "~/workflow-logic"; import { Button } from "../ui/button"; import { AgentRowContent, PhaseHeader, WorkflowStatusChip } from "./workflowUi"; +import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; type WorkflowTabId = "run" | "script" | "logs"; @@ -165,32 +166,18 @@ function CopyResumeButton({ scriptPath: string; runId: string; }): ReactElement { - const [copied, setCopied] = useState(false); - const timerRef = useRef | null>(null); - - useEffect( - () => () => { - if (timerRef.current !== null) { - clearTimeout(timerRef.current); - } - }, - [], - ); + const { copyToClipboard, isCopied } = useCopyToClipboard({ + timeout: 1200, + target: "workflow resume command", + }); const handleCopy = useCallback(() => { - const command = `Workflow({ scriptPath: "${scriptPath}", resumeFromRunId: "${runId}" })`; - void navigator.clipboard.writeText(command).then(() => { - setCopied(true); - if (timerRef.current !== null) { - clearTimeout(timerRef.current); - } - timerRef.current = setTimeout(() => setCopied(false), 1200); - }); - }, [runId, scriptPath]); + copyToClipboard(`Workflow({ scriptPath: "${scriptPath}", resumeFromRunId: "${runId}" })`); + }, [copyToClipboard, runId, scriptPath]); return ( ); @@ -395,7 +382,9 @@ function AgentTranscriptView({ const loadingRef = useRef(false); const loadMore = useCallback(async () => { - if (loadingRef.current || completeRef.current) { + // `complete` only means the last read caught up to end-of-file; a live + // run keeps appending, so polling must keep re-reading past prior EOF. + if (loadingRef.current) { return; } loadingRef.current = true; diff --git a/apps/web/src/workflow-logic.ts b/apps/web/src/workflow-logic.ts index 9f78fa8988..1744f9b283 100644 --- a/apps/web/src/workflow-logic.ts +++ b/apps/web/src/workflow-logic.ts @@ -69,6 +69,10 @@ export interface WorkflowRun { status: WorkflowRunStatus; createdAt: string; updatedAt: string; + /** Monotonic per-derivation change counter — bumped on every applied + * workflow activity so renderers can cheaply detect content changes even + * when timestamps collide at millisecond precision. */ + revision: number; turnId: TurnId | null; name?: string | undefined; description?: string | undefined; @@ -300,6 +304,7 @@ export function collectWorkflowTaskIds( 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), @@ -317,6 +322,7 @@ export function deriveWorkflowRuns( createdAt: activity.createdAt, updatedAt: activity.createdAt, turnId: activity.turnId, + revision: 0, phases: [], logs: [], agentCounts: { total: 0, queued: 0, running: 0, done: 0, error: 0 }, @@ -342,6 +348,7 @@ export function deriveWorkflowRuns( break; } const run = ensureRun(taskId, activity); + run.revision += 1; run.hasStartedActivity = true; run.createdAt = activity.createdAt; run.turnId = activity.turnId; @@ -357,6 +364,7 @@ export function deriveWorkflowRuns( } case "task.workflow-updated": { const run = ensureRun(taskId, activity); + run.revision += 1; run.updatedAt = activity.createdAt; const description = asString(payload.description); if (description !== undefined && run.description === undefined) { @@ -380,6 +388,7 @@ export function deriveWorkflowRuns( } case "task.workflow-meta": { const run = ensureRun(taskId, activity); + run.revision += 1; run.updatedAt = activity.createdAt; const name = asString(payload.workflowName); if (name !== undefined) { @@ -410,6 +419,7 @@ export function deriveWorkflowRuns( if (!run) { break; } + run.revision += 1; run.updatedAt = activity.createdAt; run.status = payload.status === "failed" @@ -428,8 +438,15 @@ export function deriveWorkflowRuns( } } + // A workflow cannot outlive its provider session: when the session is gone + // and no task_notification ever arrived (crash, interrupt, app restart), + // surface the run as stopped instead of running forever. + const sessionActive = options?.sessionActive ?? true; return [...runs.values()] .map(({ hasStartedActivity: _hasStartedActivity, ...run }) => run) + .map((run) => + run.status === "running" && !sessionActive ? { ...run, status: "stopped" as const } : run, + ) .toSorted((a, b) => a.createdAt.localeCompare(b.createdAt) || a.taskId.localeCompare(b.taskId)); } diff --git a/packages/contracts/src/workflow.ts b/packages/contracts/src/workflow.ts index 470b920d9c..07bdd89545 100644 --- a/packages/contracts/src/workflow.ts +++ b/packages/contracts/src/workflow.ts @@ -96,7 +96,6 @@ export class WorkflowInspectionError extends Schema.TaggedErrorClass