Address review findings from multi-agent review pass

- WorkflowInspectionService: re-contain joined leaf files so a symlink
  named journal.jsonl / agent-<id>.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 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-02 04:57:52 -07:00
1 parent ad171b3f42
commit e5b721efc6
11 files changed
+132 -50

No files matched your search

@@ -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* (
@@ -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 =
@@ -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",
@@ -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(
@@ -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;
@@ -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-<id>.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,
}),
),
);
+9 -1
View File
@@ -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(
@@ -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
);
}
@@ -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<ReturnType<typeof setTimeout> | 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 (
<Button type="button" size="xs" variant="outline" onClick={handleCopy}>
{copied ? <CheckIcon /> : <CopyIcon />}
{isCopied ? <CheckIcon /> : <CopyIcon />}
Copy resume command
</Button>
);
@@ -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;
+17
View File
@@ -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<OrchestrationThreadActivity>,
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));
}
-1
View File
@@ -96,7 +96,6 @@ export class WorkflowInspectionError extends Schema.TaggedErrorClass<WorkflowIns
operation: Schema.String,
reason: Schema.Literals(["invalid-path", "not-found", "read-failed", "unsupported"]),
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {