Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 0bb0f53822 Format Windows process diagnostics parser
Co-authored-by: Julius Marminge <[email protected]>
2026-06-29 16:13:09 +00:00
Cursor AgentandJulius Marminge f3da91a0d7 Use Effect Schema for Windows process diagnostics
Co-authored-by: Julius Marminge <[email protected]>
2026-06-29 16:07:02 +00:00
53 changed files with 484 additions and 6013 deletions

No files matched your search

-56
View File
@@ -229,70 +229,14 @@ function resolvePendingUserInputAnswer(
return normalizeDraftAnswer(draft?.selectedOptionLabel);
}
/**
* Task ids owned by a workflow run. Mirrors the desktop derivation in
* apps/web/src/workflow-logic.ts (collectWorkflowTaskIds) — mobile has no
* workflow card yet, so all rows for those tasks are suppressed rather than
* rendered as per-tick noise.
*/
function collectWorkflowTaskIds(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): Set<string> {
const taskIds = new Set<string>();
for (const activity of activities) {
const payload = activity.payload as Record<string, unknown> | null | undefined;
const taskId =
payload && typeof payload === "object" && typeof payload["taskId"] === "string"
? payload["taskId"]
: undefined;
if (!taskId) continue;
const workflowName =
payload && typeof payload === "object" ? payload["workflowName"] : undefined;
const taskType = payload && typeof payload === "object" ? payload["taskType"] : undefined;
if (
activity.kind === "task.workflow-updated" ||
activity.kind === "task.workflow-meta" ||
(activity.kind === "task.started" &&
(taskType === "local_workflow" || typeof workflowName === "string"))
) {
taskIds.add(taskId);
}
}
return taskIds;
}
function activityBelongsToWorkflow(
activity: OrchestrationThreadActivity,
workflowTaskIds: ReadonlySet<string>,
): boolean {
const payload = activity.payload as Record<string, unknown> | null | undefined;
const taskId = payload && typeof payload === "object" ? payload["taskId"] : undefined;
return typeof taskId === "string" && workflowTaskIds.has(taskId);
}
function deriveWorkLogEntries(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): DerivedWorkLogEntry[] {
const ordered = Arr.sort(activities, activityOrder);
const workflowTaskIds = collectWorkflowTaskIds(activities);
const entries: DerivedWorkLogEntry[] = [];
for (const activity of ordered) {
if (activity.kind === "tool.started") continue;
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 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" &&
workflowTaskIds.size > 0 &&
activityBelongsToWorkflow(activity, workflowTaskIds)
) {
continue;
}
if (activity.kind === "context-window.updated") continue;
if (activity.summary === "Checkpoint captured") continue;
if (isPlanBoundaryToolActivity(activity)) continue;
@@ -1,4 +1,4 @@
import { describe, expect, it } from "@effect/vitest";
import { assert, describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -67,6 +67,98 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("parses Windows CIM JSON process rows", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(`[
{
"ProcessId": 10,
"ParentProcessId": 1,
"Name": "node.exe",
"CommandLine": "node server.js",
"Status": "Running",
"WorkingSetSize": 4096,
"PercentProcessorTime": 12.5
},
{
"ProcessId": "invalid",
"ParentProcessId": 10,
"Name": "ignored.exe"
},
{
"ProcessId": 11,
"ParentProcessId": 10,
"Name": "agent.exe",
"CommandLine": null,
"Status": null,
"WorkingSetSize": -128,
"PercentProcessorTime": -1
}
]`);
assert.deepStrictEqual(rows, [
{
pid: 10,
ppid: 1,
pgid: null,
status: "Running",
cpuPercent: 12.5,
rssBytes: 4096,
elapsed: "",
command: "node server.js",
},
{
pid: 11,
ppid: 10,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "agent.exe",
},
]);
}),
);
it.effect("parses single Windows CIM JSON process objects", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(`{
"ProcessId": 42,
"ParentProcessId": 10,
"Name": "agent.exe",
"CommandLine": "",
"WorkingSetSize": 2048,
"PercentProcessorTime": 5
}`);
assert.deepStrictEqual(rows, [
{
pid: 42,
ppid: 10,
pgid: null,
status: "Live",
cpuPercent: 5,
rssBytes: 2048,
elapsed: "",
command: "agent.exe",
},
]);
}),
);
it.effect("ignores malformed Windows CIM JSON output", () =>
Effect.sync(() => {
assert.deepStrictEqual(ProcessDiagnostics.parseWindowsProcessRows("{not json"), []);
assert.deepStrictEqual(
ProcessDiagnostics.parseWindowsProcessRows(`{
"ProcessId": 42,
"Name": "missing-parent.exe"
}`),
[],
);
}),
);
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
@@ -28,7 +28,7 @@ export interface ProcessRow {
readonly command: string;
}
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const PROCESS_QUERY_TIMEOUT = Duration.seconds(1);
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
@@ -121,6 +121,19 @@ const ProcessDiagnosticsError = Schema.Union([
type ProcessDiagnosticsError = typeof ProcessDiagnosticsError.Type;
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
const WindowsCimProcessRecord = Schema.Struct({
ProcessId: Schema.Number,
ParentProcessId: Schema.Number,
Name: Schema.optional(Schema.NullOr(Schema.String)),
CommandLine: Schema.optional(Schema.NullOr(Schema.String)),
Status: Schema.optional(Schema.NullOr(Schema.String)),
WorkingSetSize: Schema.optional(Schema.Number),
PercentProcessorTime: Schema.optional(Schema.Number),
});
type WindowsCimProcessRecord = typeof WindowsCimProcessRecord.Type;
const decodeWindowsProcessJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));
const decodeWindowsProcessRecord = Schema.decodeUnknownOption(WindowsCimProcessRecord);
function parsePositiveInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
@@ -201,51 +214,54 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
const commandLine =
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
? record.CommandLine
: typeof record.Name === "string"
? record.Name
: null;
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
pid,
ppid,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
function nonEmptyStringOption(value: string | null | undefined): Option.Option<string> {
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
function normalizeWindowsProcessRow(value: unknown): Option.Option<ProcessRow> {
return Option.flatMap(decodeWindowsProcessRecord(value), (record: WindowsCimProcessRecord) => {
const pid = record.ProcessId;
const ppid = record.ParentProcessId;
if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(ppid) || ppid < 0) {
return Option.none();
}
const commandLine = nonEmptyStringOption(record.CommandLine).pipe(
Option.orElse(() => nonEmptyStringOption(record.Name)),
);
return Option.map(commandLine, (command) => ({
pid,
ppid,
pgid: null,
status: Option.getOrElse(nonEmptyStringOption(record.Status), () => "Live"),
cpuPercent:
typeof record.PercentProcessorTime === "number" &&
Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0,
rssBytes:
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0,
elapsed: "",
command,
}));
});
}
export function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
const parsed = decodeWindowsProcessJson(output);
if (Option.isNone(parsed)) {
return [];
}
const records = Array.isArray(parsed.value) ? parsed.value : [parsed.value];
return records.flatMap((record) =>
Option.match(normalizeWindowsProcessRow(record), {
onNone: () => [],
onSome: (row) => [row],
}),
);
}
export function buildDescendantEntries(
@@ -381,7 +397,7 @@ const runProcess = Effect.fn("runProcess")(function* (input: {
} satisfies ProcessOutput;
}).pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
Effect.timeoutOption(PROCESS_QUERY_TIMEOUT),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
@@ -390,7 +406,7 @@ const runProcess = Effect.fn("runProcess")(function* (input: {
command: input.command,
argCount: input.args.length,
cwd,
timeoutMillis: PROCESS_QUERY_TIMEOUT_MS,
timeoutMillis: Duration.toMillis(PROCESS_QUERY_TIMEOUT),
}),
),
onSome: Effect.succeed,
@@ -106,7 +106,6 @@ function createProviderServiceHarness(
startSession: () => unsupported(),
sendTurn: () => unsupported(),
interruptTurn: () => unsupported(),
stopTask: () => unsupported(),
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession: () => unsupported(),
@@ -239,7 +239,6 @@ describe("ProviderCommandReactor", () => {
}
}),
);
const stopTask = vi.fn<ProviderServiceShape["stopTask"]>(() => Effect.void);
const renameBranch = vi.fn((input: unknown) =>
Effect.succeed({
branch:
@@ -302,7 +301,6 @@ describe("ProviderCommandReactor", () => {
respondToRequest: respondToRequest as ProviderServiceShape["respondToRequest"],
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
stopSession: stopSession as ProviderServiceShape["stopSession"],
stopTask: stopTask as ProviderServiceShape["stopTask"],
listSessions: () => Effect.succeed(runtimeSessions),
getCapabilities: (_provider) =>
Effect.succeed({
@@ -419,7 +417,6 @@ describe("ProviderCommandReactor", () => {
respondToRequest,
respondToUserInput,
stopSession,
stopTask,
renameBranch,
refreshStatus,
generateBranchName,
@@ -2097,80 +2094,4 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
expect(thread?.session?.activeTurnId).toBeNull();
});
effectIt.effect(
"reacts to thread.task.stop by stopping the background task on the active session",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const now = "2026-01-01T00:00:00.000Z";
yield* harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-for-task-stop"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "running",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: asTurnId("turn-1"),
lastError: null,
updatedAt: now,
},
createdAt: now,
});
yield* harness.engine.dispatch({
type: "thread.task.stop",
commandId: CommandId.make("cmd-task-stop"),
threadId: ThreadId.make("thread-1"),
taskId: "task-9",
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.stopTask.mock.calls.length === 1));
expect(harness.stopTask.mock.calls[0]?.[0]).toEqual({
threadId: "thread-1",
taskId: "task-9",
});
}),
);
effectIt.effect("appends a task-stop failure activity when no active session is bound", () =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const now = "2026-01-01T00:00:00.000Z";
yield* harness.engine.dispatch({
type: "thread.task.stop",
commandId: CommandId.make("cmd-task-stop-no-session"),
threadId: ThreadId.make("thread-1"),
taskId: "task-9",
createdAt: now,
});
yield* Effect.promise(() =>
waitFor(async () => {
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.task.stop.failed") ??
false
);
}),
);
expect(harness.stopTask).not.toHaveBeenCalled();
const readModel = yield* Effect.promise(() => harness.readModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.task.stop.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("No active provider session"),
},
});
}),
);
});
@@ -53,8 +53,7 @@ type ProviderIntentEvent = Extract<
| "thread.turn-interrupt-requested"
| "thread.approval-response-requested"
| "thread.user-input-response-requested"
| "thread.session-stop-requested"
| "thread.task-stop-requested";
| "thread.session-stop-requested";
}
>;
@@ -220,7 +219,6 @@ const make = Effect.gen(function* () {
readonly kind:
| "provider.turn.start.failed"
| "provider.turn.interrupt.failed"
| "provider.task.stop.failed"
| "provider.approval.respond.failed"
| "provider.user-input.respond.failed"
| "provider.session.stop.failed";
@@ -1004,44 +1002,6 @@ const make = Effect.gen(function* () {
});
});
const processTaskStopRequested = Effect.fn("processTaskStopRequested")(function* (
event: Extract<ProviderIntentEvent, { type: "thread.task-stop-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread) {
return;
}
const hasSession = thread.session && thread.session.status !== "stopped";
if (!hasSession) {
return yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.task.stop.failed",
summary: "Background task stop failed",
detail: "No active provider session is bound to this thread.",
turnId: null,
createdAt: event.payload.createdAt,
});
}
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* (
event: ProviderIntentEvent,
) {
@@ -1082,9 +1042,6 @@ const make = Effect.gen(function* () {
case "thread.session-stop-requested":
yield* processSessionStopRequested(event);
return;
case "thread.task-stop-requested":
yield* processTaskStopRequested(event);
return;
}
});
@@ -1111,8 +1068,7 @@ const make = Effect.gen(function* () {
event.type === "thread.turn-interrupt-requested" ||
event.type === "thread.approval-response-requested" ||
event.type === "thread.user-input-response-requested" ||
event.type === "thread.session-stop-requested" ||
event.type === "thread.task-stop-requested"
event.type === "thread.session-stop-requested"
) {
return yield* worker.enqueue(event);
}
@@ -101,7 +101,6 @@ function createProviderServiceHarness() {
startSession: () => unsupported(),
sendTurn: () => unsupported(),
interruptTurn: () => unsupported(),
stopTask: () => unsupported(),
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession: () => unsupported(),
@@ -3061,191 +3060,4 @@ describe("ProviderRuntimeIngestion", () => {
expect(thread.session?.status).toBe("error");
expect(thread.session?.lastError).toBe("runtime still processed");
});
it("projects a plain task.progress (no workflowProgress) into a single activity", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
harness.emit({
type: "task.progress",
eventId: asEventId("evt-plain-progress"),
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plain-progress"),
payload: {
taskId: "task-plain-1",
description: "thinking through the patch",
summary: "thinking through the patch",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-plain-progress",
),
);
const progress = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-plain-progress",
);
expect(progress?.kind).toBe("task.progress");
expect(
thread.activities.filter((activity: ProviderRuntimeTestActivity) =>
activity.id.startsWith("workflow:"),
),
).toHaveLength(0);
});
it("projects a workflow task.progress into a per-tick row plus a stable workflow snapshot", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
const workflowProgress = [
{ type: "workflow_phase", index: 0, title: "Plan" },
{ type: "workflow_agent", index: 0, state: "start", phaseIndex: 0 },
{ type: "workflow_log", message: "kicked off" },
];
harness.emit({
type: "task.progress",
eventId: asEventId("evt-workflow-progress"),
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-workflow-progress"),
payload: {
taskId: "task-wf-1",
description: "spec workflow",
workflowProgress,
usage: { total_tokens: 100 },
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) =>
activity.id === `workflow:${JSON.stringify(["thread-1", "task-wf-1"])}`,
),
);
const perTick = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-workflow-progress",
);
expect(perTick?.kind).toBe("task.progress");
const snapshot = thread.activities.find(
(activity: ProviderRuntimeTestActivity) =>
activity.id === `workflow:${JSON.stringify(["thread-1", "task-wf-1"])}`,
);
expect(snapshot?.kind).toBe("task.workflow-updated");
const payload =
snapshot?.payload && typeof snapshot.payload === "object"
? (snapshot.payload as Record<string, unknown>)
: undefined;
expect(payload?.taskId).toBe("task-wf-1");
expect(payload?.workflowProgress).toEqual(workflowProgress);
});
it("projects task.workflowMeta into a stable workflow-meta activity", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
harness.emit({
type: "task.workflowMeta",
eventId: asEventId("evt-workflow-meta"),
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-workflow-meta"),
payload: {
taskId: "task-wf-meta",
runId: "wf_abc",
workflowName: "spec",
scriptPath: "/x/s.js",
transcriptDir: "/x/t",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) =>
activity.id === `workflow-meta:${JSON.stringify(["thread-1", "task-wf-meta"])}`,
),
);
const meta = thread.activities.find(
(activity: ProviderRuntimeTestActivity) =>
activity.id === `workflow-meta:${JSON.stringify(["thread-1", "task-wf-meta"])}`,
);
expect(meta?.kind).toBe("task.workflow-meta");
const payload =
meta?.payload && typeof meta.payload === "object"
? (meta.payload as Record<string, unknown>)
: undefined;
expect(payload).toMatchObject({
taskId: "task-wf-meta",
runId: "wf_abc",
workflowName: "spec",
scriptPath: "/x/s.js",
transcriptDir: "/x/t",
});
});
it("upserts successive workflow snapshots under the same stable activity id", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
harness.emit({
type: "task.progress",
eventId: asEventId("evt-workflow-progress-1"),
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-workflow-upsert"),
payload: {
taskId: "task-wf-2",
description: "spec workflow",
workflowProgress: [{ type: "workflow_agent", index: 0, state: "start" }],
},
});
harness.emit({
type: "task.progress",
eventId: asEventId("evt-workflow-progress-2"),
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-workflow-upsert"),
payload: {
taskId: "task-wf-2",
description: "spec workflow",
workflowProgress: [{ type: "workflow_agent", index: 0, state: "done" }],
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-workflow-progress-2",
),
);
await harness.drain();
const drained = await harness.readModel();
const drainedThread = drained.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const snapshots = drainedThread?.activities.filter(
(activity: ProviderRuntimeTestActivity) =>
activity.id === `workflow:${JSON.stringify(["thread-1", "task-wf-2"])}`,
);
expect(snapshots).toHaveLength(1);
const payload =
snapshots?.[0]?.payload && typeof snapshots[0].payload === "object"
? (snapshots[0].payload as Record<string, unknown>)
: undefined;
expect(payload?.workflowProgress).toEqual([
{ type: "workflow_agent", index: 0, state: "done" },
]);
// Per-tick rows remain distinct (one per progress event).
expect(
thread.activities.filter(
(activity: ProviderRuntimeTestActivity) => activity.kind === "task.progress",
).length,
).toBeGreaterThanOrEqual(2);
});
});
@@ -8,7 +8,6 @@ import {
type OrchestrationProposedPlanId,
CheckpointRef,
isToolLifecycleItemType,
EventId,
ThreadId,
type ThreadTokenUsageSnapshot,
TurnId,
@@ -163,20 +162,6 @@ function maxCheckpointTurnCount(
return maxTurnCount;
}
/**
* 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:${JSON.stringify([threadId, taskId])}`);
}
function workflowMetaActivityId(threadId: ThreadId, taskId: string): EventId {
return EventId.make(`workflow-meta:${JSON.stringify([threadId, taskId])}`);
}
function truncateDetail(value: string, limit = 180): string {
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
}
@@ -471,8 +456,6 @@ function runtimeEventToActivities(
payload: {
taskId: event.payload.taskId,
...(event.payload.taskType ? { taskType: event.payload.taskType } : {}),
...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),
...(event.payload.workflowName ? { workflowName: event.payload.workflowName } : {}),
...(event.payload.description
? { detail: truncateDetail(event.payload.description) }
: {}),
@@ -484,40 +467,18 @@ function runtimeEventToActivities(
}
case "task.progress": {
const progressActivity: OrchestrationThreadActivity = {
id: event.eventId,
createdAt: event.createdAt,
tone: "info",
kind: "task.progress",
summary: "Reasoning update",
payload: {
taskId: event.payload.taskId,
detail: truncateDetail(event.payload.summary ?? event.payload.description),
...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),
...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
};
if (event.payload.workflowProgress === undefined) {
return [progressActivity];
}
// Workflow snapshots are cumulative state, not timeline entries: reuse a
// stable activity id per task so the projection and client upsert one
// row per run instead of accumulating one per progress tick.
return [
progressActivity,
{
id: workflowActivityId(event.threadId, event.payload.taskId),
id: event.eventId,
createdAt: event.createdAt,
tone: "info",
kind: "task.workflow-updated",
summary: truncateDetail(event.payload.description),
kind: "task.progress",
summary: "Reasoning update",
payload: {
taskId: event.payload.taskId,
description: truncateDetail(event.payload.description),
workflowProgress: event.payload.workflowProgress,
detail: truncateDetail(event.payload.summary ?? event.payload.description),
...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),
...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
@@ -526,23 +487,6 @@ function runtimeEventToActivities(
];
}
case "task.workflowMeta": {
return [
{
id: workflowMetaActivityId(event.threadId, event.payload.taskId),
createdAt: event.createdAt,
tone: "info",
kind: "task.workflow-meta",
summary: event.payload.workflowName
? `Workflow "${event.payload.workflowName}" launched`
: "Workflow launched",
payload: { ...event.payload },
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "task.completed": {
return [
{
-22
View File
@@ -483,28 +483,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.task.stop": {
yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.task-stop-requested",
payload: {
threadId: command.threadId,
taskId: command.taskId,
createdAt: command.createdAt,
},
};
}
case "thread.approval.respond": {
yield* requireThread({
readModel,
@@ -1,121 +0,0 @@
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
ProjectId,
ThreadId,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
const asCommandId = (value: string): CommandId => CommandId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
const now = "2026-01-01T00:00:00.000Z";
const seedReadModel = Effect.gen(function* () {
const initial = createEmptyReadModel(now);
const withProject = yield* projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
aggregateId: asProjectId("project-workflow"),
type: "project.created",
occurredAt: now,
commandId: asCommandId("cmd-project-create"),
causationEventId: null,
correlationId: asCommandId("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-workflow"),
title: "Project Workflow",
workspaceRoot: "/tmp/project-workflow",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
return yield* projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-workflow"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create"),
metadata: {},
payload: {
threadId: asThreadId("thread-workflow"),
projectId: asProjectId("project-workflow"),
title: "Thread Workflow",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
});
it.layer(NodeServices.layer)("decider thread.task.stop", (it) => {
it.effect("emits a thread.task-stop-requested event carrying the task id", () =>
Effect.gen(function* () {
const readModel = yield* seedReadModel;
const result = yield* decideOrchestrationCommand({
command: {
type: "thread.task.stop",
commandId: asCommandId("cmd-task-stop"),
threadId: asThreadId("thread-workflow"),
taskId: "task-9",
createdAt: now,
},
readModel,
});
const events = Array.isArray(result) ? result : [result];
expect(events).toHaveLength(1);
const event = events[0]!;
expect(event.type).toBe("thread.task-stop-requested");
expect(event.payload).toMatchObject({
threadId: asThreadId("thread-workflow"),
taskId: "task-9",
createdAt: now,
});
}),
);
it.effect("rejects a task stop for a thread that does not exist", () =>
Effect.gen(function* () {
const readModel = yield* seedReadModel;
const error = yield* Effect.flip(
decideOrchestrationCommand({
command: {
type: "thread.task.stop",
commandId: asCommandId("cmd-task-stop-missing"),
threadId: asThreadId("thread-missing"),
taskId: "task-9",
createdAt: now,
},
readModel,
}),
);
expect(error.message).toContain("thread-missing");
expect(error.message).toContain("does not exist");
}),
);
});
@@ -58,7 +58,6 @@ class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
public readonly setModelCalls: Array<string | undefined> = [];
public readonly setPermissionModeCalls: Array<string> = [];
public readonly setMaxThinkingTokensCalls: Array<number | null> = [];
public readonly stopTaskCalls: Array<string> = [];
public closeCalls = 0;
emit(message: SDKMessage): void {
@@ -111,10 +110,6 @@ class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
this.setMaxThinkingTokensCalls.push(maxThinkingTokens);
};
readonly stopTask = async (taskId: string): Promise<void> => {
this.stopTaskCalls.push(taskId);
};
readonly close = (): void => {
this.closeCalls += 1;
this.finish();
@@ -3791,225 +3786,4 @@ describe("ClaudeAdapterLive", () => {
Effect.provide(harness.layer),
);
});
it.effect(
"normalizes workflow_progress on task progress, clipping previews and dropping malformed entries",
() => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.takeUntil(
adapter.streamEvents,
(event) => event.type === "task.progress",
).pipe(Stream.runCollect, Effect.forkChild);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
const longPreview = "x".repeat(300);
harness.query.emit({
type: "system",
subtype: "task_progress",
task_id: "task-wf-1",
description: "spec workflow",
workflow_progress: [
{ type: "workflow_phase", index: 0, title: "Plan" },
{ type: "workflow_agent", index: 0, state: "start", promptPreview: longPreview },
{ type: "workflow_log", message: "kicked off" },
{ type: "workflow_agent", state: "start" }, // missing index -> dropped
{ type: "workflow_mystery", index: 9 }, // unknown type -> dropped
],
session_id: "sdk-session-workflow-progress",
uuid: "task-workflow-progress-1",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const progress = runtimeEvents.find((event) => event.type === "task.progress");
assert.equal(progress?.type, "task.progress");
if (progress?.type === "task.progress") {
const workflowProgress = progress.payload.workflowProgress;
// Only the three well-formed entries survive; order is phases, agents, logs.
assert.equal(workflowProgress?.length, 3);
assert.equal(workflowProgress?.[0]?.type, "workflow_phase");
assert.equal(workflowProgress?.[1]?.type, "workflow_agent");
assert.equal(workflowProgress?.[2]?.type, "workflow_log");
const agent = workflowProgress?.[1];
if (agent?.type === "workflow_agent") {
// 240-char clip + a trailing ellipsis.
assert.equal(agent.promptPreview?.length, 241);
assert.equal(agent.promptPreview?.endsWith("…"), true);
}
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
},
);
it.effect("forwards workflow tool_use_id and workflow_name on task started", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.takeUntil(
adapter.streamEvents,
(event) => event.type === "task.started",
).pipe(Stream.runCollect, Effect.forkChild);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
harness.query.emit({
type: "system",
subtype: "task_started",
task_id: "task-wf-1",
description: "spec workflow",
task_type: "local_workflow",
tool_use_id: "tool-wf-1",
workflow_name: "spec",
session_id: "sdk-session-workflow-started",
uuid: "task-workflow-started-1",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const started = runtimeEvents.find((event) => event.type === "task.started");
assert.equal(started?.type, "task.started");
if (started?.type === "task.started") {
assert.equal(started.payload.toolUseId, "tool-wf-1");
assert.equal(started.payload.workflowName, "spec");
assert.equal(started.payload.taskType, "local_workflow");
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("emits task.workflowMeta from a Workflow tool result", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.takeUntil(
adapter.streamEvents,
(event) => event.type === "task.workflowMeta",
).pipe(Stream.runCollect, Effect.forkChild);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "run the workflow",
attachments: [],
});
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-workflow-tool",
uuid: "stream-workflow-start",
parent_tool_use_id: null,
event: {
type: "content_block_start",
index: 1,
content_block: {
type: "tool_use",
id: "tool-wf-1",
name: "Workflow",
input: {},
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-workflow-tool",
uuid: "stream-workflow-stop",
parent_tool_use_id: null,
event: {
type: "content_block_stop",
index: 1,
},
} as unknown as SDKMessage);
harness.query.emit({
type: "user",
session_id: "sdk-session-workflow-tool",
uuid: "user-workflow-result",
parent_tool_use_id: null,
message: {
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "tool-wf-1",
content: "workflow launched",
},
],
},
tool_use_result: {
taskId: "task-1",
runId: "wf_abc",
workflowName: "spec",
scriptPath: "/x/s.js",
transcriptDir: "/x/t",
taskType: "local_workflow",
},
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const meta = runtimeEvents.find((event) => event.type === "task.workflowMeta");
assert.equal(meta?.type, "task.workflowMeta");
if (meta?.type === "task.workflowMeta") {
assert.deepEqual(meta.payload, {
taskId: "task-1",
runId: "wf_abc",
workflowName: "spec",
taskType: "local_workflow",
scriptPath: "/x/s.js",
transcriptDir: "/x/t",
});
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("forwards stopTask to the Claude query runtime", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.streamEvents.pipe(Stream.runDrain, Effect.forkChild);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
const stopTask = adapter.stopTask;
if (stopTask === undefined) {
throw new Error("Expected the Claude adapter to expose stopTask.");
}
yield* stopTask(THREAD_ID, "task-9");
assert.deepEqual(harness.query.stopTaskCalls, ["task-9"]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
});
@@ -45,11 +45,6 @@ import {
ThreadId,
TurnId,
type UserInputQuestion,
type WorkflowAgentProgressEntry,
type WorkflowLogProgressEntry,
type WorkflowPhaseProgressEntry,
type WorkflowProgressEntry,
type WorkflowRunHandles,
} from "@t3tools/contracts";
import {
applyClaudePromptEffortPrefix,
@@ -209,7 +204,6 @@ interface ClaudeSessionContext {
interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {
readonly interrupt: () => Promise<void>;
readonly stopTask?: (taskId: string) => Promise<void>;
readonly setModel: (model?: string) => Promise<void>;
readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;
readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;
@@ -720,242 +714,6 @@ function readStringArray(value: unknown): Array<string> {
: [];
}
const WORKFLOW_TOOL_NAME = "Workflow";
const MAX_WORKFLOW_AGENT_ENTRIES = 300;
const MAX_WORKFLOW_PHASE_ENTRIES = 50;
const MAX_WORKFLOW_LOG_ENTRIES = 40;
const MAX_WORKFLOW_PREVIEW_CHARS = 240;
const MAX_WORKFLOW_RESULT_PREVIEW_CHARS = 400;
function workflowString(value: unknown): string | undefined {
return typeof value === "string" && value.trim().length > 0 ? value : undefined;
}
function workflowClippedString(value: unknown, limit: number): string | undefined {
const text = workflowString(value);
if (text === undefined) {
return undefined;
}
return text.length > limit ? `${text.slice(0, limit)}\u2026` : text;
}
function workflowFiniteNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function normalizeWorkflowAgentEntry(
entry: Record<string, unknown>,
): WorkflowAgentProgressEntry | undefined {
const index = workflowFiniteNumber(entry.index);
const state = workflowString(entry.state);
if (index === undefined || state === undefined) {
return undefined;
}
const isolation =
entry.isolation === "worktree" || entry.isolation === "remote" ? entry.isolation : undefined;
return {
type: "workflow_agent",
index,
state,
...(workflowString(entry.label) !== undefined ? { label: workflowString(entry.label) } : {}),
...(workflowFiniteNumber(entry.phaseIndex) !== undefined
? { phaseIndex: workflowFiniteNumber(entry.phaseIndex) }
: {}),
...(workflowString(entry.phaseTitle) !== undefined
? { phaseTitle: workflowString(entry.phaseTitle) }
: {}),
...(workflowString(entry.agentId) !== undefined
? { agentId: workflowString(entry.agentId) }
: {}),
...(workflowString(entry.agentType) !== undefined
? { agentType: workflowString(entry.agentType) }
: {}),
...(workflowString(entry.model) !== undefined ? { model: workflowString(entry.model) } : {}),
...(workflowString(entry.fallbackModel) !== undefined
? { fallbackModel: workflowString(entry.fallbackModel) }
: {}),
...(isolation !== undefined ? { isolation } : {}),
...(workflowFiniteNumber(entry.attempt) !== undefined
? { attempt: workflowFiniteNumber(entry.attempt) }
: {}),
...(workflowFiniteNumber(entry.queuedAt) !== undefined
? { queuedAt: workflowFiniteNumber(entry.queuedAt) }
: {}),
...(workflowFiniteNumber(entry.startedAt) !== undefined
? { startedAt: workflowFiniteNumber(entry.startedAt) }
: {}),
...(workflowFiniteNumber(entry.lastProgressAt) !== undefined
? { lastProgressAt: workflowFiniteNumber(entry.lastProgressAt) }
: {}),
...(entry.cached === true ? { cached: true } : {}),
...(workflowString(entry.remoteSessionId) !== undefined
? { remoteSessionId: workflowString(entry.remoteSessionId) }
: {}),
...(workflowString(entry.lastToolName) !== undefined
? { lastToolName: workflowString(entry.lastToolName) }
: {}),
...(workflowClippedString(entry.lastToolSummary, MAX_WORKFLOW_PREVIEW_CHARS) !== undefined
? {
lastToolSummary: workflowClippedString(entry.lastToolSummary, MAX_WORKFLOW_PREVIEW_CHARS),
}
: {}),
...(workflowClippedString(entry.promptPreview, MAX_WORKFLOW_PREVIEW_CHARS) !== undefined
? { promptPreview: workflowClippedString(entry.promptPreview, MAX_WORKFLOW_PREVIEW_CHARS) }
: {}),
...(workflowClippedString(entry.resultPreview, MAX_WORKFLOW_RESULT_PREVIEW_CHARS) !== undefined
? {
resultPreview: workflowClippedString(
entry.resultPreview,
MAX_WORKFLOW_RESULT_PREVIEW_CHARS,
),
}
: {}),
...(workflowClippedString(entry.error, MAX_WORKFLOW_PREVIEW_CHARS) !== undefined
? { error: workflowClippedString(entry.error, MAX_WORKFLOW_PREVIEW_CHARS) }
: {}),
...(workflowFiniteNumber(entry.tokens) !== undefined
? { tokens: workflowFiniteNumber(entry.tokens) }
: {}),
...(workflowFiniteNumber(entry.toolCalls) !== undefined
? { toolCalls: workflowFiniteNumber(entry.toolCalls) }
: {}),
...(workflowFiniteNumber(entry.durationMs) !== undefined
? { durationMs: workflowFiniteNumber(entry.durationMs) }
: {}),
};
}
/**
* Normalize the Claude Agent SDK's `workflow_progress` snapshot.
*
* The field is deliberate wire surface (the CLI's own /workflows view renders
* it) but is absent from the published SDK types, so every read is defensive:
* malformed entries and unknown entry types are dropped, previews are
* clipped, and entry counts are capped before the snapshot enters the
* runtime-event contract.
*/
function normalizeWorkflowProgress(
value: unknown,
): ReadonlyArray<WorkflowProgressEntry> | undefined {
if (!Array.isArray(value) || value.length === 0) {
return undefined;
}
// 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<number, WorkflowAgentProgressEntry>();
const phasesByIndex = new Map<number, WorkflowPhaseProgressEntry>();
const logs: Array<WorkflowLogProgressEntry> = [];
for (const raw of value) {
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
continue;
}
const entry = raw as Record<string, unknown>;
switch (entry.type) {
case "workflow_agent": {
const agent = normalizeWorkflowAgentEntry(entry);
if (
agent &&
(agentsByIndex.has(agent.index) || agentsByIndex.size < MAX_WORKFLOW_AGENT_ENTRIES)
) {
agentsByIndex.set(agent.index, agent);
}
break;
}
case "workflow_phase": {
const index = workflowFiniteNumber(entry.index);
const title = workflowString(entry.title);
if (
index !== undefined &&
title !== undefined &&
(phasesByIndex.has(index) || phasesByIndex.size < MAX_WORKFLOW_PHASE_ENTRIES)
) {
phasesByIndex.set(index, {
type: "workflow_phase",
index,
title,
...(workflowString(entry.kind) !== undefined
? { kind: workflowString(entry.kind) }
: {}),
});
}
break;
}
case "workflow_log": {
const logMessage = workflowClippedString(entry.message, MAX_WORKFLOW_RESULT_PREVIEW_CHARS);
if (logMessage !== undefined) {
logs.push({ type: "workflow_log", message: logMessage });
}
break;
}
default:
break;
}
}
// 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 = [...phasesByIndex.values(), ...agentsByIndex.values(), ...clippedLogs];
return entries.length > 0 ? entries : undefined;
}
function readClaudeWorkflowProgress(
message: SDKMessage,
): ReadonlyArray<WorkflowProgressEntry> | undefined {
// `workflow_progress` is not yet declared on SDKTaskProgressMessage — this
// cast is the single place the undocumented field is read.
const raw = (message as { readonly workflow_progress?: unknown }).workflow_progress;
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<string, unknown>,
): WorkflowRunHandles | undefined {
const taskId = workflowString(toolUseResult.taskId);
if (taskId === undefined) {
return undefined;
}
return {
taskId,
...(workflowString(toolUseResult.runId) !== undefined
? { runId: workflowString(toolUseResult.runId) }
: {}),
...(workflowString(toolUseResult.workflowName) !== undefined
? { workflowName: workflowString(toolUseResult.workflowName) }
: {}),
...(workflowString(toolUseResult.taskType) !== undefined
? { taskType: workflowString(toolUseResult.taskType) }
: {}),
...(workflowString(toolUseResult.scriptPath) !== undefined
? { scriptPath: workflowString(toolUseResult.scriptPath) }
: {}),
...(workflowString(toolUseResult.transcriptDir) !== undefined
? { transcriptDir: workflowString(toolUseResult.transcriptDir) }
: {}),
...(workflowHttpUrl(toolUseResult.sessionUrl) !== undefined
? { sessionUrl: workflowHttpUrl(toolUseResult.sessionUrl) }
: {}),
...(workflowString(toolUseResult.warning) !== undefined
? { warning: workflowString(toolUseResult.warning) }
: {}),
};
}
function readClaudeToolUseResult(message: SDKMessage): Record<string, unknown> | undefined {
if (message.type !== "user") {
return undefined;
@@ -2693,30 +2451,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
}
if (!toolResult.isError && tool.toolName === WORKFLOW_TOOL_NAME && toolUseResult) {
const workflowHandles = normalizeWorkflowRunHandles(toolUseResult);
if (workflowHandles) {
const workflowMetaStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "task.workflowMeta",
eventId: workflowMetaStamp.eventId,
provider: PROVIDER,
createdAt: workflowMetaStamp.createdAt,
threadId: context.session.threadId,
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
payload: workflowHandles,
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
raw: {
source: "claude.sdk.message",
method: "claude/user",
payload: message,
},
});
}
}
context.inFlightTools.delete(index);
}
});
@@ -2939,13 +2673,10 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
taskId: RuntimeTaskId.make(message.task_id),
description: message.description,
...(message.task_type ? { taskType: message.task_type } : {}),
...(message.tool_use_id ? { toolUseId: message.tool_use_id } : {}),
...(message.workflow_name ? { workflowName: message.workflow_name } : {}),
},
});
return;
case "task_progress": {
const workflowProgress = readClaudeWorkflowProgress(message);
case "task_progress":
yield* emitThreadTokenUsage(
context,
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
@@ -2963,18 +2694,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(message.summary ? { summary: message.summary } : {}),
...(message.usage ? { usage: message.usage } : {}),
...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}),
...(workflowProgress !== undefined ? { workflowProgress } : {}),
},
});
return;
}
case "task_updated":
// Task status patches (pause/background/description edits). The
// canonical lifecycle events above already carry everything the
// runtime-event model consumes; swallow these instead of routing
// them to the unknown-subtype warning path, which would fire on
// every workflow status transition.
return;
case "task_notification":
yield* emitThreadTokenUsage(
context,
@@ -4029,24 +3751,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
);
const stopTask: NonNullable<ClaudeAdapterShape["stopTask"]> = Effect.fn("stopTask")(
function* (threadId, taskId) {
const context = yield* requireSession(threadId);
const stop = context.query.stopTask;
if (stop === undefined) {
return yield* toRequestError(
threadId,
"task/stop",
new Error("The Claude SDK runtime for this session does not expose stopTask."),
);
}
yield* Effect.tryPromise({
try: () => stop(taskId),
catch: (cause) => toRequestError(threadId, "task/stop", cause),
});
},
);
const readThread: ClaudeAdapterShape["readThread"] = Effect.fn("readThread")(
function* (threadId) {
const context = yield* requireSession(threadId);
@@ -4150,7 +3854,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
startSession,
sendTurn,
interruptTurn,
stopTask,
readThread,
rollbackThread,
respondToRequest,
@@ -1030,15 +1030,9 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
entry.result.outcome !== null &&
"outcome" in entry.result.outcome &&
entry.result.outcome.outcome === "cancelled";
// Assert each condition against the snapshot its own wait resolved on:
// the two log appends are independent, so a snapshot that satisfies one
// predicate can miss (or tear) the other line under load.
const cancelRequests = yield* waitForJsonLogMatch(
requestLogPath,
(entry) => entry.method === "session/cancel",
);
assert.isTrue(cancelRequests.some((entry) => entry.method === "session/cancel"));
yield* waitForJsonLogMatch(requestLogPath, (entry) => entry.method === "session/cancel");
const requests = yield* waitForJsonLogMatch(requestLogPath, isCancelledApprovalResponse);
assert.isTrue(requests.some((entry) => entry.method === "session/cancel"));
assert.isTrue(requests.some(isCancelledApprovalResponse));
yield* adapter.stopSession(threadId);
@@ -19,7 +19,6 @@ import {
ProviderSendTurnInput,
ProviderSessionStartInput,
ProviderStopSessionInput,
ProviderStopTaskInput,
type ProviderInstanceId,
type ProviderDriverKind,
type ProviderRuntimeEvent,
@@ -755,45 +754,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
},
);
const stopTask: ProviderServiceMethod<"stopTask"> = Effect.fn("stopTask")(function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.stopTask",
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: false,
});
yield* Effect.annotateCurrentSpan({
"provider.operation": "stop-task",
"provider.kind": routed.adapter.provider,
"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(
"ProviderService.stopTask",
`Provider '${routed.adapter.provider}' does not support stopping background tasks.`,
);
}
yield* adapterStopTask(routed.threadId, input.taskId);
yield* analytics.record("provider.task.stopped", {
provider: routed.adapter.provider,
});
});
const respondToRequest: ProviderServiceMethod<"respondToRequest"> = Effect.fn("respondToRequest")(
function* (rawInput) {
const input = yield* decodeInputOrValidationError({
@@ -1115,7 +1075,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
respondToRequest,
respondToUserInput,
stopSession,
stopTask,
listSessions,
getCapabilities,
getInstanceInfo,
@@ -153,7 +153,6 @@ describe("ProviderSessionReaper", () => {
startSession: () => unsupported(),
sendTurn: () => unsupported(),
interruptTurn: () => unsupported(),
stopTask: () => unsupported(),
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession,
@@ -68,13 +68,6 @@ export interface ProviderAdapterShape<TError> {
*/
readonly interruptTurn: (threadId: ThreadId, turnId?: TurnId) => Effect.Effect<void, TError>;
/**
* Stop one background task (e.g. a running workflow) inside an active
* session. Optional: adapters whose provider has no background-task
* runtime omit it, and callers surface an "unsupported" error.
*/
readonly stopTask?: (threadId: ThreadId, taskId: string) => Effect.Effect<void, TError>;
/**
* Respond to an interactive approval request.
*/
@@ -13,7 +13,6 @@
*/
import type {
ProviderInterruptTurnInput,
ProviderStopTaskInput,
ProviderInstanceId,
ProviderRespondToRequestInput,
ProviderRespondToUserInputInput,
@@ -73,11 +72,6 @@ export interface ProviderServiceShape {
input: ProviderRespondToUserInputInput,
) => Effect.Effect<void, ProviderServiceError>;
/**
* Stop one background task inside an active provider session.
*/
readonly stopTask: (input: ProviderStopTaskInput) => Effect.Effect<void, ProviderServiceError>;
/**
* Stop a provider session.
*/
-2
View File
@@ -103,7 +103,6 @@ import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
import * as WorkflowInspection from "./workflow/WorkflowInspectionService.ts";
import * as ReviewService from "./review/ReviewService.ts";
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
@@ -671,7 +670,6 @@ const buildAppUnderTest = (options?: {
registerTerminalProcesses: () => Effect.void,
unregisterTerminal: () => Effect.void,
}),
WorkflowInspection.layer,
),
),
Layer.provide(
+1 -2
View File
@@ -65,7 +65,6 @@ import * as VcsProcess from "./vcs/VcsProcess.ts";
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
import * as WorkflowInspection from "./workflow/WorkflowInspectionService.ts";
import * as ReviewService from "./review/ReviewService.ts";
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
@@ -292,7 +291,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(GitLayerLive),
Layer.provideMerge(VcsLayerLive),
Layer.provideMerge(ProviderRuntimeLayerLive),
Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive, WorkflowInspection.layer)),
Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)),
Layer.provideMerge(PersistenceLayerLive),
Layer.provideMerge(Keybindings.layer),
Layer.provideMerge(ProviderRegistryLive),
@@ -1,349 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off - test builds fixtures via Node fs/path directly.
// @effect-diagnostics preferSchemaOverJson:off - fixtures serialize plain JSON journal records.
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as WorkflowInspectionService from "./WorkflowInspectionService.ts";
interface Layout {
readonly root: string;
readonly transcriptDir: string;
readonly scriptsDir: string;
readonly scriptPath: string;
}
const makeLayout = (fs: FileSystem.FileSystem, root: string) =>
Effect.gen(function* () {
const sessionDir = NodePath.join(root, "proj", "sess");
const transcriptDir = NodePath.join(sessionDir, "subagents", "workflows", "wf_abc");
const scriptsDir = NodePath.join(sessionDir, "workflows", "scripts");
yield* fs.makeDirectory(transcriptDir, { recursive: true });
yield* fs.makeDirectory(scriptsDir, { recursive: true });
return {
root,
transcriptDir,
scriptsDir,
scriptPath: NodePath.join(scriptsDir, "spec.js"),
} satisfies Layout;
});
/** Build a service instance whose projects root is an isolated temp dir. */
const setup = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-workflow-inspection-" });
const layout = yield* makeLayout(fs, root);
const service = yield* WorkflowInspectionService.make({ projectsRoot: root });
return { fs, service, layout };
});
describe("WorkflowInspectionService", () => {
describe("readScript", () => {
it.effect("reads a contained script and reports it untruncated", () =>
Effect.gen(function* () {
const { fs, service, layout } = yield* setup;
yield* fs.writeFileString(layout.scriptPath, "export const run = () => 1;\n");
const result = yield* service.readScript({ scriptPath: layout.scriptPath });
assert.equal(result.source, "export const run = () => 1;\n");
assert.isFalse(result.truncated);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("clips scripts larger than the cap and marks them truncated", () =>
Effect.gen(function* () {
const { fs, service, layout } = yield* setup;
const big = "a".repeat(512 * 1024 + 128);
yield* fs.writeFileString(layout.scriptPath, big);
const result = yield* service.readScript({ scriptPath: layout.scriptPath });
assert.isTrue(result.truncated);
assert.equal(result.source.length, 512 * 1024);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("rejects a relative path as invalid-path", () =>
Effect.gen(function* () {
const { service } = yield* setup;
const error = yield* service
.readScript({ scriptPath: "relative/spec.js" })
.pipe(Effect.flip);
assert.equal(error._tag, "WorkflowInspectionError");
assert.equal(error.reason, "invalid-path");
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("rejects a path outside the projects root as invalid-path", () =>
Effect.gen(function* () {
const { fs, service } = yield* setup;
const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-workflow-outside-" });
const outsideScript = NodePath.join(outside, "escape.js");
yield* fs.writeFileString(outsideScript, "export const x = 1;");
const error = yield* service.readScript({ scriptPath: outsideScript }).pipe(Effect.flip);
assert.equal(error._tag, "WorkflowInspectionError");
assert.equal(error.reason, "invalid-path");
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("rejects a symlink inside the root that escapes it as invalid-path", () =>
Effect.gen(function* () {
const { fs, service, layout } = yield* setup;
const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-workflow-outside-" });
const outsideScript = NodePath.join(outside, "real.js");
yield* fs.writeFileString(outsideScript, "export const x = 1;");
const linkPath = NodePath.join(layout.scriptsDir, "link.js");
yield* Effect.promise(() => NodeFSP.symlink(outsideScript, linkPath));
const error = yield* service.readScript({ scriptPath: linkPath }).pipe(Effect.flip);
assert.equal(error._tag, "WorkflowInspectionError");
assert.equal(error.reason, "invalid-path");
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("rejects a non-script extension as invalid-path", () =>
Effect.gen(function* () {
const { fs, service, layout } = yield* setup;
const badPath = NodePath.join(layout.scriptsDir, "spec.txt");
yield* fs.writeFileString(badPath, "not a script");
const error = yield* service.readScript({ scriptPath: badPath }).pipe(Effect.flip);
assert.equal(error._tag, "WorkflowInspectionError");
assert.equal(error.reason, "invalid-path");
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("reports a missing script as not-found", () =>
Effect.gen(function* () {
const { service, layout } = yield* setup;
const missing = NodePath.join(layout.scriptsDir, "missing.js");
const error = yield* service.readScript({ scriptPath: missing }).pipe(Effect.flip);
assert.equal(error._tag, "WorkflowInspectionError");
assert.equal(error.reason, "not-found");
}).pipe(Effect.provide(NodeServices.layer)),
);
});
describe("readJournal", () => {
it.effect("summarizes started and result records with clipping", () =>
Effect.gen(function* () {
const { fs, service, layout } = yield* setup;
const bigResult = "z".repeat(64 * 1024);
const lines = [
JSON.stringify({ type: "started", key: "k1", agentId: "a1" }),
JSON.stringify({
type: "result",
key: "k1",
agentId: "a1",
result: { ok: true, value: 42 },
}),
JSON.stringify({ type: "started", key: "k2", agentId: "a2" }),
"this-is-not-json{",
JSON.stringify({ type: "result", key: "k3", agentId: "a3", result: bigResult }),
];
yield* fs.writeFileString(
NodePath.join(layout.transcriptDir, "journal.jsonl"),
`${lines.join("\n")}\n`,
);
const result = yield* service.readJournal({ transcriptDir: layout.transcriptDir });
assert.isFalse(result.truncated);
assert.deepEqual(
result.entries.map((entry) => entry.agentId),
["a1", "a2", "a3"],
);
const a1 = result.entries[0];
assert.isTrue(a1?.hasResult);
assert.equal(a1?.resultJson, JSON.stringify({ ok: true, value: 42 }));
assert.isUndefined(a1?.resultTruncated);
const a2 = result.entries[1];
assert.isFalse(a2?.hasResult);
assert.isUndefined(a2?.resultJson);
const a3 = result.entries[2];
assert.isTrue(a3?.hasResult);
assert.isTrue(a3?.resultTruncated);
assert.equal(a3?.resultJson?.length, 32 * 1024);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("reports a missing journal as not-found", () =>
Effect.gen(function* () {
const { service, layout } = yield* setup;
const error = yield* service
.readJournal({ transcriptDir: layout.transcriptDir })
.pipe(Effect.flip);
assert.equal(error._tag, "WorkflowInspectionError");
assert.equal(error.reason, "not-found");
}).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;
const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-workflow-outside-" });
yield* fs.writeFileString(NodePath.join(outside, "journal.jsonl"), "");
const error = yield* service.readJournal({ transcriptDir: outside }).pipe(Effect.flip);
assert.equal(error._tag, "WorkflowInspectionError");
assert.equal(error.reason, "invalid-path");
}).pipe(Effect.provide(NodeServices.layer)),
);
});
describe("readAgentTranscript", () => {
it.effect("reads the full transcript and reports completion", () =>
Effect.gen(function* () {
const { fs, service, layout } = yield* setup;
yield* fs.writeFileString(
NodePath.join(layout.transcriptDir, "agent-a1.jsonl"),
"l0\nl1\nl2\n",
);
const result = yield* service.readAgentTranscript({
transcriptDir: layout.transcriptDir,
agentId: "a1",
});
assert.deepEqual(result.lines, ["l0", "l1", "l2"]);
assert.equal(result.nextLine, 3);
assert.isTrue(result.complete);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("returns the remainder from a mid-file cursor", () =>
Effect.gen(function* () {
const { fs, service, layout } = yield* setup;
yield* fs.writeFileString(
NodePath.join(layout.transcriptDir, "agent-a1.jsonl"),
"l0\nl1\nl2\n",
);
const result = yield* service.readAgentTranscript({
transcriptDir: layout.transcriptDir,
agentId: "a1",
afterLine: 1,
});
assert.deepEqual(result.lines, ["l1", "l2"]);
assert.equal(result.nextLine, 3);
assert.isTrue(result.complete);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("returns empty and complete when the cursor is past end-of-file", () =>
Effect.gen(function* () {
const { fs, service, layout } = yield* setup;
yield* fs.writeFileString(
NodePath.join(layout.transcriptDir, "agent-a1.jsonl"),
"l0\nl1\nl2\n",
);
const result = yield* service.readAgentTranscript({
transcriptDir: layout.transcriptDir,
agentId: "a1",
afterLine: 10,
});
assert.deepEqual(result.lines, []);
assert.equal(result.nextLine, 10);
assert.isTrue(result.complete);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("rejects a traversal agent id as invalid-path", () =>
Effect.gen(function* () {
const { service, layout } = yield* setup;
const error = yield* service
.readAgentTranscript({ transcriptDir: layout.transcriptDir, agentId: "../journal" })
.pipe(Effect.flip);
assert.equal(error._tag, "WorkflowInspectionError");
assert.equal(error.reason, "invalid-path");
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("pages a long transcript at the line cap", () =>
Effect.gen(function* () {
const { fs, service, layout } = yield* setup;
const lines = Array.from({ length: 500 }, (_unused, index) => `line-${index}`);
yield* fs.writeFileString(
NodePath.join(layout.transcriptDir, "agent-a1.jsonl"),
lines.join("\n"),
);
const first = yield* service.readAgentTranscript({
transcriptDir: layout.transcriptDir,
agentId: "a1",
});
assert.equal(first.lines.length, 400);
assert.equal(first.nextLine, 400);
assert.isFalse(first.complete);
const second = yield* service.readAgentTranscript({
transcriptDir: layout.transcriptDir,
agentId: "a1",
afterLine: first.nextLine,
});
assert.equal(second.lines.length, 100);
assert.equal(second.nextLine, 500);
assert.isTrue(second.complete);
assert.equal(second.lines[99], "line-499");
}).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;
const error = yield* service
.readAgentTranscript({ transcriptDir: layout.transcriptDir, agentId: "missing" })
.pipe(Effect.flip);
assert.equal(error._tag, "WorkflowInspectionError");
assert.equal(error.reason, "not-found");
}).pipe(Effect.provide(NodeServices.layer)),
);
});
});
@@ -1,319 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off - realpath containment must use Node's fs/path directly.
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import {
WorkflowInspectionError,
type WorkflowReadAgentTranscriptInput,
type WorkflowReadAgentTranscriptResult,
type WorkflowReadJournalInput,
type WorkflowReadJournalResult,
type WorkflowReadScriptInput,
type WorkflowReadScriptResult,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
/**
* Read-only inspection of Claude Agent SDK workflow-run artifacts on local
* disk. Clients echo server-local paths back over RPC, so every path is
* validated structurally (absolute + realpath-contained inside the projects
* root) before any disk access — the service must never become an
* arbitrary-file-read oracle.
*/
/** `readScript`: clip source text past this many characters. */
const SCRIPT_MAX_CHARS = 512 * 1024;
/** `readJournal`: clip each serialized result past this many characters. */
const JOURNAL_RESULT_MAX_CHARS = 32 * 1024;
/** `readJournal`: cap the number of distinct agents reported. */
const JOURNAL_MAX_ENTRIES = 512;
/** `readAgentTranscript`: cap the number of lines returned per page. */
const TRANSCRIPT_MAX_LINES = 400;
/** `readAgentTranscript`: stop a page once accumulated chars exceed this. */
const TRANSCRIPT_MAX_CHARS = 768 * 1024;
/** Only these agent id shapes are accepted before touching the filesystem. */
const AGENT_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
/** Mutable while parsing the journal; frozen into the readonly contract shape. */
interface MutableJournalEntry {
agentId: string;
hasResult: boolean;
resultJson?: string;
resultTruncated?: boolean;
}
/** Parse one JSONL line defensively; unparseable lines return `undefined`. */
const parseJsonLine = (text: string): unknown => {
try {
return JSON.parse(text) as unknown;
} catch {
return undefined;
}
};
const isEnoent = (cause: unknown): boolean =>
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
(cause as { code?: unknown }).code === "ENOENT";
const isNotFoundPlatformError = (cause: unknown): boolean =>
typeof cause === "object" &&
cause !== null &&
"reason" in cause &&
typeof (cause as { reason?: unknown }).reason === "object" &&
(cause as { reason: { _tag?: unknown } }).reason !== null &&
(cause as { reason: { _tag?: unknown } }).reason._tag === "NotFound";
export class WorkflowInspectionService extends Context.Service<
WorkflowInspectionService,
{
readonly readScript: (
input: WorkflowReadScriptInput,
) => Effect.Effect<WorkflowReadScriptResult, WorkflowInspectionError>;
readonly readJournal: (
input: WorkflowReadJournalInput,
) => Effect.Effect<WorkflowReadJournalResult, WorkflowInspectionError>;
readonly readAgentTranscript: (
input: WorkflowReadAgentTranscriptInput,
) => Effect.Effect<WorkflowReadAgentTranscriptResult, WorkflowInspectionError>;
}
>()("t3/workflow/WorkflowInspectionService") {}
export const make = (options?: { readonly projectsRoot?: string }) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const projectsRoot =
options?.projectsRoot ?? NodePath.join(NodeOS.homedir(), ".claude", "projects");
/**
* Resolve the real path of `target` and prove it is contained within the
* real projects root using a path-segment-safe prefix comparison. ENOENT
* during either realpath maps to `not-found`; escape maps to
* `invalid-path`.
*/
const resolveContained = Effect.fn("WorkflowInspectionService.resolveContained")(function* (
operation: string,
target: string,
) {
if (!NodePath.isAbsolute(target)) {
return yield* new WorkflowInspectionError({
operation,
reason: "invalid-path",
detail: "Path must be absolute.",
});
}
const realRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(projectsRoot),
catch: (cause) =>
new WorkflowInspectionError({
operation,
reason: isEnoent(cause) ? "not-found" : "read-failed",
detail: "Failed to resolve the workflow projects root.",
cause,
}),
});
const realTarget = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target),
catch: (cause) =>
new WorkflowInspectionError({
operation,
reason: isEnoent(cause) ? "not-found" : "read-failed",
detail: "Failed to resolve the requested path.",
cause,
}),
});
if (realTarget !== realRoot && !realTarget.startsWith(realRoot + NodePath.sep)) {
return yield* new WorkflowInspectionError({
operation,
reason: "invalid-path",
detail: "Path escapes the workflow projects root.",
});
}
return realTarget;
});
const readScript = Effect.fn("WorkflowInspectionService.readScript")(function* (
input: WorkflowReadScriptInput,
) {
const operation = "WorkflowInspectionService.readScript";
if (!input.scriptPath.endsWith(".js") && !input.scriptPath.endsWith(".mjs")) {
return yield* new WorkflowInspectionError({
operation,
reason: "invalid-path",
detail: "Script path must end with .js or .mjs.",
});
}
const realPath = yield* resolveContained(operation, input.scriptPath);
const source = yield* fs.readFileString(realPath).pipe(
Effect.mapError(
(cause) =>
new WorkflowInspectionError({
operation,
reason: isNotFoundPlatformError(cause) ? "not-found" : "read-failed",
detail: "Failed to read the workflow script.",
cause,
}),
),
);
const truncated = source.length > SCRIPT_MAX_CHARS;
return {
source: truncated ? source.slice(0, SCRIPT_MAX_CHARS) : source,
truncated,
} satisfies WorkflowReadScriptResult;
});
const readJournal = Effect.fn("WorkflowInspectionService.readJournal")(function* (
input: WorkflowReadJournalInput,
) {
const operation = "WorkflowInspectionService.readJournal";
const realDir = yield* resolveContained(operation, input.transcriptDir);
// 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) =>
new WorkflowInspectionError({
operation,
reason: isNotFoundPlatformError(cause) ? "not-found" : "read-failed",
detail: "Failed to read the workflow journal.",
cause,
}),
),
);
// Preserve first-seen agent order via an insertion-ordered Map.
const entries = new Map<string, MutableJournalEntry>();
let truncated = false;
const ensureEntry = (agentId: string): MutableJournalEntry | undefined => {
const existing = entries.get(agentId);
if (existing !== undefined) return existing;
if (entries.size >= JOURNAL_MAX_ENTRIES) {
truncated = true;
return undefined;
}
const created: MutableJournalEntry = { agentId, hasResult: false };
entries.set(agentId, created);
return created;
};
for (const line of raw.split("\n")) {
const text = line.trim();
if (text.length === 0) continue;
const record = parseJsonLine(text);
if (record === undefined) continue;
if (typeof record !== "object" || record === null) continue;
const parsed = record as {
type?: unknown;
agentId?: unknown;
result?: unknown;
};
if (typeof parsed.agentId !== "string" || parsed.agentId.length === 0) continue;
if (parsed.type === "started") {
ensureEntry(parsed.agentId);
continue;
}
if (parsed.type === "result") {
const entry = ensureEntry(parsed.agentId);
if (entry === undefined) continue;
entry.hasResult = true;
// @effect-diagnostics-next-line preferSchemaOverJson:off - result is arbitrary JSON re-serialized verbatim.
const serialized = JSON.stringify(parsed.result);
if (serialized !== undefined) {
const resultTruncated = serialized.length > JOURNAL_RESULT_MAX_CHARS;
entry.resultJson = resultTruncated
? serialized.slice(0, JOURNAL_RESULT_MAX_CHARS)
: serialized;
if (resultTruncated) entry.resultTruncated = true;
}
}
}
return {
entries: Array.from(entries.values()),
truncated,
} satisfies WorkflowReadJournalResult;
});
const readAgentTranscript = Effect.fn("WorkflowInspectionService.readAgentTranscript")(
function* (input: WorkflowReadAgentTranscriptInput) {
const operation = "WorkflowInspectionService.readAgentTranscript";
if (!AGENT_ID_PATTERN.test(input.agentId)) {
return yield* new WorkflowInspectionError({
operation,
reason: "invalid-path",
detail: "Agent id contains unsupported characters.",
});
}
const realDir = yield* resolveContained(operation, input.transcriptDir);
// 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(
Effect.mapError(
(cause) =>
new WorkflowInspectionError({
operation,
reason: isNotFoundPlatformError(cause) ? "not-found" : "read-failed",
detail: "Failed to read the agent transcript.",
cause,
}),
),
);
const allLines = raw.split("\n");
if (allLines.length > 0 && allLines[allLines.length - 1] === "") {
allLines.pop();
}
const total = allLines.length;
const afterLine = Math.max(0, input.afterLine ?? 0);
const lines: string[] = [];
let accumulated = 0;
for (let index = afterLine; index < total && lines.length < TRANSCRIPT_MAX_LINES; index++) {
const current = allLines[index] ?? "";
lines.push(current);
accumulated += current.length;
if (accumulated > TRANSCRIPT_MAX_CHARS) break;
}
const nextLine = afterLine + lines.length;
return {
lines,
nextLine,
complete: nextLine >= total,
} satisfies WorkflowReadAgentTranscriptResult;
},
);
return WorkflowInspectionService.of({
readScript,
readJournal,
readAgentTranscript,
});
});
export const layer = Layer.effect(WorkflowInspectionService, make());
-19
View File
@@ -89,7 +89,6 @@ import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
import * as WorkflowInspection from "./workflow/WorkflowInspectionService.ts";
import * as ReviewService from "./review/ReviewService.ts";
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
@@ -314,9 +313,6 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[WS_METHODS.gitResolvePullRequest, AuthOrchestrationOperateScope],
[WS_METHODS.gitPreparePullRequestThread, AuthOrchestrationOperateScope],
[WS_METHODS.vcsListRefs, AuthOrchestrationReadScope],
[WS_METHODS.workflowReadScript, AuthOrchestrationReadScope],
[WS_METHODS.workflowReadJournal, AuthOrchestrationReadScope],
[WS_METHODS.workflowReadAgentTranscript, AuthOrchestrationReadScope],
[WS_METHODS.vcsCreateWorktree, AuthOrchestrationOperateScope],
[WS_METHODS.vcsRemoveWorktree, AuthOrchestrationOperateScope],
[WS_METHODS.vcsCreateRef, AuthOrchestrationOperateScope],
@@ -403,7 +399,6 @@ const makeWsRpcLayer = (
const keybindings = yield* Keybindings.Keybindings;
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
const workflowInspection = yield* WorkflowInspection.WorkflowInspectionService;
const review = yield* ReviewService.ReviewService;
const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
@@ -1564,20 +1559,6 @@ const makeWsRpcLayer = (
observeRpcEffect(WS_METHODS.reviewGetDiffPreview, review.getDiffPreview(input), {
"rpc.aggregate": "review",
}),
[WS_METHODS.workflowReadScript]: (input) =>
observeRpcEffect(WS_METHODS.workflowReadScript, workflowInspection.readScript(input), {
"rpc.aggregate": "workflow",
}),
[WS_METHODS.workflowReadJournal]: (input) =>
observeRpcEffect(WS_METHODS.workflowReadJournal, workflowInspection.readJournal(input), {
"rpc.aggregate": "workflow",
}),
[WS_METHODS.workflowReadAgentTranscript]: (input) =>
observeRpcEffect(
WS_METHODS.workflowReadAgentTranscript,
workflowInspection.readAgentTranscript(input),
{ "rpc.aggregate": "workflow" },
),
[WS_METHODS.terminalOpen]: (input) =>
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
"rpc.aggregate": "terminal",
+1 -1
View File
@@ -239,7 +239,7 @@ export const BranchToolbar = memo(function BranchToolbar({
if (!hasActiveThread || !activeProject) return null;
return (
<div className="mx-auto flex w-full max-w-3xl items-center gap-2 px-2.5 pb-3 pt-1 sm:px-3">
<div className="mx-auto flex w-full max-w-208 items-center gap-2 px-2.5 pb-3 pt-1 sm:px-3">
{isMobile ? (
<MobileRunContextSelector
envLocked={envLocked}
+23 -316
View File
@@ -85,7 +85,6 @@ import {
isLatestTurnSettled,
} from "../session-logic";
import { type LegendListRef } from "@legendapp/list/react";
import { getAnchoredTurnMetrics, type TimelineScrollMode } from "./chat/timelineScrollAnchoring";
import {
buildPendingUserInputAnswers,
derivePendingUserInputProgress,
@@ -249,8 +248,6 @@ import {
resolveServerConfigVersionMismatch,
} from "../versionSkew";
import { useAssetUrls } from "../assets/assetUrls";
import { deriveWorkflowRuns } from "../workflow-logic";
import { WorkflowPanel } from "./workflow/WorkflowPanel";
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
@@ -1014,7 +1011,6 @@ function ChatViewContent(props: ChatViewProps) {
reportFailure: false,
});
const startThreadTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
const stopThreadTask = useAtomCommand(threadEnvironment.stopTask, { reportFailure: true });
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, {
reportFailure: false,
});
@@ -1165,7 +1161,6 @@ function ChatViewContent(props: ChatViewProps) {
const updateHeight = () => {
const nextHeight = Math.ceil(composerOverlayElement.getBoundingClientRect().height);
if (nextHeight <= 0) return;
setComposerOverlayHeight((currentHeight) =>
currentHeight === nextHeight ? currentHeight : nextHeight,
);
@@ -1730,44 +1725,6 @@ function ChatViewContent(props: ChatViewProps) {
const phase = derivePhase(activeThread?.session ?? null);
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
// Mirrors derivePhase: interrupted/stopped/error sessions are all
// disconnected, and a workflow cannot still be running under any of them.
const workflowSessionActive = phase !== "disconnected";
const workflowRuns = useMemo(
() => deriveWorkflowRuns(threadActivities, { sessionActive: workflowSessionActive }),
[threadActivities, workflowSessionActive],
);
const activeWorkflowSurface =
activeRightPanelSurface?.kind === "workflow" ? activeRightPanelSurface : null;
const activeWorkflowRun = useMemo(
() =>
activeWorkflowSurface
? (workflowRuns.find((run) => run.taskId === activeWorkflowSurface.taskId) ?? null)
: null,
[activeWorkflowSurface, workflowRuns],
);
const onOpenWorkflowDetails = useCallback(
(taskId: string) => {
if (!activeThreadRef) {
return;
}
useRightPanelStore.getState().openWorkflow(activeThreadRef, taskId);
},
[activeThreadRef],
);
const onStopWorkflowTask = useMemo(() => {
if (!activeThread || activeThread.session?.status === "stopped") {
return null;
}
const threadId = activeThread.id;
const threadEnvironmentId = activeThread.environmentId;
return (taskId: string) => {
void stopThreadTask({
environmentId: threadEnvironmentId,
input: { threadId, taskId },
});
};
}, [activeThread, stopThreadTask]);
const pendingApprovals = useMemo(
() => derivePendingApprovals(threadActivities),
[threadActivities],
@@ -2055,6 +2012,7 @@ function ChatViewContent(props: ChatViewProps) {
: // Spread only fires for the few messages that actually changed;
// unchanged ones early-return their original reference.
// In-place mutation would break React's immutable state contract.
// oxlint-disable-next-line no-map-spread
messages.map((message) => {
if (
message.role !== "user" ||
@@ -2101,13 +2059,8 @@ function ChatViewContent(props: ChatViewProps) {
}, [attachmentPreviewHandoffByMessageId, displayServerMessages, optimisticUserMessages]);
const timelineEntries = useMemo(
() =>
deriveTimelineEntries(
timelineMessages,
activeThread?.proposedPlans ?? [],
workLogEntries,
workflowRuns,
),
[activeThread?.proposedPlans, timelineMessages, workLogEntries, workflowRuns],
deriveTimelineEntries(timelineMessages, activeThread?.proposedPlans ?? [], workLogEntries),
[activeThread?.proposedPlans, timelineMessages, workLogEntries],
);
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
@@ -3195,158 +3148,31 @@ function ChatViewContent(props: ChatViewProps) {
],
);
// Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
// thread switches. LegendList fires scroll events with isAtEnd=false while
// initialScrollAtEnd is settling; hiding is always immediate.
const showScrollDebouncer = useRef(
new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),
);
const timelineScrollModeRef = useRef<TimelineScrollMode>("following-end");
const pendingTimelineAnchorRef = useRef<MessageId | null>(null);
// Scrolling is explicit so streamed timeline updates never take control away
// from the user after the newly sent row has been positioned once.
const scrollToEnd = useCallback((animated = false) => {
void legendListRef.current?.scrollToEnd?.({ animated });
}, []);
const positionedTimelineAnchorRef = useRef<MessageId | null>(null);
const settledTimelineAnchorRef = useRef<MessageId | null>(null);
const activeTimelineAnchorIndexRef = useRef<number | null>(null);
const anchorUserScrollGenerationRef = useRef(0);
const liveFollowUserScrollGenerationRef = useRef<number | null>(0);
const pendingAnchorScrollRestoreRef = useRef<{
readonly messageId: MessageId;
readonly offset: number;
readonly userScrollGeneration: number;
} | null>(null);
const anchorScrollRestoreFrameRef = useRef<number | null>(null);
const cancelTimelineLiveFollowForUserNavigation = useCallback(() => {
anchorUserScrollGenerationRef.current += 1;
timelineScrollModeRef.current = "free-scrolling";
liveFollowUserScrollGenerationRef.current = null;
pendingTimelineAnchorRef.current = null;
positionedTimelineAnchorRef.current = null;
settledTimelineAnchorRef.current = null;
activeTimelineAnchorIndexRef.current = null;
pendingAnchorScrollRestoreRef.current = null;
if (anchorScrollRestoreFrameRef.current !== null) {
cancelAnimationFrame(anchorScrollRestoreFrameRef.current);
anchorScrollRestoreFrameRef.current = null;
}
}, []);
const cancelTimelineLiveFollowForUserNavigationRef = useRef(
cancelTimelineLiveFollowForUserNavigation,
);
useEffect(() => {
cancelTimelineLiveFollowForUserNavigationRef.current =
cancelTimelineLiveFollowForUserNavigation;
}, [cancelTimelineLiveFollowForUserNavigation]);
const getActiveTimelineTurnMetrics = useCallback(
(list?: LegendListRef | null) => {
const resolvedList = list ?? legendListRef.current;
const anchorIndex = activeTimelineAnchorIndexRef.current;
const state = resolvedList?.getState();
if (!resolvedList || !state || anchorIndex === null) {
return null;
}
return getAnchoredTurnMetrics({
state,
anchorIndex,
composerOverlayHeight,
anchorOffset: CHAT_LIST_ANCHOR_OFFSET,
});
},
[composerOverlayHeight],
);
const timelineRealContentOverflowsViewport = useCallback(
(list?: LegendListRef | null) => {
const resolvedList = list ?? legendListRef.current;
const state = resolvedList?.getState();
if (!resolvedList || !state || state.data.length === 0) {
return false;
}
const lastRowIndex = state.data.length - 1;
const lastRowTop = state.positionAtIndex(lastRowIndex);
const lastRowHeight = state.sizeAtIndex(lastRowIndex);
if (
typeof lastRowTop !== "number" ||
typeof lastRowHeight !== "number" ||
!Number.isFinite(lastRowTop) ||
!Number.isFinite(lastRowHeight)
) {
return false;
}
const realContentBottom = lastRowTop + Math.max(1, lastRowHeight);
const visibleScrollLength = Math.max(
0,
(state.scrollLength ?? 0) - composerOverlayHeight - CHAT_LIST_ANCHOR_OFFSET,
);
return realContentBottom > visibleScrollLength;
},
[composerOverlayHeight],
);
// Live-follow stays active after send/thread-open until an actual list scroll
// gesture opts out.
const scrollToEnd = useCallback((animated = false) => {
isAtEndRef.current = true;
timelineScrollModeRef.current = "following-end";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
pendingTimelineAnchorRef.current = null;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
void legendListRef.current?.scrollToEnd?.({ animated });
}, []);
useEffect(() => {
let removeListeners: (() => void) | null = null;
const frame = requestAnimationFrame(() => {
const scrollNode = legendListRef.current?.getScrollableNode();
if (!scrollNode) {
return;
}
const handleManualNavigation = () => {
cancelTimelineLiveFollowForUserNavigationRef.current();
};
scrollNode.addEventListener("wheel", handleManualNavigation, {
passive: true,
});
scrollNode.addEventListener("touchmove", handleManualNavigation, {
passive: true,
});
scrollNode.addEventListener("pointerdown", handleManualNavigation, {
passive: true,
});
removeListeners = () => {
scrollNode.removeEventListener("wheel", handleManualNavigation);
scrollNode.removeEventListener("touchmove", handleManualNavigation);
scrollNode.removeEventListener("pointerdown", handleManualNavigation);
};
});
return () => {
cancelAnimationFrame(frame);
removeListeners?.();
};
}, [activeThread?.id]);
const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => {
if (pendingTimelineAnchorRef.current === messageId) {
pendingTimelineAnchorRef.current = null;
}
activeTimelineAnchorIndexRef.current = anchorIndex;
if (positionedTimelineAnchorRef.current === messageId) {
return;
}
positionedTimelineAnchorRef.current = messageId;
settledTimelineAnchorRef.current = null;
const positionAnchor = (remainingAttempts: number) => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (positionedTimelineAnchorRef.current !== messageId) {
return;
}
const list = legendListRef.current;
if (!list) {
if (remainingAttempts > 0) {
positionAnchor(remainingAttempts - 1);
}
return;
}
const scrollNode = list.getScrollableNode();
@@ -3374,26 +3200,18 @@ function ChatViewContent(props: ChatViewProps) {
viewOffset: CHAT_LIST_ANCHOR_OFFSET,
});
});
};
requestAnimationFrame(() => positionAnchor(12));
});
}, []);
const onTimelineAnchorSizeChanged = useCallback((messageId: MessageId) => {
if (settledTimelineAnchorRef.current !== messageId) {
return;
}
if (liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current) {
return;
}
const scrollOffset = legendListRef.current?.getState().scroll;
if (scrollOffset === undefined) {
return;
}
if (pendingAnchorScrollRestoreRef.current === null) {
pendingAnchorScrollRestoreRef.current = {
messageId,
offset: scrollOffset,
userScrollGeneration: anchorUserScrollGenerationRef.current,
};
pendingAnchorScrollRestoreRef.current = { messageId, offset: scrollOffset };
}
if (anchorScrollRestoreFrameRef.current !== null) {
return;
@@ -3402,121 +3220,32 @@ function ChatViewContent(props: ChatViewProps) {
anchorScrollRestoreFrameRef.current = null;
const pending = pendingAnchorScrollRestoreRef.current;
pendingAnchorScrollRestoreRef.current = null;
if (
pending &&
settledTimelineAnchorRef.current === pending.messageId &&
pending.userScrollGeneration === anchorUserScrollGenerationRef.current
) {
const list = legendListRef.current;
const currentScrollOffset = list?.getState().scroll;
if (
typeof currentScrollOffset === "number" &&
Math.abs(currentScrollOffset - pending.offset) <= 2
) {
void list?.scrollToOffset({ offset: pending.offset, animated: false });
}
if (pending && settledTimelineAnchorRef.current === pending.messageId) {
void legendListRef.current?.scrollToOffset({ offset: pending.offset, animated: false });
}
});
}, []);
// Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
// thread switches. LegendList fires scroll events with isAtEnd=false while
// initialScrollAtEnd is settling; hiding is always immediate.
const showScrollDebouncer = useRef(
new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),
);
const onIsAtEndChange = useCallback((isAtEnd: boolean) => {
if (
!isAtEnd &&
liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current
) {
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
return;
}
if (isAtEndRef.current === isAtEnd) return;
isAtEndRef.current = isAtEnd;
if (isAtEnd) {
timelineScrollModeRef.current = "following-end";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
} else {
timelineScrollModeRef.current = "free-scrolling";
liveFollowUserScrollGenerationRef.current = null;
showScrollDebouncer.current.maybeExecute();
}
}, []);
useEffect(() => {
if (!activeThread?.id) {
return;
}
if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) {
return;
}
let secondFrame: number | null = null;
const frame = requestAnimationFrame(() => {
secondFrame = requestAnimationFrame(() => {
if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) {
return;
}
if (pendingTimelineAnchorRef.current !== null) {
return;
}
if (
positionedTimelineAnchorRef.current !== null &&
settledTimelineAnchorRef.current !== positionedTimelineAnchorRef.current
) {
return;
}
const list = legendListRef.current;
if (!list) {
return;
}
if (timelineScrollModeRef.current === "anchoring-new-turn") {
const metrics = getActiveTimelineTurnMetrics(list);
if (!metrics) {
return;
}
if (metrics.scrollDeltaToRevealEnd <= 1) {
return;
}
const nextOffset = list.getState().scroll + metrics.scrollDeltaToRevealEnd;
void list.scrollToOffset({ offset: nextOffset, animated: false });
return;
}
if (timelineScrollModeRef.current !== "following-end") {
return;
}
if (!timelineRealContentOverflowsViewport(list)) {
return;
}
void list.scrollToEnd?.({ animated: false });
});
});
return () => {
cancelAnimationFrame(frame);
if (secondFrame !== null) {
cancelAnimationFrame(secondFrame);
}
};
}, [
activeThread?.id,
timelineEntries,
getActiveTimelineTurnMetrics,
timelineRealContentOverflowsViewport,
]);
useEffect(() => {
setPullRequestDialogState(null);
isAtEndRef.current = true;
timelineScrollModeRef.current = "following-end";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
pendingTimelineAnchorRef.current = null;
positionedTimelineAnchorRef.current = null;
settledTimelineAnchorRef.current = null;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
if (planSidebarOpenOnNextThreadRef.current) {
@@ -3527,6 +3256,7 @@ function ChatViewContent(props: ChatViewProps) {
}
planSidebarDismissedForTurnRef.current = null;
// activeThreadRef resets transitively with the active thread.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeThread?.id]);
// Auto-open the plan sidebar when plan/todo steps arrive for the current turn.
@@ -4076,10 +3806,6 @@ function ChatViewContent(props: ChatViewProps) {
// anchored end-space target so it lands near the top while the response
// streams into the reserved space below it.
isAtEndRef.current = true;
timelineScrollModeRef.current = "anchoring-new-turn";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
pendingTimelineAnchorRef.current = messageIdForSend;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
setTimelineAnchor({
@@ -4513,10 +4239,6 @@ function ChatViewContent(props: ChatViewProps) {
// Position this sent row once LegendList has measured the anchored tail.
isAtEndRef.current = true;
timelineScrollModeRef.current = "anchoring-new-turn";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
pendingTimelineAnchorRef.current = messageIdForSend;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
setTimelineAnchor({
@@ -5016,16 +4738,6 @@ function ChatViewContent(props: ChatViewProps) {
<Suspense fallback={null}>
<DiffPanel mode="embedded" composerDraftTarget={composerDraftTarget} />
</Suspense>
) : activeRightPanelSurface?.kind === "workflow" ? (
<WorkflowPanel
workflowRun={activeWorkflowRun}
environmentId={environmentId}
onStop={
activeWorkflowRun?.status === "running" && onStopWorkflowTask !== null
? () => onStopWorkflowTask(activeWorkflowRun.taskId)
: undefined
}
/>
) : activeRightPanelSurface?.kind === "plan" ? (
<PlanSidebar
activePlan={activePlan}
@@ -5151,17 +4863,14 @@ function ChatViewContent(props: ChatViewProps) {
timestampFormat={timestampFormat}
workspaceRoot={activeWorkspaceRoot}
skills={activeProviderStatus?.skills ?? EMPTY_PROVIDER_SKILLS}
onOpenWorkflowDetails={onOpenWorkflowDetails}
onStopWorkflowTask={onStopWorkflowTask}
anchorMessageId={timelineAnchorMessageId}
onAnchorReady={onTimelineAnchorReady}
onAnchorSizeChanged={onTimelineAnchorSizeChanged}
contentInsetEndAdjustment={composerOverlayHeight}
onIsAtEndChange={onIsAtEndChange}
onManualNavigation={cancelTimelineLiveFollowForUserNavigation}
/>
{/* scroll to end pill — shown when user has scrolled away from the live edge */}
{/* scroll to bottom pill — shown when user has scrolled away from the bottom */}
{showScrollToBottom && (
<div
className="pointer-events-none absolute left-1/2 z-30 flex -translate-x-1/2 justify-center py-1.5"
@@ -5169,13 +4878,11 @@ function ChatViewContent(props: ChatViewProps) {
>
<button
type="button"
aria-label="Scroll to end"
title="Scroll to end"
onClick={() => scrollToEnd(true)}
className="pointer-events-auto flex items-center gap-1.5 rounded-full border border-border/60 bg-card px-3 py-1 text-muted-foreground text-xs shadow-sm transition-colors hover:border-border hover:text-foreground hover:cursor-pointer"
>
<ChevronDownIcon className="size-3.5" />
Scroll to end
Scroll to bottom
</button>
</div>
)}
@@ -5191,7 +4898,7 @@ function ChatViewContent(props: ChatViewProps) {
aria-hidden="true"
className="chat-composer-horizontal-inset pointer-events-none absolute inset-x-0 top-1.5 bottom-0 z-0 sm:top-2"
>
<div className="relative mx-auto h-full w-full max-w-3xl overflow-clip rounded-t-[20px]">
<div className="relative mx-auto h-full w-full max-w-208 overflow-clip rounded-t-[20px]">
<div className="chat-composer-shared-blur absolute -inset-8" />
</div>
</div>
+1 -14
View File
@@ -1,15 +1,6 @@
import type { ContextMenuItem, PreviewSessionSnapshot } from "@t3tools/contracts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import {
ClipboardList,
FileDiff,
Files,
Globe2,
Network,
Plus,
TerminalSquare,
X,
} from "lucide-react";
import { ClipboardList, FileDiff, Files, Globe2, Plus, TerminalSquare, X } from "lucide-react";
import {
type MouseEvent as ReactMouseEvent,
type ReactElement,
@@ -214,8 +205,6 @@ function surfaceTitle(
);
case "plan":
return "Plan";
case "workflow":
return "Workflow";
case "preview": {
const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser";
@@ -277,8 +266,6 @@ function SurfaceIcon({
return <TerminalSquare className="size-3.5 shrink-0" />;
case "plan":
return <ClipboardList className="size-3.5 shrink-0" />;
case "workflow":
return <Network className="size-3.5 shrink-0" />;
}
}
@@ -2044,7 +2044,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<form
ref={composerFormRef}
onSubmit={submitComposer}
className="mx-auto w-full min-w-0 max-w-3xl"
className="mx-auto w-full min-w-0 max-w-208"
data-chat-composer-form="true"
>
<div
@@ -82,7 +82,7 @@ export function ComposerBannerStack({ className, items }: ComposerBannerStackPro
};
return (
<div className={cn("group/banner-stack mx-auto mb-2 max-w-3xl", className)}>
<div className={cn("group/banner-stack mx-auto mb-2 max-w-208", className)}>
<div
className={cn(
"relative",
@@ -6,64 +6,10 @@ import {
type TimelineEntry,
type WorkLogEntry,
} from "../../session-logic";
import type { WorkflowRun } from "../../workflow-logic";
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts";
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
export const TIMELINE_MINIMAP_ITEM_SPACING = 8;
export const TIMELINE_MINIMAP_MIN_ITEMS = 2;
export const TIMELINE_MINIMAP_MAX_HEIGHT_CSS = "calc(100vh - 18rem)";
export const TIMELINE_CONTENT_MAX_WIDTH = 768;
export const TIMELINE_MINIMAP_PERSISTENT_GUTTER = 48;
export interface TimelineEndState {
readonly isAtEnd?: boolean;
readonly isNearEnd?: boolean;
}
export function resolveTimelineIsAtEnd(state: TimelineEndState | undefined): boolean | undefined {
return state?.isNearEnd ?? state?.isAtEnd;
}
export function resolveTimelineMinimapHeightStyle(itemCount: number): string {
const naturalHeight = Math.max(1, (itemCount - 1) * TIMELINE_MINIMAP_ITEM_SPACING);
return `min(${naturalHeight}px, ${TIMELINE_MINIMAP_MAX_HEIGHT_CSS})`;
}
export function resolveTimelineMinimapTopPercent(index: number, itemCount: number): number {
if (itemCount <= 1) {
return 0;
}
return (Math.max(0, Math.min(index, itemCount - 1)) / (itemCount - 1)) * 100;
}
export function resolveTimelineMinimapIndexFromPointer(input: {
readonly itemCount: number;
readonly railTop: number;
readonly railHeight: number;
readonly pointerY: number;
}): number | null {
if (input.itemCount <= 0 || input.railHeight <= 0) {
return null;
}
if (input.itemCount === 1) {
return 0;
}
const progress = Math.max(0, Math.min(1, (input.pointerY - input.railTop) / input.railHeight));
return Math.max(0, Math.min(input.itemCount - 1, Math.round(progress * (input.itemCount - 1))));
}
export function resolveTimelineMinimapHasPersistentGutter(viewportWidth: number): boolean {
if (!Number.isFinite(viewportWidth) || viewportWidth <= 0) {
return false;
}
const contentWidth = Math.min(viewportWidth, TIMELINE_CONTENT_MAX_WIDTH);
const sideGutter = Math.max(0, (viewportWidth - contentWidth) / 2);
return sideGutter >= TIMELINE_MINIMAP_PERSISTENT_GUTTER;
}
function computeElapsedMs(startIso: string, endIso: string): number | null {
const start = Date.parse(startIso);
@@ -137,12 +83,6 @@ export type MessagesTimelineRow =
createdAt: string;
proposedPlan: ProposedPlan;
}
| {
kind: "workflow";
id: string;
createdAt: string;
workflowRun: WorkflowRun;
}
| { kind: "working"; id: string; createdAt: string | null };
export interface StableMessagesTimelineRowsState {
@@ -495,16 +435,6 @@ export function deriveMessagesTimelineRows(input: {
continue;
}
if (timelineEntry.kind === "workflow") {
nextRows.push({
kind: "workflow",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
workflowRun: timelineEntry.workflowRun,
});
continue;
}
const assistantTurnStillInProgress =
timelineEntry.message.role === "assistant" &&
unsettledTurnId !== null &&
@@ -588,19 +518,6 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
case "proposed-plan":
return a.proposedPlan === (b as typeof a).proposedPlan;
case "workflow": {
const bw = b as typeof a;
// 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.revision === bw.workflowRun.revision
);
}
case "work":
return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
@@ -22,16 +22,7 @@ vi.mock("@legendapp/list/react", async () => {
};
contentInsetEndAdjustment?: number;
className?: string;
maintainScrollAtEnd?:
| boolean
| {
animated?: boolean;
on?: {
dataChange?: boolean;
itemLayout?: boolean;
layout?: boolean;
};
};
maintainScrollAtEnd?: boolean;
maintainVisibleContentPosition?:
| boolean
| {
@@ -54,27 +45,7 @@ vi.mock("@legendapp/list/react", async () => {
data-anchor-on-ready={Boolean(props.anchoredEndSpace?.onReady)}
data-content-inset-end={props.contentInsetEndAdjustment}
data-class-name={props.className}
data-maintain-scroll-at-end={props.maintainScrollAtEnd ? "enabled" : undefined}
data-maintain-scroll-at-end-animated={
typeof props.maintainScrollAtEnd === "object"
? props.maintainScrollAtEnd.animated
: undefined
}
data-maintain-scroll-at-end-data-change={
typeof props.maintainScrollAtEnd === "object"
? props.maintainScrollAtEnd.on?.dataChange
: undefined
}
data-maintain-scroll-at-end-item-layout={
typeof props.maintainScrollAtEnd === "object"
? props.maintainScrollAtEnd.on?.itemLayout
: undefined
}
data-maintain-scroll-at-end-layout={
typeof props.maintainScrollAtEnd === "object"
? props.maintainScrollAtEnd.on?.layout
: undefined
}
data-maintain-scroll-at-end={props.maintainScrollAtEnd}
data-maintain-visible-content-position={
typeof props.maintainVisibleContentPosition === "object"
? "object"
@@ -177,8 +148,6 @@ function buildProps() {
turnDiffSummaryByAssistantMessageId: new Map(),
routeThreadKey: "environment-local:thread-1",
onOpenTurnDiff: () => {},
onOpenWorkflowDetails: () => {},
onStopWorkflowTask: null,
revertTurnCountByUserMessageId: new Map(),
onRevertUserMessage: () => {},
isRevertingCheckpoint: false,
@@ -193,7 +162,6 @@ function buildProps() {
onAnchorSizeChanged: () => {},
contentInsetEndAdjustment: 0,
onIsAtEndChange: () => {},
onManualNavigation: () => {},
};
}
@@ -221,43 +189,6 @@ function buildUserTimelineEntry(text: string) {
}
describe("MessagesTimeline", () => {
it("uses LegendList isNearEnd when deciding whether the live edge is visible", async () => {
const {
resolveTimelineIsAtEnd,
resolveTimelineMinimapHasPersistentGutter,
resolveTimelineMinimapHeightStyle,
resolveTimelineMinimapIndexFromPointer,
resolveTimelineMinimapTopPercent,
} = await import("./MessagesTimeline.logic");
expect(resolveTimelineIsAtEnd({ isNearEnd: true, isAtEnd: false })).toBe(true);
expect(resolveTimelineIsAtEnd({ isNearEnd: false, isAtEnd: true })).toBe(false);
expect(resolveTimelineIsAtEnd({ isAtEnd: true })).toBe(true);
expect(resolveTimelineIsAtEnd(undefined)).toBeUndefined();
expect(resolveTimelineMinimapHeightStyle(5)).toBe("min(32px, calc(100vh - 18rem))");
expect(resolveTimelineMinimapTopPercent(2, 5)).toBe(50);
expect(
resolveTimelineMinimapIndexFromPointer({
itemCount: 101,
railTop: 100,
railHeight: 500,
pointerY: 350,
}),
).toBe(50);
expect(
resolveTimelineMinimapIndexFromPointer({
itemCount: 101,
railTop: 100,
railHeight: 500,
pointerY: 999,
}),
).toBe(100);
expect(resolveTimelineMinimapHasPersistentGutter(832)).toBe(false);
expect(resolveTimelineMinimapHasPersistentGutter(863)).toBe(false);
expect(resolveTimelineMinimapHasPersistentGutter(864)).toBe(true);
});
it("anchors a sent attachment message using its measured height", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const onAnchorReady = vi.fn();
@@ -298,7 +229,7 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain("data-anchor-max-size=");
expect(markup).toContain('data-content-inset-end="144"');
expect(markup).toContain("[overflow-anchor:none]");
expect(markup).not.toContain('data-maintain-scroll-at-end="enabled"');
expect(markup).not.toContain("data-maintain-scroll-at-end=");
expect(markup).toContain('data-maintain-visible-content-position="object"');
expect(markup).toContain('data-maintain-visible-content-position-data="true"');
expect(markup).toContain('data-maintain-visible-content-position-size="false"');
@@ -317,11 +248,6 @@ describe("MessagesTimeline", () => {
);
expect(markup).toContain("Show full message");
expect(markup).toContain('data-maintain-scroll-at-end="enabled"');
expect(markup).toContain('data-maintain-scroll-at-end-animated="false"');
expect(markup).toContain('data-maintain-scroll-at-end-data-change="true"');
expect(markup).toContain('data-maintain-scroll-at-end-item-layout="true"');
expect(markup).toContain('data-maintain-scroll-at-end-layout="true"');
expect(markup).toContain('data-user-message-collapsed="true"');
expect(markup).toContain('data-user-message-fade="true"');
expect(markup).toContain('data-user-message-footer="true"');
+22 -402
View File
@@ -18,7 +18,6 @@ import {
useRef,
useState,
type KeyboardEvent,
type MouseEvent,
type ReactNode,
} from "react";
import { flushSync } from "react-dom";
@@ -70,14 +69,8 @@ import {
deriveMessagesTimelineRows,
normalizeCompactToolLabel,
resolveAssistantMessageCopyState,
resolveTimelineIsAtEnd,
resolveTimelineMinimapHasPersistentGutter,
resolveTimelineMinimapHeightStyle,
resolveTimelineMinimapIndexFromPointer,
resolveTimelineMinimapTopPercent,
type StableMessagesTimelineRowsState,
type MessagesTimelineRow,
TIMELINE_MINIMAP_MIN_ITEMS,
type TimelineLatestTurn,
} from "./MessagesTimeline.logic";
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
@@ -112,7 +105,6 @@ import {
parseReviewCommentMessageSegments,
type ReviewCommentContext,
} from "../../reviewCommentContext";
import { WorkflowRunCard } from "../workflow/WorkflowRunCard";
// ---------------------------------------------------------------------------
// Context — shared state consumed by every row component via Context.
@@ -135,8 +127,6 @@ interface TimelineRowSharedState {
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
onToggleTurnFold: (turnId: TurnId) => void;
onToggleWorkGroup: (groupId: string, anchorElement?: HTMLElement) => void;
onOpenWorkflowDetails: (taskId: string) => void;
onStopWorkflowTask: ((taskId: string) => void) | null;
}
interface TimelineRowActivityState {
@@ -176,14 +166,11 @@ interface MessagesTimelineProps {
timestampFormat: TimestampFormat;
workspaceRoot: string | undefined;
skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
onOpenWorkflowDetails: (taskId: string) => void;
onStopWorkflowTask: ((taskId: string) => void) | null;
anchorMessageId: MessageId | null;
onAnchorReady: (messageId: MessageId, anchorIndex: number) => void;
onAnchorSizeChanged: (messageId: MessageId, size: number) => void;
contentInsetEndAdjustment: number;
onIsAtEndChange: (isAtEnd: boolean) => void;
onManualNavigation: () => void;
}
// ---------------------------------------------------------------------------
@@ -211,18 +198,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({
timestampFormat,
workspaceRoot,
skills = EMPTY_TIMELINE_SKILLS,
onOpenWorkflowDetails,
onStopWorkflowTask,
anchorMessageId,
onAnchorReady,
onAnchorSizeChanged,
contentInsetEndAdjustment,
onIsAtEndChange,
onManualNavigation,
}: MessagesTimelineProps) {
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
const onToggleTurnFold = useCallback((turnId: TurnId) => {
setExpandedTurnIds((existing) => {
@@ -324,11 +307,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
],
);
const rows = useStableRows(rawRows);
const minimapItems = useMemo(() => deriveTimelineMinimapItems(rows), [rows]);
const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(
null,
);
const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);
const handleAnchorReady = useCallback(
(info: { anchorIndex: number | undefined }) => {
if (anchorMessageId !== null && info.anchorIndex !== undefined) {
@@ -356,62 +334,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
const handleScroll = useCallback(() => {
const state = listRef.current?.getState?.();
const isAtEnd = resolveTimelineIsAtEnd(state);
if (isAtEnd !== undefined) {
onIsAtEndChange(isAtEnd);
if (state) {
onIsAtEndChange(state.isAtEnd);
}
if (!state || minimapItems.length === 0) {
return;
}
const scrollTop = state.scroll ?? 0;
const scrollBottom = scrollTop + (state.scrollLength ?? 0);
for (const item of minimapItems) {
const strip = minimapStripMap.get(item.id);
if (!strip) {
continue;
}
const rowTop = resolveTimelineRowTop(state, item.rowIndex);
const rowHeight = resolveTimelineRowHeight(state, item.rowIndex);
const inView =
rowTop !== null &&
rowTop < scrollBottom &&
rowTop + Math.max(1, rowHeight ?? 1) > scrollTop;
strip.dataset.inView = inView ? "true" : "false";
}
}, [listRef, minimapItems, minimapStripMap, onIsAtEndChange]);
useEffect(() => {
const frame = requestAnimationFrame(handleScroll);
return () => cancelAnimationFrame(frame);
}, [handleScroll, rows.length]);
useEffect(() => {
if (!timelineViewportElement) {
return;
}
const measure = () => {
const viewportWidth = timelineViewportElement.getBoundingClientRect().width;
const nextHasPersistentGutter = resolveTimelineMinimapHasPersistentGutter(viewportWidth);
setMinimapHasPersistentGutter((current) =>
current === nextHasPersistentGutter ? current : nextHasPersistentGutter,
);
};
const frame = requestAnimationFrame(measure);
const observer = new ResizeObserver(measure);
observer.observe(timelineViewportElement);
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
};
}, [timelineViewportElement, rows.length]);
}, [listRef, onIsAtEndChange]);
const sharedState = useMemo<TimelineRowSharedState>(
() => ({
@@ -428,8 +354,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onOpenTurnDiff,
onToggleTurnFold,
onToggleWorkGroup,
onOpenWorkflowDetails,
onStopWorkflowTask,
}),
[
timestampFormat,
@@ -444,8 +368,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onOpenTurnDiff,
onToggleTurnFold,
onToggleWorkGroup,
onOpenWorkflowDetails,
onStopWorkflowTask,
],
);
const activityState = useMemo<TimelineRowActivityState>(
@@ -481,53 +403,25 @@ export const MessagesTimeline = memo(function MessagesTimeline({
return (
<TimelineRowCtx value={sharedState}>
<TimelineRowActivityCtx value={activityState}>
<div ref={setTimelineViewportElement} className="relative h-full min-h-0">
<LegendList<MessagesTimelineRow>
ref={listRef}
data={rows}
keyExtractor={keyExtractor}
getItemType={getItemType}
renderItem={renderItem}
estimatedItemSize={90}
initialScrollAtEnd
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={contentInsetEndAdjustment}
maintainScrollAtEnd={
anchoredEndSpace
? false
: {
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
}
}
maintainVisibleContentPosition={{
data: true,
size: false,
}}
onScroll={handleScroll}
className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5"
ListHeaderComponent={TIMELINE_LIST_HEADER}
ListFooterComponent={TIMELINE_LIST_FOOTER}
/>
<TimelineMinimap
items={minimapItems}
bottomInset={contentInsetEndAdjustment}
hasPersistentGutter={minimapHasPersistentGutter}
stripMap={minimapStripMap}
onSelect={(item) => {
onManualNavigation();
void listRef.current?.scrollToIndex({
index: item.rowIndex,
animated: true,
viewOffset: 24,
});
}}
/>
</div>
<LegendList<MessagesTimelineRow>
ref={listRef}
data={rows}
keyExtractor={keyExtractor}
getItemType={getItemType}
renderItem={renderItem}
estimatedItemSize={90}
initialScrollAtEnd
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={contentInsetEndAdjustment}
maintainVisibleContentPosition={{
data: true,
size: false,
}}
onScroll={handleScroll}
className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5"
ListHeaderComponent={TIMELINE_LIST_HEADER}
ListFooterComponent={TIMELINE_LIST_FOOTER}
/>
</TimelineRowActivityCtx>
</TimelineRowCtx>
);
@@ -541,261 +435,6 @@ function getItemType(item: MessagesTimelineRow) {
return item.kind === "message" ? `message:${item.message.role}` : item.kind;
}
interface TimelineMinimapItem {
readonly id: string;
readonly rowIndex: number;
readonly userText: string | null;
readonly assistantText: string | null;
}
interface TimelinePositionState {
readonly contentLength?: number;
readonly scroll?: number;
readonly scrollLength?: number;
readonly positionAtIndex?: (index: number) => number | undefined;
readonly sizeAtIndex?: (index: number) => number | undefined;
}
function deriveTimelineMinimapItems(
rows: ReadonlyArray<MessagesTimelineRow>,
): TimelineMinimapItem[] {
const items: TimelineMinimapItem[] = [];
for (let index = 0; index < rows.length; index += 1) {
const row = rows[index];
if (row?.kind !== "message" || row.message.role !== "user") {
continue;
}
items.push({
id: row.id,
rowIndex: index,
userText: compactMinimapPreview(row.message.text),
assistantText: compactMinimapPreview(resolveFinalAssistantTextForTurn(rows, index)),
});
}
return items;
}
function resolveFinalAssistantTextForTurn(
rows: ReadonlyArray<MessagesTimelineRow>,
userRowIndex: number,
) {
let finalAssistantText: string | null = null;
for (let index = userRowIndex + 1; index < rows.length; index += 1) {
const row = rows[index];
if (row?.kind !== "message") {
continue;
}
if (row.message.role === "user") {
break;
}
if (row.message.role === "assistant") {
finalAssistantText = row.message.text ?? null;
}
}
return finalAssistantText;
}
function compactMinimapPreview(text: string | null | undefined) {
const compact = text?.replace(/\s+/g, " ").trim() ?? "";
return compact.length > 0 ? compact : null;
}
function resolveTimelineRowTop(state: TimelinePositionState, rowIndex: number) {
const top = state.positionAtIndex?.(rowIndex);
return typeof top === "number" && Number.isFinite(top) ? top : null;
}
function resolveTimelineRowHeight(state: TimelinePositionState, rowIndex: number) {
const height = state.sizeAtIndex?.(rowIndex);
return typeof height === "number" && Number.isFinite(height) ? height : null;
}
function TimelineMinimap({
bottomInset,
hasPersistentGutter,
items,
stripMap,
onSelect,
}: {
bottomInset: number;
hasPersistentGutter: boolean;
items: ReadonlyArray<TimelineMinimapItem>;
stripMap: Map<string, HTMLSpanElement>;
onSelect: (item: TimelineMinimapItem) => void;
}) {
const [activeIndex, setActiveIndex] = useState<number | null>(null);
const resolvedActiveIndex =
activeIndex !== null && activeIndex < items.length ? activeIndex : null;
const activeItem = resolvedActiveIndex === null ? null : (items[resolvedActiveIndex] ?? null);
const activeTopPercent =
resolvedActiveIndex === null
? 0
: resolveTimelineMinimapTopPercent(resolvedActiveIndex, items.length);
const activeTooltipTranslate =
resolvedActiveIndex === null
? "-50%"
: resolvedActiveIndex === 0
? "0%"
: resolvedActiveIndex === items.length - 1
? "-100%"
: "-50%";
const resolveActiveIndexFromPointer = useCallback(
(event: MouseEvent<HTMLElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
return resolveTimelineMinimapIndexFromPointer({
itemCount: items.length,
railTop: rect.top,
railHeight: rect.height,
pointerY: event.clientY,
});
},
[items.length],
);
const updateActiveIndexFromPointer = useCallback(
(event: MouseEvent<HTMLElement>) => {
const nextIndex = resolveActiveIndexFromPointer(event);
setActiveIndex(nextIndex);
},
[resolveActiveIndexFromPointer],
);
const moveActiveIndex = useCallback(
(delta: number) => {
setActiveIndex((current) => {
const base = current ?? 0;
return Math.max(0, Math.min(items.length - 1, base + delta));
});
},
[items.length],
);
if (items.length < TIMELINE_MINIMAP_MIN_ITEMS) {
return null;
}
const safeBottomInset = Math.max(0, Math.ceil(bottomInset));
return (
<div
className={cn(
"group/minimap pointer-events-auto absolute top-0 left-0 z-40 hidden w-18 [@media(pointer:fine)]:block",
hasPersistentGutter
? "opacity-100"
: "opacity-0 transition-opacity duration-150 hover:opacity-100 focus-within:opacity-100",
)}
data-testid="timeline-minimap"
data-persistent-gutter={hasPersistentGutter ? "true" : "false"}
style={{ bottom: safeBottomInset }}
>
<div className="relative h-full w-full select-none">
<button
aria-label={`Jump to message: ${activeItem?.userText ?? "User message"}`}
className="pointer-events-auto absolute top-1/2 left-3 w-10 -translate-y-1/2 cursor-pointer bg-transparent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/70"
onBlur={() => setActiveIndex(null)}
onClick={(event) => {
const nextIndex = resolveActiveIndexFromPointer(event);
const nextItem = nextIndex === null ? null : (items[nextIndex] ?? null);
if (nextItem) {
onSelect(nextItem);
}
event.currentTarget.blur();
}}
onFocus={() => setActiveIndex((current) => current ?? 0)}
onKeyDown={(event) => {
if (event.key === "ArrowDown") {
event.preventDefault();
moveActiveIndex(1);
} else if (event.key === "ArrowUp") {
event.preventDefault();
moveActiveIndex(-1);
} else if (event.key === "Home") {
event.preventDefault();
setActiveIndex(0);
} else if (event.key === "End") {
event.preventDefault();
setActiveIndex(items.length - 1);
} else if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
if (activeItem) {
onSelect(activeItem);
}
}
}}
onMouseLeave={() => setActiveIndex(null)}
onMouseMove={updateActiveIndexFromPointer}
onMouseDown={(event) => {
event.preventDefault();
}}
style={{ height: resolveTimelineMinimapHeightStyle(items.length) }}
type="button"
>
<div className="absolute top-0 left-3 h-full w-px bg-border/15" />
{items.map((item, index) => {
const top = `${resolveTimelineMinimapTopPercent(index, items.length)}%`;
const activeDistance =
resolvedActiveIndex === null ? null : Math.abs(index - resolvedActiveIndex);
return (
<span
aria-hidden="true"
className={cn(
"pointer-events-none absolute left-0 h-0.5 -translate-y-1/2 rounded-full bg-muted-foreground/35 transition-[background-color,width] duration-150 data-[in-view=true]:bg-foreground/90",
activeDistance === 0
? "w-6 bg-muted-foreground/75"
: activeDistance === 1
? "w-4"
: activeDistance === 2
? "w-2.5"
: "w-2",
)}
data-in-view="false"
data-minimap-strip
key={item.id}
ref={(node) => {
if (node) {
stripMap.set(item.id, node);
} else {
stripMap.delete(item.id);
}
}}
style={{ top }}
/>
);
})}
{activeItem ? (
<span
className="pointer-events-none absolute left-8 w-80 rounded-xl border border-border/70 bg-popover/95 p-3 text-left text-popover-foreground shadow-xl shadow-black/25 backdrop-blur"
style={{
top: `${activeTopPercent}%`,
transform: `translateY(${activeTooltipTranslate})`,
}}
>
<span className="block max-w-full overflow-hidden text-ellipsis whitespace-nowrap text-sm font-medium leading-5">
{activeItem.userText ?? "User message"}
</span>
{activeItem.assistantText ? (
<span
className="mt-1 max-h-[3.75rem] overflow-hidden text-muted-foreground text-sm leading-5"
style={{
display: "-webkit-box",
WebkitBoxOrient: "vertical",
WebkitLineClamp: 3,
}}
>
{activeItem.assistantText}
</span>
) : null}
</span>
) : null}
</button>
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// TimelineRowContent — the actual row component
// ---------------------------------------------------------------------------
@@ -831,30 +470,11 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
<AssistantTimelineRow row={row} />
) : null}
{row.kind === "proposed-plan" ? <ProposedPlanTimelineRow row={row} /> : null}
{row.kind === "workflow" ? <WorkflowTimelineRow row={row} /> : null}
{row.kind === "working" ? <WorkingTimelineRow row={row} /> : null}
</div>
);
});
function WorkflowTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "workflow" }> }) {
const ctx = use(TimelineRowCtx);
const run = row.workflowRun;
const onOpenDetails = useCallback(() => {
ctx.onOpenWorkflowDetails(run.taskId);
}, [ctx, run.taskId]);
const stopHandler = ctx.onStopWorkflowTask;
const onStop = useMemo(() => {
if (run.status !== "running" || stopHandler === null) {
return undefined;
}
return () => {
stopHandler(run.taskId);
};
}, [run.status, run.taskId, stopHandler]);
return <WorkflowRunCard workflowRun={run} onOpenDetails={onOpenDetails} onStop={onStop} />;
}
function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
const ctx = use(TimelineRowCtx);
const userImages = row.message.attachments ?? [];
@@ -1,138 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { getAnchoredTurnMetrics, getRowBottom } from "./timelineScrollAnchoring";
function buildState({
positions,
sizes,
scroll = 0,
scrollLength = 700,
}: {
readonly positions: readonly number[];
readonly sizes: readonly number[];
readonly scroll?: number;
readonly scrollLength?: number;
}) {
return {
data: positions.map((_, index) => index),
scroll,
scrollLength,
positionAtIndex: (index: number) => positions[index],
sizeAtIndex: (index: number) => sizes[index],
};
}
describe("timeline scroll anchoring", () => {
it("measures row bottoms from LegendList row position and size", () => {
const state = buildState({
positions: [0, 120],
sizes: [80, 40],
});
expect(getRowBottom(state, 1)).toBe(160);
});
it("treats the active turn as fitting when it fits above the composer", () => {
const state = buildState({
positions: [0, 300, 460],
sizes: [240, 80, 140],
scrollLength: 760,
});
const metrics = getAnchoredTurnMetrics({
state,
anchorIndex: 1,
composerOverlayHeight: 180,
anchorOffset: 16,
});
expect(metrics?.turnHeight).toBe(300);
expect(metrics?.usableViewportHeight).toBe(564);
expect(metrics?.overflowsUsableViewport).toBe(false);
expect(metrics?.targetScrollToRevealEnd).toBe(36);
expect(metrics?.scrollDeltaToRevealEnd).toBe(36);
});
it("targets the real row end instead of any temporary reserved tail", () => {
const state = buildState({
positions: [0, 1720, 1880],
sizes: [1600, 80, 120],
scroll: 1900,
scrollLength: 760,
});
const metrics = getAnchoredTurnMetrics({
state,
anchorIndex: 1,
composerOverlayHeight: 180,
anchorOffset: 16,
});
expect(metrics?.lastBottom).toBe(2000);
expect(metrics?.targetScrollToRevealEnd).toBe(1436);
expect(metrics?.scrollDeltaToRevealEnd).toBe(0);
});
it("reports overflow only for the current anchored turn", () => {
const state = buildState({
positions: [0, 900, 1180],
sizes: [800, 220, 300],
scroll: 900,
scrollLength: 760,
});
const metrics = getAnchoredTurnMetrics({
state,
anchorIndex: 1,
composerOverlayHeight: 180,
anchorOffset: 16,
});
expect(metrics?.turnHeight).toBe(580);
expect(metrics?.usableViewportHeight).toBe(564);
expect(metrics?.overflowsUsableViewport).toBe(true);
});
it("returns the minimal positive scroll delta needed to reveal the turn end", () => {
const state = buildState({
positions: [0, 900, 1180],
sizes: [800, 220, 360],
scroll: 900,
scrollLength: 760,
});
const metrics = getAnchoredTurnMetrics({
state,
anchorIndex: 1,
composerOverlayHeight: 180,
anchorOffset: 16,
});
expect(metrics?.lastBottom).toBe(1540);
expect(metrics?.visibleUsableBottom).toBe(1464);
expect(metrics?.scrollDeltaToRevealEnd).toBe(76);
});
it("subtracts composer height from usable viewport height", () => {
const state = buildState({
positions: [0, 300],
sizes: [120, 470],
scrollLength: 700,
});
const withoutComposer = getAnchoredTurnMetrics({
state,
anchorIndex: 1,
composerOverlayHeight: 0,
anchorOffset: 16,
});
const withComposer = getAnchoredTurnMetrics({
state,
anchorIndex: 1,
composerOverlayHeight: 220,
anchorOffset: 16,
});
expect(withoutComposer?.overflowsUsableViewport).toBe(false);
expect(withComposer?.overflowsUsableViewport).toBe(true);
});
});
@@ -1,78 +0,0 @@
export type TimelineScrollMode = "following-end" | "anchoring-new-turn" | "free-scrolling";
export interface TimelineListMeasurementState {
readonly data: readonly unknown[];
readonly scroll: number;
readonly scrollLength: number;
readonly positionAtIndex: (index: number) => number | undefined;
readonly sizeAtIndex: (index: number) => number | undefined;
}
export interface AnchoredTurnMetrics {
readonly anchorTop: number;
readonly lastBottom: number;
readonly turnHeight: number;
readonly usableViewportHeight: number;
readonly visibleUsableBottom: number;
readonly overflowsUsableViewport: boolean;
readonly targetScrollToRevealEnd: number;
readonly scrollDeltaToRevealEnd: number;
}
export function getRowBottom(state: TimelineListMeasurementState, index: number): number | null {
const top = state.positionAtIndex(index);
const height = state.sizeAtIndex(index);
if (
typeof top !== "number" ||
typeof height !== "number" ||
!Number.isFinite(top) ||
!Number.isFinite(height)
) {
return null;
}
return top + Math.max(1, height);
}
export function getAnchoredTurnMetrics({
state,
anchorIndex,
composerOverlayHeight,
anchorOffset,
}: {
readonly state: TimelineListMeasurementState;
readonly anchorIndex: number;
readonly composerOverlayHeight: number;
readonly anchorOffset: number;
}): AnchoredTurnMetrics | null {
if (state.data.length === 0) {
return null;
}
const boundedAnchorIndex = Math.max(0, Math.min(anchorIndex, state.data.length - 1));
const anchorTop = state.positionAtIndex(boundedAnchorIndex);
const lastBottom = getRowBottom(state, state.data.length - 1);
if (typeof anchorTop !== "number" || !Number.isFinite(anchorTop) || lastBottom === null) {
return null;
}
const usableViewportHeight = Math.max(
0,
state.scrollLength - composerOverlayHeight - anchorOffset,
);
const turnHeight = Math.max(0, lastBottom - anchorTop);
const visibleUsableBottom = state.scroll + usableViewportHeight;
const targetScrollToRevealEnd = Math.max(0, lastBottom - usableViewportHeight);
const scrollDeltaToRevealEnd = Math.max(0, targetScrollToRevealEnd - state.scroll);
return {
anchorTop,
lastBottom,
turnHeight,
usableViewportHeight,
visibleUsableBottom,
overflowsUsableViewport: turnHeight > usableViewportHeight,
targetScrollToRevealEnd,
scrollDeltaToRevealEnd,
};
}
@@ -1,753 +0,0 @@
import { DiffsHighlighter, getSharedHighlighter, SupportedLanguages } from "@pierre/diffs";
import type { EnvironmentId } from "@t3tools/contracts";
import { CheckIcon, ChevronRightIcon, CopyIcon, ExternalLinkIcon, NetworkIcon } from "lucide-react";
import {
Component,
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
type ReactElement,
type ReactNode,
Suspense,
use,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { useTheme } from "~/hooks/useTheme";
import { type DiffThemeName, resolveDiffThemeName } from "~/lib/diffRendering";
import { cn } from "~/lib/utils";
import { useEnvironmentQuery } from "~/state/query";
import { useAtomCommand } from "~/state/use-atom-command";
import { workflowEnvironment } from "~/state/workflow";
import {
isRemoteWorkflowRun,
type WorkflowRun,
type WorkflowRunAgent,
type WorkflowRunStatus,
workflowRunTitle,
} from "~/workflow-logic";
import { Button } from "../ui/button";
import {
AgentRowContent,
PhaseHeader,
WorkflowStatusChip,
safeWorkflowSessionUrl,
} from "./workflowUi";
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
type WorkflowTabId = "run" | "script" | "logs";
const WORKFLOW_TABS: ReadonlyArray<{ id: WorkflowTabId; label: string }> = [
{ id: "run", label: "Run" },
{ id: "script", label: "Script" },
{ id: "logs", label: "Logs" },
];
// ---------------------------------------------------------------------------
// Root — handles the not-found empty state, then delegates to the inner panel
// so every data hook runs unconditionally.
// ---------------------------------------------------------------------------
export function WorkflowPanel(props: {
workflowRun: WorkflowRun | null;
environmentId: EnvironmentId;
onStop?: (() => void) | undefined;
}): ReactElement {
if (props.workflowRun === null) {
return (
<div className="flex h-full min-w-0 items-center justify-center p-6 text-muted-foreground text-sm">
Workflow not found
</div>
);
}
return (
<WorkflowPanelInner
run={props.workflowRun}
environmentId={props.environmentId}
onStop={props.onStop}
/>
);
}
function WorkflowPanelInner({
run,
environmentId,
onStop,
}: {
run: WorkflowRun;
environmentId: EnvironmentId;
onStop?: (() => void) | undefined;
}): ReactElement {
const [tab, setTab] = useState<WorkflowTabId>("run");
const { resolvedTheme } = useTheme();
const themeName = resolveDiffThemeName(resolvedTheme);
const scriptPath = run.handles?.scriptPath;
const transcriptDir = run.handles?.transcriptDir;
const remote = isRemoteWorkflowRun(run);
const isTerminal = run.status !== "running";
const scriptQuery = useEnvironmentQuery(
tab === "script" && scriptPath !== undefined
? workflowEnvironment.readScript({ environmentId, input: { scriptPath } })
: null,
);
const journalQuery = useEnvironmentQuery(
tab === "logs" && transcriptDir !== undefined
? workflowEnvironment.readJournal({ environmentId, input: { transcriptDir } })
: null,
);
return (
<div className="flex h-full min-w-0 flex-col">
<div className="flex items-center gap-2 border-border/60 border-b px-3 py-2">
<NetworkIcon className="size-4 shrink-0 text-muted-foreground" />
<span className="truncate font-medium text-foreground text-sm">
{workflowRunTitle(run)}
</span>
<WorkflowStatusChip status={run.status} />
<div className="ml-auto flex items-center gap-1.5">
{isTerminal && run.handles?.runId !== undefined && scriptPath !== undefined && (
<CopyResumeButton scriptPath={scriptPath} runId={run.handles.runId} />
)}
{onStop && (
<Button type="button" size="xs" variant="outline" onClick={onStop}>
Stop
</Button>
)}
</div>
</div>
<div className="flex items-center gap-1 border-border/60 border-b px-2 py-1.5">
{WORKFLOW_TABS.map((entry) => (
<button
key={entry.id}
type="button"
data-active-tab={tab === entry.id}
onClick={() => setTab(entry.id)}
className={cn(
"flex h-7 items-center rounded-md px-2.5 text-sm transition-colors",
tab === entry.id
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
)}
>
{entry.label}
</button>
))}
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-2.5">
{tab === "run" && (
<RunTab
run={run}
environmentId={environmentId}
transcriptDir={transcriptDir}
remote={remote}
/>
)}
{tab === "script" && (
<ScriptTab scriptPath={scriptPath} query={scriptQuery} themeName={themeName} />
)}
{tab === "logs" && (
<LogsTab logs={run.logs} transcriptDir={transcriptDir} query={journalQuery} />
)}
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Header copy button
// ---------------------------------------------------------------------------
function CopyResumeButton({
scriptPath,
runId,
}: {
scriptPath: string;
runId: string;
}): ReactElement {
const { copyToClipboard, isCopied } = useCopyToClipboard({
timeout: 1200,
target: "workflow resume command",
});
const handleCopy = useCallback(() => {
copyToClipboard(`Workflow({ scriptPath: "${scriptPath}", resumeFromRunId: "${runId}" })`);
}, [copyToClipboard, runId, scriptPath]);
return (
<Button type="button" size="xs" variant="outline" onClick={handleCopy}>
{isCopied ? <CheckIcon /> : <CopyIcon />}
Copy resume command
</Button>
);
}
// ---------------------------------------------------------------------------
// Run tab
// ---------------------------------------------------------------------------
function RunTab({
run,
environmentId,
transcriptDir,
remote,
}: {
run: WorkflowRun;
environmentId: EnvironmentId;
transcriptDir: string | undefined;
remote: boolean;
}): ReactElement {
if (remote) {
const sessionUrl = safeWorkflowSessionUrl(run.handles?.sessionUrl);
if (sessionUrl === undefined) {
return <MutedBody text="Running in the cloud" />;
}
return (
<a
href={sessionUrl}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1.5 rounded-md px-0.5 py-1 text-[12px] text-foreground/82 leading-5 hover:bg-accent/20 hover:text-foreground"
>
<ExternalLinkIcon className="size-3.5 shrink-0 text-muted-foreground" />
Running in the cloud — open session
</a>
);
}
if (run.phases.length === 0) {
return <MutedBody text="No agents yet" />;
}
return (
<div className="space-y-px">
{run.phases.map((phase) => (
<div key={`${run.taskId}:${phase.index}`}>
<PhaseHeader phase={phase} />
{phase.agents.map((agent) => (
<ExpandableAgentRow
key={`${run.taskId}:${agent.index}`}
agent={agent}
environmentId={environmentId}
transcriptDir={transcriptDir}
runStatus={run.status}
/>
))}
</div>
))}
</div>
);
}
const stopPropagation = (event: ReactMouseEvent) => event.stopPropagation();
function ExpandableAgentRow({
agent,
environmentId,
transcriptDir,
runStatus,
}: {
agent: WorkflowRunAgent;
environmentId: EnvironmentId;
transcriptDir: string | undefined;
runStatus: WorkflowRunStatus;
}): ReactElement {
const [expanded, setExpanded] = useState(false);
const agentId = agent.agentId;
const canExpand =
agentId !== undefined && transcriptDir !== undefined && agent.isolation !== "remote";
const toggle = useCallback(() => setExpanded((value) => !value), []);
const onKeyDown = useCallback(
(event: ReactKeyboardEvent<HTMLDivElement>) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
toggle();
}
},
[toggle],
);
const leading = canExpand ? (
<ChevronRightIcon
className={cn(
"size-3 shrink-0 text-muted-foreground/60 transition-transform",
expanded && "rotate-90",
)}
/>
) : (
<span className="size-3 shrink-0" />
);
return (
<div
className={cn(
"flex flex-col rounded-md px-0.5 py-0.5 transition-colors",
canExpand &&
"cursor-pointer hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/70 focus-visible:ring-inset",
)}
{...(canExpand
? { role: "button", tabIndex: 0, "aria-expanded": expanded, onClick: toggle, onKeyDown }
: {})}
>
<AgentRowContent agent={agent} leading={leading} />
{canExpand && expanded && agentId !== undefined && transcriptDir !== undefined && (
<AgentTranscriptView
environmentId={environmentId}
transcriptDir={transcriptDir}
agentId={agentId}
runStatus={runStatus}
/>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Transcript view (cursor-paged, polled while running)
// ---------------------------------------------------------------------------
interface TranscriptEntry {
kind: "text" | "tool";
text: string;
}
const TRANSCRIPT_MAX_RETAINED_LINES = 600;
const TRANSCRIPT_TEXT_MAX_CHARS = 600;
const TRANSCRIPT_TOOL_PREVIEW_CHARS = 120;
function clipTranscriptText(text: string, limit: number): string {
const trimmed = text.trim();
return trimmed.length > limit ? `${trimmed.slice(0, limit)}\u2026` : trimmed;
}
function toolInputPreview(input: unknown): string | undefined {
if (typeof input !== "object" || input === null) {
return undefined;
}
const record = input as Record<string, unknown>;
// The most informative single field per common tool, else the first string.
const preferred = record.command ?? record.file_path ?? record.pattern ?? record.prompt;
const value =
typeof preferred === "string"
? preferred
: Object.values(record).find((entry): entry is string => typeof entry === "string");
return value !== undefined ? clipTranscriptText(value, TRANSCRIPT_TOOL_PREVIEW_CHARS) : undefined;
}
/**
* Distill one transcript JSONL line into displayable entries. Only assistant
* text and tool calls render; user turns, tool results, attachments, thinking,
* and harness metadata are skipped — they dominate line counts on long runs
* and read as noise ("user", "attachment", ...) when printed raw.
*/
function parseTranscriptEntries(raw: string): TranscriptEntry[] {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return [];
}
if (typeof parsed !== "object" || parsed === null) {
return [];
}
const record = parsed as Record<string, unknown>;
if (record.type !== "assistant") {
return [];
}
const message =
typeof record.message === "object" && record.message !== null
? (record.message as Record<string, unknown>)
: record;
const content = message.content;
if (typeof content === "string") {
const text = clipTranscriptText(content, TRANSCRIPT_TEXT_MAX_CHARS);
return text.length > 0 ? [{ kind: "text", text }] : [];
}
if (!Array.isArray(content)) {
return [];
}
const entries: TranscriptEntry[] = [];
for (const block of content) {
if (typeof block !== "object" || block === null) {
continue;
}
const blockRecord = block as Record<string, unknown>;
if (blockRecord.type === "text" && typeof blockRecord.text === "string") {
const text = clipTranscriptText(blockRecord.text, TRANSCRIPT_TEXT_MAX_CHARS);
if (text.length > 0) {
entries.push({ kind: "text", text });
}
} else if (blockRecord.type === "tool_use" && typeof blockRecord.name === "string") {
const preview = toolInputPreview(blockRecord.input);
entries.push({
kind: "tool",
text: preview !== undefined ? `${blockRecord.name} ${preview}` : blockRecord.name,
});
}
}
return entries;
}
function AgentTranscriptView({
environmentId,
transcriptDir,
agentId,
runStatus,
}: {
environmentId: EnvironmentId;
transcriptDir: string;
agentId: string;
runStatus: WorkflowRunStatus;
}): ReactElement {
const runTranscript = useAtomCommand(
workflowEnvironment.readAgentTranscript,
"workflow read transcript",
);
const [lines, setLines] = useState<string[]>([]);
const [trimmed, setTrimmed] = useState(false);
const [failed, setFailed] = useState(false);
const [loading, setLoading] = useState(false);
// Render-visible mirror of completeRef: "have we caught up to EOF at least
// once" — before that, an absence of parsed entries just means we are
// still paging, not that the agent produced no output.
const [caughtUp, setCaughtUp] = useState(false);
const transcriptEntries = useMemo(() => lines.flatMap(parseTranscriptEntries), [lines]);
const nextLineRef = useRef(0);
const completeRef = useRef(false);
const loadingRef = useRef(false);
const loadMore = useCallback(async () => {
// `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;
setLoading(true);
const result = await runTranscript({
environmentId,
input: { transcriptDir, agentId, afterLine: nextLineRef.current },
});
loadingRef.current = false;
setLoading(false);
if (result._tag !== "Success") {
setFailed(true);
return;
}
setFailed(false);
nextLineRef.current = result.value.nextLine;
completeRef.current = result.value.complete;
if (result.value.complete) {
setCaughtUp(true);
}
if (result.value.lines.length > 0) {
// Long-running agents can produce transcripts far larger than a view
// needs — retain a bounded tail so memory stays flat on million-token
// threads.
setLines((prev) => {
const merged = [...prev, ...result.value.lines];
if (merged.length > TRANSCRIPT_MAX_RETAINED_LINES) {
setTrimmed(true);
return merged.slice(-TRANSCRIPT_MAX_RETAINED_LINES);
}
return merged;
});
}
}, [agentId, environmentId, runTranscript, transcriptDir]);
// Drain all currently-available pages when the row opens.
useEffect(() => {
const control = { cancelled: false };
const drain = async () => {
while (!control.cancelled && !completeRef.current) {
const before = nextLineRef.current;
await loadMore();
if (control.cancelled || nextLineRef.current === before) {
break;
}
}
};
void drain();
return () => {
control.cancelled = true;
};
}, [loadMore]);
// Keep polling for new lines while the run is live; when the run settles
// (or the row opens on an already-terminal run), fetch once more so lines
// appended after the last poll tick are not lost.
useEffect(() => {
if (runStatus !== "running") {
void loadMore();
return;
}
const id = setInterval(() => {
void loadMore();
}, 2000);
return () => clearInterval(id);
}, [loadMore, runStatus]);
return (
<div
className="mt-1 ml-4 max-h-72 overflow-y-auto rounded-md border border-border/60 bg-muted/30 p-1.5 font-mono text-[11px] leading-4"
onClick={stopPropagation}
>
{transcriptEntries.length === 0 ? (
failed ? (
<p className="text-destructive/80">Failed to load transcript.</p>
) : loading || !caughtUp ? (
<p className="text-muted-foreground/60">Loading transcript…</p>
) : (
<p className="text-muted-foreground/60">No assistant output yet.</p>
)
) : (
<>
{trimmed && (
<p className="text-muted-foreground/50">
Earlier activity trimmed — showing the latest entries.
</p>
)}
{transcriptEntries.map((entry, index) => (
<div
// Entries are append-only and never reordered, so the index is stable.
// oxlint-disable-next-line no-array-index-key
key={`${index}:${entry.text.length}`}
className={cn(
"whitespace-pre-wrap break-words",
entry.kind === "tool" && "text-muted-foreground/60",
)}
>
{entry.kind === "tool" ? `→ ${entry.text}` : entry.text}
</div>
))}
</>
)}
{failed && lines.length > 0 && (
<p className="text-destructive/70">Failed to load more transcript.</p>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Script tab
// ---------------------------------------------------------------------------
let cachedScriptHighlighter: Promise<DiffsHighlighter> | undefined;
function getScriptHighlighter(): Promise<DiffsHighlighter> {
cachedScriptHighlighter ??= getSharedHighlighter({
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
langs: ["javascript" as SupportedLanguages],
preferredHighlighter: "shiki-js",
});
return cachedScriptHighlighter;
}
class WorkflowCodeErrorBoundary extends Component<
{ fallback: ReactNode; children: ReactNode },
{ hasError: boolean }
> {
constructor(props: { fallback: ReactNode; children: ReactNode }) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
override render() {
return this.state.hasError ? this.props.fallback : this.props.children;
}
}
function ScriptHighlight({
source,
themeName,
}: {
source: string;
themeName: DiffThemeName;
}): ReactElement {
const highlighter = use(getScriptHighlighter());
const html = useMemo(
() => highlighter.codeToHtml(source, { lang: "javascript", theme: themeName }),
[highlighter, source, themeName],
);
return (
<div
className="chat-markdown-shiki overflow-x-auto text-[12px]"
dangerouslySetInnerHTML={{ __html: html }}
/>
);
}
function ScriptTab({
scriptPath,
query,
themeName,
}: {
scriptPath: string | undefined;
query: {
data: { source: string; truncated: boolean } | null;
error: string | null;
isPending: boolean;
};
themeName: DiffThemeName;
}): ReactElement {
if (scriptPath === undefined) {
return <MutedBody text="No script for this run." />;
}
if (query.error !== null) {
return <p className="text-[12px] text-destructive/80">{query.error}</p>;
}
if (query.data === null) {
return <MutedBody text={query.isPending ? "Loading script…" : "No script."} />;
}
const { source, truncated } = query.data;
const fallback = (
<pre className="overflow-x-auto rounded-md bg-muted/30 p-2 font-mono text-[12px] leading-5">
{source}
</pre>
);
return (
<div>
{truncated && (
<p className="mb-1.5 text-[11px] text-warning">Script truncated for display.</p>
)}
<WorkflowCodeErrorBoundary fallback={fallback}>
<Suspense fallback={fallback}>
<ScriptHighlight source={source} themeName={themeName} />
</Suspense>
</WorkflowCodeErrorBoundary>
</div>
);
}
// ---------------------------------------------------------------------------
// Logs tab
// ---------------------------------------------------------------------------
interface JournalEntry {
agentId: string;
hasResult: boolean;
resultJson?: string | undefined;
resultTruncated?: boolean | undefined;
}
function LogsTab({
logs,
transcriptDir,
query,
}: {
logs: string[];
transcriptDir: string | undefined;
query: {
data: { entries: readonly JournalEntry[]; truncated: boolean } | null;
error: string | null;
isPending: boolean;
};
}): ReactElement {
return (
<div className="space-y-3">
{logs.length === 0 ? (
<MutedBody text="No logs." />
) : (
<div className="space-y-px font-mono text-[11px] text-muted-foreground/70 leading-4">
{logs.map((log, index) => (
// oxlint-disable-next-line no-array-index-key -- logs are append-only, index is stable
<div key={`${index}:${log.length}`} className="whitespace-pre-wrap break-words">
{log}
</div>
))}
</div>
)}
{transcriptDir !== undefined && (
<div>
<p className="mb-1 text-[10px] text-muted-foreground/65 uppercase tracking-[0.12em]">
Results
</p>
{query.error !== null ? (
<p className="text-[12px] text-destructive/80">{query.error}</p>
) : query.data === null ? (
query.isPending ? (
<MutedBody text="Loading results…" />
) : null
) : query.data.entries.length === 0 ? (
<MutedBody text="No results yet." />
) : (
<div className="space-y-px">
{query.data.entries.map((entry) => (
<JournalResultRow key={entry.agentId} entry={entry} />
))}
</div>
)}
{query.data?.truncated && (
<p className="mt-1 text-[11px] text-muted-foreground/55">Results truncated.</p>
)}
</div>
)}
</div>
);
}
function JournalResultRow({ entry }: { entry: JournalEntry }): ReactElement {
const [expanded, setExpanded] = useState(false);
const resultJson = entry.resultJson;
return (
<div className="rounded-md px-0.5 py-0.5">
<div className="flex items-center gap-1.5 text-[12px] leading-5">
<span className="shrink-0 truncate font-medium text-foreground/82">{entry.agentId}</span>
{!entry.hasResult && <span className="text-[11px] text-muted-foreground/55">pending</span>}
</div>
{resultJson !== undefined &&
(expanded ? (
<div
className="mt-1 cursor-pointer"
role="button"
tabIndex={0}
onClick={() => setExpanded(false)}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
setExpanded(false);
}
}}
>
<pre className="max-h-64 overflow-auto rounded-md bg-muted/30 p-1.5 font-mono text-[11px] leading-4">
{resultJson}
</pre>
{entry.resultTruncated && (
<p className="mt-0.5 text-[10px] text-muted-foreground/55">Result truncated.</p>
)}
</div>
) : (
<button
type="button"
onClick={() => setExpanded(true)}
className="mt-0.5 block w-full cursor-pointer text-left"
>
<span className="line-clamp-3 whitespace-pre-wrap break-words font-mono text-[11px] text-muted-foreground/70 leading-4">
{resultJson}
</span>
</button>
))}
</div>
);
}
// ---------------------------------------------------------------------------
// Shared muted body
// ---------------------------------------------------------------------------
function MutedBody({ text }: { text: string }): ReactElement {
return <p className="px-0.5 py-1 text-[12px] text-muted-foreground/60 leading-5">{text}</p>;
}
@@ -1,152 +0,0 @@
import { ExternalLinkIcon, NetworkIcon } from "lucide-react";
import { type ReactElement } from "react";
import { cn } from "~/lib/utils";
import {
formatWorkflowDuration,
formatWorkflowTokens,
isRemoteWorkflowRun,
type WorkflowRun,
type WorkflowRunAgent,
workflowRunTitle,
} from "~/workflow-logic";
import { Button } from "../ui/button";
import {
AgentRowContent,
PhaseHeader,
WorkflowStatusChip,
agentRollupLabel,
safeWorkflowSessionUrl,
} from "./workflowUi";
const MAX_CARD_AGENT_ROWS = 8;
function agentRecency(agent: WorkflowRunAgent): number {
return agent.lastProgressAt ?? agent.startedAt ?? agent.queuedAt ?? 0;
}
/** Choose which agent indices survive the card cap: running+error first, then most recent. */
function selectVisibleAgentIndices(agents: WorkflowRunAgent[], cap: number): Set<number> {
const prioritized = [...agents].sort((a, b) => {
const aUrgent = a.status === "running" || a.status === "error" ? 0 : 1;
const bUrgent = b.status === "running" || b.status === "error" ? 0 : 1;
if (aUrgent !== bUrgent) {
return aUrgent - bUrgent;
}
return agentRecency(b) - agentRecency(a);
});
return new Set(prioritized.slice(0, cap).map((agent) => agent.index));
}
export function WorkflowRunCard(props: {
workflowRun: WorkflowRun;
onOpenDetails?: (() => void) | undefined;
onStop?: (() => void) | undefined;
}): ReactElement {
const { workflowRun: run, onOpenDetails, onStop } = props;
const title = workflowRunTitle(run);
const remote = isRemoteWorkflowRun(run);
const tokens = run.usage?.totalTokens;
const durationMs = run.usage?.durationMs;
const allAgents = run.phases.flatMap((phase) => phase.agents);
const overCap = allAgents.length > MAX_CARD_AGENT_ROWS;
const visibleIndices = overCap ? selectVisibleAgentIndices(allAgents, MAX_CARD_AGENT_ROWS) : null;
const hiddenCount = overCap ? allAgents.length - MAX_CARD_AGENT_ROWS : 0;
return (
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
<div className="flex items-center gap-2">
<NetworkIcon className="size-3.5 shrink-0 text-muted-foreground" />
<span className="truncate font-medium text-[13px] text-foreground">{title}</span>
<WorkflowStatusChip status={run.status} />
<div className="ml-auto flex items-center gap-2">
<div className="flex items-center gap-2 text-[11px] text-muted-foreground/70 tabular-nums">
<span>{agentRollupLabel(run.agentCounts)}</span>
{tokens !== undefined && <span>{formatWorkflowTokens(tokens)}</span>}
{durationMs !== undefined && <span>{formatWorkflowDuration(durationMs)}</span>}
</div>
{(onStop || onOpenDetails) && (
<div className="flex items-center gap-1.5">
{onStop && (
<Button type="button" size="xs" variant="outline" onClick={onStop}>
Stop
</Button>
)}
{onOpenDetails && (
<Button type="button" size="xs" variant="outline" onClick={onOpenDetails}>
Details
</Button>
)}
</div>
)}
</div>
</div>
{remote ? (
<RemoteRunBody run={run} />
) : allAgents.length > 0 ? (
<div className="mt-1 space-y-px">
{run.phases.map((phase) => {
const rows = phase.agents.filter(
(agent) => visibleIndices === null || visibleIndices.has(agent.index),
);
if (rows.length === 0) {
return null;
}
return (
<div key={`${run.taskId}:${phase.index}`}>
<PhaseHeader phase={phase} />
{rows.map((agent) => (
<div key={`${run.taskId}:${agent.index}`} className="px-0.5 py-0.5">
<AgentRowContent agent={agent} />
</div>
))}
</div>
);
})}
{hiddenCount > 0 && (
<button
type="button"
disabled={onOpenDetails === undefined}
onClick={onOpenDetails}
className={cn(
"w-full px-0.5 py-0.5 text-left text-[12px] text-muted-foreground/60 leading-5",
onOpenDetails &&
"cursor-pointer rounded-md hover:bg-accent/20 hover:text-muted-foreground",
)}
>
+{hiddenCount} more agents — open details
</button>
)}
</div>
) : null}
{run.handles?.warning !== undefined && (
<p className="mt-1.5 text-[11px] text-warning">{run.handles.warning}</p>
)}
</div>
);
}
function RemoteRunBody({ run }: { run: WorkflowRun }): ReactElement {
const sessionUrl = safeWorkflowSessionUrl(run.handles?.sessionUrl);
if (sessionUrl === undefined) {
return (
<p className="mt-1.5 px-0.5 text-[12px] text-muted-foreground/70 leading-5">
Running in the cloud
</p>
);
}
return (
<a
href={sessionUrl}
target="_blank"
rel="noopener noreferrer"
className="mt-1.5 flex items-center gap-1.5 rounded-md px-0.5 py-0.5 text-[12px] text-foreground/82 leading-5 hover:bg-accent/20 hover:text-foreground"
>
<ExternalLinkIcon className="size-3.5 shrink-0 text-muted-foreground" />
Running in the cloud — open session
</a>
);
}
@@ -1,236 +0,0 @@
import type { ReactElement, ReactNode } from "react";
import { cn } from "~/lib/utils";
import {
formatWorkflowDuration,
formatWorkflowTokens,
type WorkflowAgentStatus,
type WorkflowRun,
type WorkflowRunAgent,
type WorkflowRunPhase,
type WorkflowRunStatus,
} from "~/workflow-logic";
// ---------------------------------------------------------------------------
// Run-level status chip
// ---------------------------------------------------------------------------
interface RunStatusVisual {
label: string;
dotClass: string;
textClass: string;
pulse: boolean;
}
const RUN_STATUS_VISUALS: Record<WorkflowRunStatus, RunStatusVisual> = {
running: { label: "Running", dotClass: "bg-info", textClass: "text-info", pulse: true },
completed: {
label: "Completed",
dotClass: "bg-success",
textClass: "text-success",
pulse: false,
},
failed: {
label: "Failed",
dotClass: "bg-destructive",
textClass: "text-destructive",
pulse: false,
},
stopped: {
label: "Stopped",
dotClass: "bg-muted-foreground",
textClass: "text-muted-foreground",
pulse: false,
},
};
export function WorkflowStatusChip({ status }: { status: WorkflowRunStatus }): ReactElement {
const visual = RUN_STATUS_VISUALS[status];
return (
<span
className={cn(
"inline-flex shrink-0 items-center gap-1 font-medium text-[11px]",
visual.textClass,
)}
>
<span className="relative flex size-1.5">
{visual.pulse && (
<span
className={cn(
"absolute inline-flex size-full animate-ping rounded-full opacity-60",
visual.dotClass,
)}
/>
)}
<span className={cn("relative inline-flex size-1.5 rounded-full", visual.dotClass)} />
</span>
{visual.label}
</span>
);
}
// ---------------------------------------------------------------------------
// Agent-level presentation
// ---------------------------------------------------------------------------
const AGENT_STATUS_DOT: Record<WorkflowAgentStatus, string> = {
queued: "bg-muted-foreground/50",
running: "bg-info animate-pulse",
done: "bg-success",
error: "bg-destructive",
};
export function AgentStatusDot({ status }: { status: WorkflowAgentStatus }): ReactElement {
return <span className={cn("size-1.5 shrink-0 rounded-full", AGENT_STATUS_DOT[status])} />;
}
export function agentDisplayLabel(agent: WorkflowRunAgent): string {
return agent.label ?? agent.agentType ?? `agent ${agent.index}`;
}
function AgentMetaBadges({ agent }: { agent: WorkflowRunAgent }): ReactElement | null {
const badges: string[] = [];
if (agent.cached) {
badges.push("cached");
}
if (agent.attempt !== undefined && agent.attempt > 1) {
badges.push(`retry ${agent.attempt}`);
}
if (badges.length === 0) {
return null;
}
return (
<>
{badges.map((badge) => (
<span
key={badge}
className="shrink-0 rounded-sm bg-muted px-1 text-[10px] text-muted-foreground/80 leading-4"
>
{badge}
</span>
))}
</>
);
}
/** "94.2k tok · 47 tools · 7m 03s" — cumulative per-agent stats from the
* SDK snapshot. Tokens and tool counts update on every progress tick; the
* duration is the reported total once the agent settles, and the elapsed
* time between start and the latest tick while it runs (tick-driven, so no
* client timer is needed). */
export function agentStatsLabel(agent: WorkflowRunAgent): string | undefined {
const parts: string[] = [];
if (agent.tokens !== undefined && agent.tokens > 0) {
parts.push(`${formatWorkflowTokens(agent.tokens)} tok`);
}
if (agent.toolCalls !== undefined && agent.toolCalls > 0) {
parts.push(`${agent.toolCalls} ${agent.toolCalls === 1 ? "tool" : "tools"}`);
}
const settled = agent.status === "done" || agent.status === "error";
if (settled && agent.durationMs !== undefined && agent.durationMs > 0) {
parts.push(formatWorkflowDuration(agent.durationMs));
} else if (
!settled &&
agent.startedAt !== undefined &&
agent.lastProgressAt !== undefined &&
agent.lastProgressAt > agent.startedAt
) {
parts.push(formatWorkflowDuration(agent.lastProgressAt - agent.startedAt));
}
return parts.length > 0 ? parts.join(" · ") : undefined;
}
/**
* The shared inner content of an agent row. Two-line layout: the label owns
* the first line and wraps freely (long workflow labels are common), and
* model / stats / badges / error text sit on a muted meta line beneath —
* nothing competes for horizontal space, so nothing clips.
*/
export function AgentRowContent({
agent,
leading,
}: {
agent: WorkflowRunAgent;
leading?: ReactNode;
}): ReactElement {
const stats = agentStatsLabel(agent);
// Failures often surface only in resultPreview (e.g. a thrown value the
// runner stringified) — fall back to it so red rows always explain why.
const errorText = agent.status === "error" ? (agent.error ?? agent.resultPreview) : undefined;
const metaLabel = [agent.model, stats].filter((part) => part !== undefined).join(" · ");
const hasBadges = agent.cached === true || (agent.attempt !== undefined && agent.attempt > 1);
return (
<div className="flex min-w-0 items-start gap-1.5 text-[12px] leading-5">
{/* Fixed line-height boxes center the affordances on the first text line. */}
{leading !== undefined && <span className="flex h-5 shrink-0 items-center">{leading}</span>}
<span className="flex h-5 shrink-0 items-center">
<AgentStatusDot status={agent.status} />
</span>
<div className="min-w-0 flex-1">
<div
className={cn(
"break-words font-medium",
agent.status === "error" ? "text-destructive" : "text-foreground/82",
)}
>
{agentDisplayLabel(agent)}
</div>
{(metaLabel.length > 0 || hasBadges || errorText !== undefined) && (
<div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[11px] text-muted-foreground/60 leading-4">
{metaLabel.length > 0 && <span className="tabular-nums">{metaLabel}</span>}
<AgentMetaBadges agent={agent} />
{errorText !== undefined && (
<span className="min-w-0 break-words text-destructive/75">{errorText}</span>
)}
</div>
)}
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// 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" || agent.status === "error").length;
}
export function PhaseHeader({ phase }: { phase: WorkflowRunPhase }): ReactElement {
return (
<div className="flex items-center justify-between gap-2 px-0.5 pt-1.5 pb-0.5">
<span className="truncate text-[10px] text-muted-foreground/65 uppercase tracking-[0.12em]">
{phase.title}
</span>
{phase.agents.length > 0 && (
<span className="shrink-0 text-[10px] text-muted-foreground/55 tabular-nums">
{phaseDoneCount(phase)}/{phase.agents.length}
</span>
)}
</div>
);
}
export function agentRollupLabel(counts: WorkflowRun["agentCounts"]): string {
return `${counts.done + counts.error}/${counts.total} agents`;
}
+5 -33
View File
@@ -14,15 +14,7 @@ import { createJSONStorage, persist } from "zustand/middleware";
import { resolveStorage } from "./lib/storage";
export const RIGHT_PANEL_KINDS = [
"plan",
"diff",
"files",
"file",
"preview",
"terminal",
"workflow",
] as const;
export const RIGHT_PANEL_KINDS = ["plan", "diff", "files", "file", "preview", "terminal"] as const;
export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
export type RightPanelSurface =
@@ -45,8 +37,7 @@ export type RightPanelSurface =
revealLine: number | null;
revealRequestId: number;
}
| { id: "plan"; kind: "plan" }
| { id: `workflow:${string}`; kind: "workflow"; taskId: string };
| { id: "plan"; kind: "plan" };
const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
const RIGHT_PANEL_STORAGE_VERSION = 7;
@@ -59,14 +50,10 @@ export interface ThreadRightPanelState {
interface RightPanelStoreState {
byThreadKey: Record<string, ThreadRightPanelState>;
open: (
ref: ScopedThreadRef,
kind: Exclude<RightPanelKind, "file" | "terminal" | "workflow">,
) => void;
open: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "file" | "terminal">) => void;
openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;
openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
openWorkflow: (ref: ScopedThreadRef, taskId: string) => void;
splitTerminal: (
ref: ScopedThreadRef,
surfaceId: string,
@@ -85,10 +72,7 @@ interface RightPanelStoreState {
show: (ref: ScopedThreadRef) => void;
close: (ref: ScopedThreadRef) => void;
toggleVisibility: (ref: ScopedThreadRef) => void;
toggle: (
ref: ScopedThreadRef,
kind: Exclude<RightPanelKind, "file" | "terminal" | "workflow">,
) => void;
toggle: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "file" | "terminal">) => void;
removeThread: (ref: ScopedThreadRef) => void;
}
@@ -99,7 +83,7 @@ const EMPTY_THREAD_STATE: ThreadRightPanelState = {
};
const singletonSurface = (
kind: Exclude<RightPanelKind, "file" | "preview" | "terminal" | "workflow">,
kind: Exclude<RightPanelKind, "file" | "preview" | "terminal">,
): RightPanelSurface => {
switch (kind) {
case "diff":
@@ -128,12 +112,6 @@ const fileSurface = (
revealRequestId,
});
const workflowSurface = (taskId: string): RightPanelSurface => ({
id: `workflow:${taskId}`,
kind: "workflow",
taskId,
});
const terminalSurface = (terminalId: string): RightPanelSurface => ({
id: `terminal:${terminalId}`,
kind: "terminal",
@@ -308,12 +286,6 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
};
}),
})),
openWorkflow: (ref, taskId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
upsertSurface(current, workflowSurface(taskId)),
),
})),
openTerminal: (ref, terminalId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
-115
View File
@@ -22,7 +22,6 @@ import {
workEntryIndicatesToolNeutralStatus,
workEntryIndicatesToolSuccess,
} from "./session-logic";
import { deriveWorkflowRuns } from "./workflow-logic.ts";
let nextActivityId = 0;
@@ -1491,72 +1490,6 @@ describe("deriveWorkLogEntries", () => {
expect(entries).toHaveLength(1);
expect(entries[0]?.id).toBe("a-complete-same-timestamp");
});
it("suppresses workflow task rows and snapshot activities while keeping plain task rows", () => {
const activities: OrchestrationThreadActivity[] = [
// Plain task: its progress/completed rows must survive.
makeActivity({
id: "plain-progress",
createdAt: "2026-02-23T00:00:01.000Z",
kind: "task.progress",
summary: "Reasoning update",
tone: "info",
payload: { taskId: "plain-1", summary: "thinking about it" },
}),
makeActivity({
id: "plain-complete",
createdAt: "2026-02-23T00:00:02.000Z",
kind: "task.completed",
summary: "Task completed",
tone: "info",
payload: { taskId: "plain-1", status: "completed", detail: "plain done" },
}),
// Workflow task: every row below belongs to the dedicated workflow card.
makeActivity({
id: "wf-start",
createdAt: "2026-02-23T00:00:03.000Z",
kind: "task.started",
summary: "local_workflow task started",
tone: "info",
payload: { taskId: "wf-1", taskType: "local_workflow", workflowName: "spec" },
}),
makeActivity({
id: "wf-progress",
createdAt: "2026-02-23T00:00:04.000Z",
kind: "task.progress",
summary: "Reasoning update",
tone: "info",
payload: { taskId: "wf-1", summary: "workflow ticking" },
}),
makeActivity({
id: "wf-updated",
createdAt: "2026-02-23T00:00:05.000Z",
kind: "task.workflow-updated",
summary: "spec workflow",
tone: "info",
payload: { taskId: "wf-1", description: "spec", workflowProgress: [] },
}),
makeActivity({
id: "wf-meta",
createdAt: "2026-02-23T00:00:06.000Z",
kind: "task.workflow-meta",
summary: "Workflow launched",
tone: "info",
payload: { taskId: "wf-1", runId: "wf_abc" },
}),
makeActivity({
id: "wf-complete",
createdAt: "2026-02-23T00:00:07.000Z",
kind: "task.completed",
summary: "Task completed",
tone: "info",
payload: { taskId: "wf-1", status: "completed" },
}),
];
const entries = deriveWorkLogEntries(activities);
expect(entries.map((entry) => entry.id)).toEqual(["plain-progress", "plain-complete"]);
});
});
describe("deriveTimelineEntries", () => {
@@ -1604,54 +1537,6 @@ describe("deriveTimelineEntries", () => {
},
});
});
it("emits a workflow entry sorted chronologically among messages", () => {
const workflowRuns = deriveWorkflowRuns([
makeActivity({
id: "wf-start",
createdAt: "2026-02-23T00:00:02.000Z",
kind: "task.started",
summary: "local_workflow task started",
tone: "info",
payload: { taskId: "task-wf", taskType: "local_workflow", workflowName: "spec" },
}),
]);
expect(workflowRuns).toHaveLength(1);
const entries = deriveTimelineEntries(
[
{
id: MessageId.make("message-before"),
role: "user",
text: "kick it off",
createdAt: "2026-02-23T00:00:01.000Z",
turnId: null,
updatedAt: "2026-02-23T00:00:01.000Z",
streaming: false,
},
{
id: MessageId.make("message-after"),
role: "assistant",
text: "done",
createdAt: "2026-02-23T00:00:03.000Z",
turnId: null,
updatedAt: "2026-02-23T00:00:03.000Z",
streaming: false,
},
],
[],
[],
workflowRuns,
);
expect(entries.map((entry) => entry.kind)).toEqual(["message", "workflow", "message"]);
const workflowEntry = entries[1];
expect(workflowEntry).toMatchObject({
kind: "workflow",
id: "workflow:task-wf",
workflowRun: { taskId: "task-wf", name: "spec" },
});
});
});
describe("deriveWorkLogEntries context window handling", () => {
+1 -36
View File
@@ -21,7 +21,6 @@ import type {
ThreadSession,
TurnDiffSummary,
} from "./types";
import { collectWorkflowTaskIds, type WorkflowRun } from "./workflow-logic.ts";
export type ProviderPickerKind = ProviderDriverKind;
@@ -138,12 +137,6 @@ export type TimelineEntry =
kind: "work";
createdAt: string;
entry: WorkLogEntry;
}
| {
id: string;
kind: "workflow";
createdAt: string;
workflowRun: WorkflowRun;
};
export function workLogEntryIsToolLike(entry: WorkLogEntry): boolean {
@@ -631,36 +624,15 @@ export function hasActionableProposedPlan(
return proposedPlan !== null && proposedPlan.implementedAt === null;
}
function activityBelongsToWorkflow(
activity: OrchestrationThreadActivity,
workflowTaskIds: ReadonlySet<string>,
): boolean {
const payload = activity.payload as Record<string, unknown> | null | undefined;
const taskId = payload && typeof payload === "object" ? payload["taskId"] : undefined;
return typeof taskId === "string" && workflowTaskIds.has(taskId);
}
export function deriveWorkLogEntries(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): WorkLogEntry[] {
const ordered = [...activities].toSorted(compareActivitiesByOrder);
const workflowTaskIds = collectWorkflowTaskIds(activities);
const entries: DerivedWorkLogEntry[] = [];
for (const activity of ordered) {
if (activity.kind === "tool.started") continue;
if (activity.kind === "task.started") continue;
if (activity.kind === "context-window.updated") continue;
// Workflow runs render as dedicated timeline cards; their snapshot
// activities and per-tick task rows would duplicate that surface.
if (activity.kind === "task.workflow-updated") continue;
if (activity.kind === "task.workflow-meta") continue;
if (
(activity.kind === "task.progress" || activity.kind === "task.completed") &&
workflowTaskIds.size > 0 &&
activityBelongsToWorkflow(activity, workflowTaskIds)
) {
continue;
}
if (activity.summary === "Checkpoint captured") continue;
if (isPlanBoundaryToolActivity(activity)) continue;
entries.push(toDerivedWorkLogEntry(activity));
@@ -1369,7 +1341,6 @@ export function deriveTimelineEntries(
messages: ReadonlyArray<ChatMessage>,
proposedPlans: ReadonlyArray<ProposedPlan>,
workEntries: ReadonlyArray<WorkLogEntry>,
workflowRuns: ReadonlyArray<WorkflowRun> = [],
): TimelineEntry[] {
const messageRows: TimelineEntry[] = messages.map((message) => ({
id: message.id,
@@ -1389,13 +1360,7 @@ export function deriveTimelineEntries(
createdAt: entry.createdAt,
entry,
}));
const workflowRows: TimelineEntry[] = workflowRuns.map((workflowRun) => ({
id: `workflow:${workflowRun.taskId}`,
kind: "workflow",
createdAt: workflowRun.createdAt,
workflowRun,
}));
return [...messageRows, ...proposedPlanRows, ...workRows, ...workflowRows].toSorted((a, b) =>
return [...messageRows, ...proposedPlanRows, ...workRows].toSorted((a, b) =>
a.createdAt.localeCompare(b.createdAt),
);
}
-5
View File
@@ -1,5 +0,0 @@
import { createWorkflowEnvironmentAtoms } from "@t3tools/client-runtime/state/workflow";
import { connectionAtomRuntime } from "../connection/runtime";
export const workflowEnvironment = createWorkflowEnvironmentAtoms(connectionAtomRuntime);
-397
View File
@@ -1,397 +0,0 @@
import {
NonNegativeInt,
EventId,
type OrchestrationThreadActivity,
TurnId,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
collectWorkflowTaskIds,
deriveWorkflowAgentStatus,
deriveWorkflowRuns,
groupWorkflowAgentsByPhase,
isRemoteWorkflowRun,
type WorkflowRunAgent,
} from "./workflow-logic.ts";
let nextActivityId = 0;
function buildActivity(overrides: {
id?: string;
createdAt?: string;
kind?: string;
summary?: string;
tone?: OrchestrationThreadActivity["tone"];
payload?: Record<string, unknown>;
turnId?: string;
sequence?: number;
}): OrchestrationThreadActivity {
return {
id: EventId.make(overrides.id ?? `activity-${nextActivityId++}`),
createdAt: overrides.createdAt ?? "2026-02-23T00:00:00.000Z",
kind: overrides.kind ?? "task.started",
// summary/kind must be trimmed non-empty branded strings.
summary: overrides.summary ?? "Workflow",
tone: overrides.tone ?? "info",
payload: overrides.payload ?? {},
turnId: overrides.turnId ? TurnId.make(overrides.turnId) : null,
...(overrides.sequence !== undefined
? { sequence: NonNegativeInt.make(overrides.sequence) }
: {}),
};
}
describe("deriveWorkflowAgentStatus", () => {
it("maps terminal states directly", () => {
expect(deriveWorkflowAgentStatus({ state: "done" })).toBe("done");
expect(deriveWorkflowAgentStatus({ state: "error" })).toBe("error");
});
it("treats start without startedAt as queued and with startedAt as running", () => {
expect(deriveWorkflowAgentStatus({ state: "start" })).toBe("queued");
expect(deriveWorkflowAgentStatus({ state: "start", startedAt: 123 })).toBe("running");
});
it("renders unknown future states as running once startedAt is present", () => {
expect(deriveWorkflowAgentStatus({ state: "reticulating", startedAt: 1 })).toBe("running");
expect(deriveWorkflowAgentStatus({ state: "reticulating" })).toBe("queued");
});
});
describe("groupWorkflowAgentsByPhase", () => {
const agent = (over: Partial<WorkflowRunAgent> & { index: number }): WorkflowRunAgent => ({
state: "start",
status: "queued",
...over,
});
it("groups agents under their phase and synthesizes an Agents phase for unphased agents", () => {
const phases = groupWorkflowAgentsByPhase({
phases: [{ index: 0, title: "Plan" }],
agents: [
agent({ index: 0, phaseIndex: 0 }),
agent({ index: 1 }), // no phaseIndex -> synthetic "Agents" phase (index -1)
],
});
expect(phases.map((phase) => phase.title)).toEqual(["Agents", "Plan"]);
const synthetic = phases.find((phase) => phase.title === "Agents");
expect(synthetic?.index).toBe(-1);
expect(synthetic?.agents.map((entry) => entry.index)).toEqual([1]);
});
it("falls back to a Phase <n> title when the phase is unknown but an agent references it", () => {
const phases = groupWorkflowAgentsByPhase({
phases: [],
agents: [agent({ index: 0, phaseIndex: 2 })],
});
expect(phases).toHaveLength(1);
expect(phases[0]?.title).toBe("Phase 2");
});
it("prefers an agent-supplied phaseTitle for an otherwise-unknown phase", () => {
const phases = groupWorkflowAgentsByPhase({
phases: [],
agents: [agent({ index: 0, phaseIndex: 5, phaseTitle: "Custom" })],
});
expect(phases[0]?.title).toBe("Custom");
});
});
function workflowStartedActivity(taskId: string, extra?: Record<string, unknown>) {
return buildActivity({
id: `start-${taskId}`,
kind: "task.started",
createdAt: "2026-02-23T00:00:01.000Z",
turnId: "turn-1",
payload: { taskId, taskType: "local_workflow", workflowName: "spec", ...extra },
});
}
function workflowUpdatedActivity(
taskId: string,
workflowProgress: unknown[],
extra?: Record<string, unknown>,
) {
return buildActivity({
id: `updated-${taskId}`,
kind: "task.workflow-updated",
createdAt: "2026-02-23T00:00:02.000Z",
payload: { taskId, description: "spec workflow", workflowProgress, ...extra },
});
}
describe("deriveWorkflowRuns", () => {
it("derives a single running->completed lifecycle from started + updated + meta + completed", () => {
const runs = deriveWorkflowRuns([
workflowStartedActivity("task-1"),
workflowUpdatedActivity("task-1", [
{ type: "workflow_phase", index: 0, title: "Plan" },
{ type: "workflow_agent", index: 0, state: "done", phaseIndex: 0 },
{ type: "workflow_log", message: "kicked off" },
]),
buildActivity({
id: "meta-task-1",
kind: "task.workflow-meta",
createdAt: "2026-02-23T00:00:03.000Z",
payload: {
taskId: "task-1",
runId: "wf_abc",
scriptPath: "/x/s.js",
transcriptDir: "/x/t",
},
}),
buildActivity({
id: "complete-task-1",
kind: "task.completed",
createdAt: "2026-02-23T00:00:04.000Z",
payload: { taskId: "task-1", status: "completed", detail: "all done" },
}),
]);
expect(runs).toHaveLength(1);
const run = runs[0]!;
expect(run.taskId).toBe("task-1");
expect(run.status).toBe("completed");
expect(run.name).toBe("spec");
expect(run.completionSummary).toBe("all done");
expect(run.handles?.runId).toBe("wf_abc");
expect(run.logs).toEqual(["kicked off"]);
expect(run.agentCounts).toEqual({ total: 1, queued: 0, running: 0, done: 1, error: 0 });
expect(run.turnId).toBe(TurnId.make("turn-1"));
});
it("maps failed and stopped completion statuses", () => {
const failed = deriveWorkflowRuns([
workflowStartedActivity("task-f"),
buildActivity({
id: "complete-task-f",
kind: "task.completed",
createdAt: "2026-02-23T00:00:04.000Z",
payload: { taskId: "task-f", status: "failed" },
}),
]);
expect(failed[0]?.status).toBe("failed");
const stopped = deriveWorkflowRuns([
workflowStartedActivity("task-s"),
buildActivity({
id: "complete-task-s",
kind: "task.completed",
createdAt: "2026-02-23T00:00:04.000Z",
payload: { taskId: "task-s", status: "stopped" },
}),
]);
expect(stopped[0]?.status).toBe("stopped");
});
it("derives agent status per entry (queued/running/done/error/unknown-with-startedAt)", () => {
const runs = deriveWorkflowRuns([
workflowStartedActivity("task-1"),
workflowUpdatedActivity("task-1", [
{ type: "workflow_agent", index: 0, state: "start" },
{ type: "workflow_agent", index: 1, state: "start", startedAt: 100 },
{ type: "workflow_agent", index: 2, state: "done" },
{ type: "workflow_agent", index: 3, state: "error" },
{ type: "workflow_agent", index: 4, state: "reticulating", startedAt: 5 },
]),
]);
expect(runs[0]?.agentCounts).toEqual({
total: 5,
queued: 1,
running: 2,
done: 1,
error: 1,
});
});
it("lets a later agent entry with the same index win", () => {
const runs = deriveWorkflowRuns([
workflowStartedActivity("task-1"),
workflowUpdatedActivity("task-1", [
{ type: "workflow_agent", index: 0, state: "start" },
{ type: "workflow_agent", index: 0, state: "done" },
]),
]);
expect(runs[0]?.agentCounts.total).toBe(1);
expect(runs[0]?.agentCounts.done).toBe(1);
expect(runs[0]?.agentCounts.queued).toBe(0);
});
it("drops malformed progress entries without throwing", () => {
const runs = deriveWorkflowRuns([
workflowStartedActivity("task-1"),
workflowUpdatedActivity("task-1", [
{ type: "workflow_agent", state: "start" }, // missing index
{ type: "workflow_agent", index: 1 }, // missing state
"not an object",
null,
{ type: "workflow_mystery", index: 9 },
{ type: "workflow_agent", index: 2, state: "done" },
]),
]);
expect(runs[0]?.agentCounts.total).toBe(1);
expect(runs[0]?.agentCounts.done).toBe(1);
});
it("parses per-agent tokens, tool calls, and duration from the snapshot", () => {
const runs = deriveWorkflowRuns([
workflowStartedActivity("task-1"),
workflowUpdatedActivity("task-1", [
{
type: "workflow_agent",
index: 0,
state: "done",
tokens: 94_200,
toolCalls: 47,
durationMs: 423_000,
},
]),
]);
const agent = runs[0]?.phases.flatMap((phase) => phase.agents)[0];
expect(agent?.tokens).toBe(94_200);
expect(agent?.toolCalls).toBe(47);
expect(agent?.durationMs).toBe(423_000);
});
it("parses snake_case usage from the updated snapshot", () => {
const runs = deriveWorkflowRuns([
workflowStartedActivity("task-1"),
workflowUpdatedActivity("task-1", [{ type: "workflow_agent", index: 0, state: "done" }], {
usage: { total_tokens: 1200, tool_uses: 3, duration_ms: 4500 },
}),
]);
expect(runs[0]?.usage).toEqual({ totalTokens: 1200, toolUses: 3, durationMs: 4500 });
});
it("ignores plain (non-workflow) tasks entirely", () => {
const runs = deriveWorkflowRuns([
buildActivity({
id: "plain-start",
kind: "task.started",
payload: { taskId: "plain-1", taskType: "plan" },
}),
buildActivity({
id: "plain-progress",
kind: "task.progress",
payload: { taskId: "plain-1", summary: "thinking" },
}),
buildActivity({
id: "plain-complete",
kind: "task.completed",
payload: { taskId: "plain-1", status: "completed" },
}),
]);
expect(runs).toEqual([]);
});
it("terminalizes a still-running run and settles in-flight agents when the session is gone", () => {
const runs = deriveWorkflowRuns(
[
workflowStartedActivity("task-1"),
workflowUpdatedActivity("task-1", [
{ type: "workflow_agent", index: 0, state: "done" },
{ type: "workflow_agent", index: 1, state: "start", startedAt: 1000 },
{ type: "workflow_agent", index: 2, state: "start" },
]),
],
{ sessionActive: false },
);
const run = runs[0];
expect(run?.status).toBe("stopped");
const agents = run?.phases.flatMap((phase) => phase.agents) ?? [];
expect(agents.map((agent) => agent.status)).toEqual(["done", "error", "error"]);
expect(agents[1]?.error).toBe("Interrupted before completion");
expect(run?.agentCounts).toEqual({ total: 3, queued: 0, running: 0, done: 1, error: 2 });
});
it("applies a completion even when it sorts before its task.started", () => {
const completed = buildActivity({
id: "completed-task-1",
kind: "task.completed",
createdAt: "2026-02-23T00:00:00.500Z",
sequence: 1,
payload: { taskId: "task-1", status: "completed", detail: "done" },
});
// Same-timestamp + inverted sequence (adopted runs can reset provider
// sequence): the started activity sorts after the completion.
const started = { ...workflowStartedActivity("task-1"), sequence: NonNegativeInt.make(5) };
const runs = deriveWorkflowRuns([completed, started]);
expect(runs).toHaveLength(1);
expect(runs[0]?.status).toBe("completed");
expect(runs[0]?.name).toBe("spec");
});
it("keeps a running run untouched while the session is active", () => {
const runs = deriveWorkflowRuns(
[
workflowStartedActivity("task-1"),
workflowUpdatedActivity("task-1", [
{ type: "workflow_agent", index: 0, state: "start", startedAt: 1000 },
]),
],
{ sessionActive: true },
);
expect(runs[0]?.status).toBe("running");
expect(runs[0]?.phases.flatMap((phase) => phase.agents)[0]?.status).toBe("running");
});
it("detects remote runs from session handles", () => {
const runs = deriveWorkflowRuns([
workflowStartedActivity("task-remote"),
buildActivity({
id: "meta-remote",
kind: "task.workflow-meta",
createdAt: "2026-02-23T00:00:03.000Z",
payload: { taskId: "task-remote", sessionUrl: "https://example.com/run" },
}),
]);
expect(runs).toHaveLength(1);
expect(isRemoteWorkflowRun(runs[0]!)).toBe(true);
});
});
describe("collectWorkflowTaskIds", () => {
it("collects workflow task ids via workflowName, local_workflow task type, and workflow kinds", () => {
const ids = collectWorkflowTaskIds([
buildActivity({
id: "s1",
kind: "task.started",
payload: { taskId: "by-name", workflowName: "spec" },
}),
buildActivity({
id: "s2",
kind: "task.started",
payload: { taskId: "by-type", taskType: "local_workflow" },
}),
buildActivity({
id: "u1",
kind: "task.workflow-updated",
payload: { taskId: "by-updated", workflowProgress: [] },
}),
buildActivity({
id: "m1",
kind: "task.workflow-meta",
payload: { taskId: "by-meta" },
}),
]);
expect([...ids].sort()).toEqual(["by-meta", "by-name", "by-type", "by-updated"]);
});
it("does not collect plain task ids", () => {
const ids = collectWorkflowTaskIds([
buildActivity({
id: "plain",
kind: "task.started",
payload: { taskId: "plain-1", taskType: "plan" },
}),
buildActivity({
id: "plain-progress",
kind: "task.progress",
payload: { taskId: "plain-1" },
}),
]);
expect(ids.has("plain-1")).toBe(false);
expect(ids.size).toBe(0);
});
});
-546
View File
@@ -1,546 +0,0 @@
import type { OrchestrationThreadActivity, TurnId } from "@t3tools/contracts";
/**
* Derivation of workflow-run view models from thread activities.
*
* Workflow state arrives as three activity kinds emitted by the server:
* - `task.started` / `task.completed` — lifecycle (shared with plain tasks)
* - `task.workflow-updated` — cumulative snapshot (phases, agents, logs),
* upserted under a stable activity id per task
* - `task.workflow-meta` — run handles (script path, transcript dir, run id)
*
* Everything here parses `activity.payload` defensively: payloads are
* `unknown` end-to-end and originate from an undocumented SDK surface, so a
* malformed field must degrade to less detail, never throw.
*/
export type WorkflowAgentStatus = "queued" | "running" | "done" | "error";
export interface WorkflowRunAgent {
index: number;
status: WorkflowAgentStatus;
state: string;
label?: string | undefined;
phaseIndex?: number | undefined;
phaseTitle?: string | undefined;
agentId?: string | undefined;
agentType?: string | undefined;
model?: string | undefined;
isolation?: "worktree" | "remote" | undefined;
attempt?: number | undefined;
queuedAt?: number | undefined;
startedAt?: number | undefined;
lastProgressAt?: number | undefined;
cached?: boolean | undefined;
remoteSessionId?: string | undefined;
lastToolName?: string | undefined;
lastToolSummary?: string | undefined;
promptPreview?: string | undefined;
resultPreview?: string | undefined;
error?: string | undefined;
tokens?: number | undefined;
toolCalls?: number | undefined;
durationMs?: number | undefined;
}
export interface WorkflowRunPhase {
index: number;
title: string;
kind?: string | undefined;
agents: WorkflowRunAgent[];
}
export interface WorkflowRunUsage {
totalTokens?: number | undefined;
toolUses?: number | undefined;
durationMs?: number | undefined;
}
export interface WorkflowRunHandlesView {
runId?: string | undefined;
taskType?: string | undefined;
scriptPath?: string | undefined;
transcriptDir?: string | undefined;
sessionUrl?: string | undefined;
warning?: string | undefined;
}
export type WorkflowRunStatus = "running" | "completed" | "failed" | "stopped";
export interface WorkflowRun {
taskId: string;
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;
completionSummary?: string | undefined;
phases: WorkflowRunPhase[];
logs: string[];
usage?: WorkflowRunUsage | undefined;
handles?: WorkflowRunHandlesView | undefined;
agentCounts: {
total: number;
queued: number;
running: number;
done: number;
error: number;
};
}
function asRecord(value: unknown): Record<string, unknown> | undefined {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" && value.trim().length > 0 ? value : undefined;
}
function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
export function deriveWorkflowAgentStatus(input: {
state: string;
startedAt?: number;
}): WorkflowAgentStatus {
if (input.state === "done") {
return "done";
}
if (input.state === "error") {
return "error";
}
// "start" plus any state a future SDK adds: running once work has begun.
return input.startedAt !== undefined ? "running" : "queued";
}
function parseAgentEntry(entry: Record<string, unknown>): WorkflowRunAgent | undefined {
const index = asNumber(entry.index);
const state = asString(entry.state);
if (index === undefined || state === undefined) {
return undefined;
}
const startedAt = asNumber(entry.startedAt);
const isolation =
entry.isolation === "worktree" || entry.isolation === "remote" ? entry.isolation : undefined;
return {
index,
state,
status: deriveWorkflowAgentStatus({ state, ...(startedAt !== undefined ? { startedAt } : {}) }),
...(asString(entry.label) !== undefined ? { label: asString(entry.label) } : {}),
...(asNumber(entry.phaseIndex) !== undefined ? { phaseIndex: asNumber(entry.phaseIndex) } : {}),
...(asString(entry.phaseTitle) !== undefined ? { phaseTitle: asString(entry.phaseTitle) } : {}),
...(asString(entry.agentId) !== undefined ? { agentId: asString(entry.agentId) } : {}),
...(asString(entry.agentType) !== undefined ? { agentType: asString(entry.agentType) } : {}),
...(asString(entry.model) !== undefined ? { model: asString(entry.model) } : {}),
...(isolation !== undefined ? { isolation } : {}),
...(asNumber(entry.attempt) !== undefined ? { attempt: asNumber(entry.attempt) } : {}),
...(asNumber(entry.queuedAt) !== undefined ? { queuedAt: asNumber(entry.queuedAt) } : {}),
...(startedAt !== undefined ? { startedAt } : {}),
...(asNumber(entry.lastProgressAt) !== undefined
? { lastProgressAt: asNumber(entry.lastProgressAt) }
: {}),
...(entry.cached === true ? { cached: true } : {}),
...(asString(entry.remoteSessionId) !== undefined
? { remoteSessionId: asString(entry.remoteSessionId) }
: {}),
...(asString(entry.lastToolName) !== undefined
? { lastToolName: asString(entry.lastToolName) }
: {}),
...(asString(entry.lastToolSummary) !== undefined
? { lastToolSummary: asString(entry.lastToolSummary) }
: {}),
...(asString(entry.promptPreview) !== undefined
? { promptPreview: asString(entry.promptPreview) }
: {}),
...(asString(entry.resultPreview) !== undefined
? { resultPreview: asString(entry.resultPreview) }
: {}),
...(asString(entry.error) !== undefined ? { error: asString(entry.error) } : {}),
...(asNumber(entry.tokens) !== undefined ? { tokens: asNumber(entry.tokens) } : {}),
...(asNumber(entry.toolCalls) !== undefined ? { toolCalls: asNumber(entry.toolCalls) } : {}),
...(asNumber(entry.durationMs) !== undefined ? { durationMs: asNumber(entry.durationMs) } : {}),
};
}
interface ParsedWorkflowProgress {
phases: Array<{ index: number; title: string; kind?: string | undefined }>;
agents: WorkflowRunAgent[];
logs: string[];
}
function parseWorkflowProgress(value: unknown): ParsedWorkflowProgress {
const parsed: ParsedWorkflowProgress = { phases: [], agents: [], logs: [] };
if (!Array.isArray(value)) {
return parsed;
}
// Later entries for the same index win: snapshots are cumulative and the
// runner may re-emit an agent slot on retry.
const agentsByIndex = new Map<number, WorkflowRunAgent>();
const phasesByIndex = new Map<
number,
{ index: number; title: string; kind?: string | undefined }
>();
for (const raw of value) {
const entry = asRecord(raw);
if (!entry) {
continue;
}
switch (entry.type) {
case "workflow_agent": {
const agent = parseAgentEntry(entry);
if (agent) {
agentsByIndex.set(agent.index, agent);
}
break;
}
case "workflow_phase": {
const index = asNumber(entry.index);
const title = asString(entry.title);
if (index !== undefined && title !== undefined) {
phasesByIndex.set(index, {
index,
title,
...(asString(entry.kind) !== undefined ? { kind: asString(entry.kind) } : {}),
});
}
break;
}
case "workflow_log": {
const message = asString(entry.message);
if (message !== undefined) {
parsed.logs.push(message);
}
break;
}
default:
break;
}
}
parsed.agents = [...agentsByIndex.values()].toSorted((a, b) => a.index - b.index);
parsed.phases = [...phasesByIndex.values()].toSorted((a, b) => a.index - b.index);
return parsed;
}
function parseUsage(value: unknown): WorkflowRunUsage | undefined {
const record = asRecord(value);
if (!record) {
return undefined;
}
const totalTokens = asNumber(record.total_tokens);
const toolUses = asNumber(record.tool_uses);
const durationMs = asNumber(record.duration_ms);
if (totalTokens === undefined && toolUses === undefined && durationMs === undefined) {
return undefined;
}
return {
...(totalTokens !== undefined ? { totalTokens } : {}),
...(toolUses !== undefined ? { toolUses } : {}),
...(durationMs !== undefined ? { durationMs } : {}),
};
}
export function groupWorkflowAgentsByPhase(parsed: {
phases: ReadonlyArray<{ index: number; title: string; kind?: string | undefined }>;
agents: ReadonlyArray<WorkflowRunAgent>;
}): WorkflowRunPhase[] {
const phases = new Map<number, WorkflowRunPhase>();
for (const phase of parsed.phases) {
phases.set(phase.index, { ...phase, agents: [] });
}
const UNPHASED = -1;
for (const agent of parsed.agents) {
const phaseIndex = agent.phaseIndex ?? UNPHASED;
let phase = phases.get(phaseIndex);
if (!phase) {
phase = {
index: phaseIndex,
title: agent.phaseTitle ?? (phaseIndex === UNPHASED ? "Agents" : `Phase ${phaseIndex}`),
agents: [],
};
phases.set(phaseIndex, phase);
}
phase.agents.push(agent);
}
return [...phases.values()]
.filter(
(phase) => phase.agents.length > 0 || parsed.phases.some((p) => p.index === phase.index),
)
.toSorted((a, b) => a.index - b.index);
}
type MutableWorkflowRun = WorkflowRun;
function isWorkflowTaskStartedPayload(payload: Record<string, unknown>): boolean {
return payload.taskType === "local_workflow" || asString(payload.workflowName) !== undefined;
}
/** Task ids owned by a workflow run — used to suppress duplicate work-log rows. */
export function collectWorkflowTaskIds(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): Set<string> {
const taskIds = new Set<string>();
for (const activity of activities) {
const payload = asRecord(activity.payload);
const taskId = payload ? asString(payload.taskId) : undefined;
if (!taskId) {
continue;
}
if (
activity.kind === "task.workflow-updated" ||
activity.kind === "task.workflow-meta" ||
(activity.kind === "task.started" &&
payload !== undefined &&
isWorkflowTaskStartedPayload(payload))
) {
taskIds.add(taskId);
}
}
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<string, number> = {
"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<OrchestrationThreadActivity>,
options?: { readonly sessionActive?: boolean | undefined },
): WorkflowRun[] {
const ordered = [...activities].toSorted(compareWorkflowActivityOrder);
const workflowTaskIds = collectWorkflowTaskIds(activities);
const runs = new Map<string, MutableWorkflowRun>();
const ensureRun = (taskId: string, activity: OrchestrationThreadActivity): MutableWorkflowRun => {
const existing = runs.get(taskId);
if (existing) {
return existing;
}
const run: MutableWorkflowRun = {
taskId,
status: "running",
createdAt: activity.createdAt,
updatedAt: activity.createdAt,
turnId: activity.turnId,
revision: 0,
phases: [],
logs: [],
agentCounts: { total: 0, queued: 0, running: 0, done: 0, error: 0 },
};
runs.set(taskId, run);
return run;
};
for (const activity of ordered) {
const payload = asRecord(activity.payload);
if (!payload) {
continue;
}
const taskId = asString(payload.taskId);
if (!taskId) {
continue;
}
switch (activity.kind) {
case "task.started": {
if (!isWorkflowTaskStartedPayload(payload) && !runs.has(taskId)) {
break;
}
const run = ensureRun(taskId, activity);
run.revision += 1;
run.createdAt = activity.createdAt;
run.turnId = activity.turnId;
const name = asString(payload.workflowName);
if (name !== undefined) {
run.name = name;
}
const detail = asString(payload.detail);
if (detail !== undefined) {
run.description = detail;
}
break;
}
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) {
run.description = description;
}
const parsed = parseWorkflowProgress(payload.workflowProgress);
run.phases = groupWorkflowAgentsByPhase(parsed);
run.logs = parsed.logs;
run.agentCounts = {
total: parsed.agents.length,
queued: parsed.agents.filter((agent) => agent.status === "queued").length,
running: parsed.agents.filter((agent) => agent.status === "running").length,
done: parsed.agents.filter((agent) => agent.status === "done").length,
error: parsed.agents.filter((agent) => agent.status === "error").length,
};
const usage = parseUsage(payload.usage);
if (usage !== undefined) {
run.usage = usage;
}
break;
}
case "task.workflow-meta": {
const run = ensureRun(taskId, activity);
run.revision += 1;
run.updatedAt = activity.createdAt;
const name = asString(payload.workflowName);
if (name !== undefined) {
run.name = name;
}
run.handles = {
...(asString(payload.runId) !== undefined ? { runId: asString(payload.runId) } : {}),
...(asString(payload.taskType) !== undefined
? { taskType: asString(payload.taskType) }
: {}),
...(asString(payload.scriptPath) !== undefined
? { scriptPath: asString(payload.scriptPath) }
: {}),
...(asString(payload.transcriptDir) !== undefined
? { transcriptDir: asString(payload.transcriptDir) }
: {}),
...(asString(payload.sessionUrl) !== undefined
? { sessionUrl: asString(payload.sessionUrl) }
: {}),
...(asString(payload.warning) !== undefined
? { warning: asString(payload.warning) }
: {}),
};
break;
}
case "task.completed": {
// Order-robust terminal handling: a completion for a known workflow
// task creates the run if its task.started has not been applied yet
// (adopted runs can carry inverted provider sequences across CLI
// restarts); the later-applied started only fills metadata and can
// never resurrect a terminal status.
if (!runs.has(taskId) && !workflowTaskIds.has(taskId)) {
break;
}
const run = ensureRun(taskId, activity);
run.revision += 1;
run.updatedAt = activity.createdAt;
run.status =
payload.status === "failed"
? "failed"
: payload.status === "stopped"
? "stopped"
: "completed";
const detail = asString(payload.detail);
if (detail !== undefined) {
run.completionSummary = detail;
}
break;
}
default:
break;
}
}
// 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. Runs derived only
// from snapshot/meta activities (no task.started — e.g. after a checkpoint
// revert trimmed it) are kept intentionally: partial history still renders.
const sessionActive = options?.sessionActive ?? true;
return [...runs.values()]
.map((run) =>
run.status === "running" && !sessionActive ? terminalizeInterruptedRun(run) : run,
)
.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt) || a.taskId.localeCompare(b.taskId));
}
/**
* Settle a run whose session died before a terminal task notification:
* the run becomes "stopped" and its in-flight agents settle to "error" so
* nothing keeps rendering (or polling) as live work.
*/
function terminalizeInterruptedRun(run: WorkflowRun): WorkflowRun {
const settleAgent = (agent: WorkflowRunAgent): WorkflowRunAgent =>
agent.status === "running" || agent.status === "queued"
? { ...agent, status: "error", error: agent.error ?? "Interrupted before completion" }
: agent;
const phases = run.phases.map((phase) => ({ ...phase, agents: phase.agents.map(settleAgent) }));
const agents = phases.flatMap((phase) => phase.agents);
return {
...run,
status: "stopped",
phases,
agentCounts: {
total: agents.length,
queued: agents.filter((agent) => agent.status === "queued").length,
running: agents.filter((agent) => agent.status === "running").length,
done: agents.filter((agent) => agent.status === "done").length,
error: agents.filter((agent) => agent.status === "error").length,
},
};
}
export function isRemoteWorkflowRun(run: WorkflowRun): boolean {
return run.handles?.taskType === "remote_agent" || run.handles?.sessionUrl !== undefined;
}
export function workflowRunTitle(run: WorkflowRun): string {
return run.name ?? run.description ?? "Workflow";
}
export function formatWorkflowDuration(durationMs: number): string {
const totalSeconds = Math.max(0, Math.round(durationMs / 1000));
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
if (minutes === 0) {
return `${seconds}s`;
}
const hours = Math.floor(minutes / 60);
if (hours === 0) {
return `${minutes}m ${seconds.toString().padStart(2, "0")}s`;
}
return `${hours}h ${(minutes % 60).toString().padStart(2, "0")}m`;
}
export function formatWorkflowTokens(totalTokens: number): string {
if (totalTokens < 1000) {
return `${totalTokens}`;
}
if (totalTokens < 1_000_000) {
return `${(totalTokens / 1000).toFixed(totalTokens < 10_000 ? 1 : 0)}k`;
}
return `${(totalTokens / 1_000_000).toFixed(1)}M`;
}
-4
View File
@@ -130,10 +130,6 @@
"./state/vcs": {
"types": "./src/state/vcs.ts",
"default": "./src/state/vcs.ts"
},
"./state/workflow": {
"types": "./src/state/workflow.ts",
"default": "./src/state/workflow.ts"
}
},
"scripts": {
@@ -44,7 +44,6 @@ export type RespondToThreadApprovalInput = CommandInput<"thread.approval.respond
export type RespondToThreadUserInputInput = CommandInput<"thread.user-input.respond">;
export type RevertThreadCheckpointInput = CommandInput<"thread.checkpoint.revert">;
export type StopThreadSessionInput = CommandInput<"thread.session.stop">;
export type StopThreadTaskInput = CommandInput<"thread.task.stop">;
type DispatchTag = typeof ORCHESTRATION_WS_METHODS.dispatchCommand;
type CommandEffect = Effect.Effect<
@@ -255,15 +254,3 @@ export const stopThreadSession: (input: StopThreadSessionInput) => CommandEffect
createdAt: metadata.createdAt,
});
});
export const stopThreadTask: (input: StopThreadTaskInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.stopThreadTask",
)(function* (input) {
const metadata = yield* timestampedCommandMetadata(input);
return yield* dispatch({
...input,
type: "thread.task.stop",
commandId: metadata.commandId,
createdAt: metadata.createdAt,
});
});
@@ -14,14 +14,12 @@ import {
type SetThreadRuntimeModeInput,
type StartThreadTurnInput,
type StopThreadSessionInput,
type StopThreadTaskInput,
type UnarchiveThreadInput,
type UpdateThreadMetadataInput,
archiveThread,
createThread,
deleteThread,
interruptThreadTurn,
stopThreadTask,
respondToThreadApproval,
respondToThreadUserInput,
revertThreadCheckpoint,
@@ -46,7 +44,6 @@ export type {
SetThreadRuntimeModeInput,
StartThreadTurnInput,
StopThreadSessionInput,
StopThreadTaskInput,
UnarchiveThreadInput,
UpdateThreadMetadataInput,
} from "../operations/commands.ts";
@@ -139,11 +136,5 @@ export function createThreadEnvironmentAtoms<R, E>(
scheduler,
concurrency,
}),
stopTask: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:stop-task",
execute: (input: StopThreadTaskInput) => stopThreadTask(input),
scheduler,
concurrency,
}),
};
}
@@ -1,38 +0,0 @@
import { WS_METHODS } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
/**
* Workflow-run inspection atoms (Claude Agent SDK workflow artifacts).
*
* `readScript` and `readJournal` are cached queries — the script never
* changes for a given path within a run, and journal reads are refreshed by
* re-query. `readAgentTranscript` is an imperative command because the
* caller drives cursor-paged polling while a transcript pane is open.
*/
export function createWorkflowEnvironmentAtoms<R, E>(
runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
) {
return {
readScript: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:workflow:read-script",
tag: WS_METHODS.workflowReadScript,
staleTimeMs: 30_000,
}),
readJournal: createEnvironmentRpcQueryAtomFamily(runtime, {
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",
tag: WS_METHODS.workflowReadAgentTranscript,
}),
};
}
-1
View File
@@ -16,7 +16,6 @@ export * from "./server.ts";
export * from "./settings.ts";
export * from "./git.ts";
export * from "./vcs.ts";
export * from "./workflow.ts";
export * from "./sourceControl.ts";
export * from "./orchestration.ts";
export * from "./editor.ts";
-26
View File
@@ -657,18 +657,6 @@ const ThreadSessionStopCommand = Schema.Struct({
createdAt: IsoDateTime,
});
/**
* Stop one background task (e.g. a running workflow) inside an active
* provider session, without interrupting the session itself.
*/
const ThreadTaskStopCommand = Schema.Struct({
type: Schema.Literal("thread.task.stop"),
commandId: CommandId,
threadId: ThreadId,
taskId: TrimmedNonEmptyString,
createdAt: IsoDateTime,
});
const DispatchableClientOrchestrationCommand = Schema.Union([
ProjectCreateCommand,
ProjectMetaUpdateCommand,
@@ -686,7 +674,6 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
ThreadUserInputRespondCommand,
ThreadCheckpointRevertCommand,
ThreadSessionStopCommand,
ThreadTaskStopCommand,
]);
export type DispatchableClientOrchestrationCommand =
typeof DispatchableClientOrchestrationCommand.Type;
@@ -708,7 +695,6 @@ export const ClientOrchestrationCommand = Schema.Union([
ThreadUserInputRespondCommand,
ThreadCheckpointRevertCommand,
ThreadSessionStopCommand,
ThreadTaskStopCommand,
]);
export type ClientOrchestrationCommand = typeof ClientOrchestrationCommand.Type;
@@ -813,7 +799,6 @@ export const OrchestrationEventType = Schema.Literals([
"thread.checkpoint-revert-requested",
"thread.reverted",
"thread.session-stop-requested",
"thread.task-stop-requested",
"thread.session-set",
"thread.proposed-plan-upserted",
"thread.turn-diff-completed",
@@ -966,12 +951,6 @@ export const ThreadSessionStopRequestedPayload = Schema.Struct({
createdAt: IsoDateTime,
});
export const ThreadTaskStopRequestedPayload = Schema.Struct({
threadId: ThreadId,
taskId: TrimmedNonEmptyString,
createdAt: IsoDateTime,
});
export const ThreadSessionSetPayload = Schema.Struct({
threadId: ThreadId,
session: OrchestrationSession,
@@ -1110,11 +1089,6 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("thread.session-stop-requested"),
payload: ThreadSessionStopRequestedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.task-stop-requested"),
payload: ThreadTaskStopRequestedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.session-set"),
-6
View File
@@ -95,12 +95,6 @@ export const ProviderStopSessionInput = Schema.Struct({
});
export type ProviderStopSessionInput = typeof ProviderStopSessionInput.Type;
export const ProviderStopTaskInput = Schema.Struct({
threadId: ThreadId,
taskId: TrimmedNonEmptyString,
});
export type ProviderStopTaskInput = typeof ProviderStopTaskInput.Type;
export const ProviderRespondToRequestInput = Schema.Struct({
threadId: ThreadId,
requestId: ApprovalRequestId,
-27
View File
@@ -14,7 +14,6 @@ import {
TurnId,
} from "./baseSchemas.ts";
import { ProviderInstanceId, ProviderDriverKind } from "./providerInstance.ts";
import { WorkflowProgressEntry, WorkflowRunHandles } from "./workflow.ts";
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
const UnknownRecordSchema = Schema.Record(Schema.String, Schema.Unknown);
@@ -178,7 +177,6 @@ const ProviderRuntimeEventType = Schema.Literals([
"task.started",
"task.progress",
"task.completed",
"task.workflowMeta",
"hook.started",
"hook.progress",
"hook.completed",
@@ -229,7 +227,6 @@ const UserInputResolvedType = Schema.Literal("user-input.resolved");
const TaskStartedType = Schema.Literal("task.started");
const TaskProgressType = Schema.Literal("task.progress");
const TaskCompletedType = Schema.Literal("task.completed");
const TaskWorkflowMetaType = Schema.Literal("task.workflowMeta");
const HookStartedType = Schema.Literal("hook.started");
const HookProgressType = Schema.Literal("hook.progress");
const HookCompletedType = Schema.Literal("hook.completed");
@@ -466,9 +463,6 @@ const TaskStartedPayload = Schema.Struct({
taskId: RuntimeTaskId,
description: Schema.optional(TrimmedNonEmptyStringSchema),
taskType: Schema.optional(TrimmedNonEmptyStringSchema),
toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),
/** meta.name from the workflow script; set when taskType is "local_workflow". */
workflowName: Schema.optional(TrimmedNonEmptyStringSchema),
});
export type TaskStartedPayload = typeof TaskStartedPayload.Type;
@@ -478,22 +472,9 @@ const TaskProgressPayload = Schema.Struct({
summary: Schema.optional(TrimmedNonEmptyStringSchema),
usage: Schema.optional(Schema.Unknown),
lastToolName: Schema.optional(TrimmedNonEmptyStringSchema),
/**
* Cumulative workflow snapshot (phases, agents, narration) for
* `local_workflow` tasks. Normalized and size-capped by the adapter.
*/
workflowProgress: Schema.optional(Schema.Array(WorkflowProgressEntry)),
});
export type TaskProgressPayload = typeof TaskProgressPayload.Type;
/**
* Emitted once per workflow run when the Workflow tool result is observed —
* carries the run handles (script path, transcript dir, run id) that the
* progress stream does not repeat.
*/
const TaskWorkflowMetaPayload = WorkflowRunHandles;
export type TaskWorkflowMetaPayload = WorkflowRunHandles;
const TaskCompletedPayload = Schema.Struct({
taskId: RuntimeTaskId,
status: Schema.Literals(["completed", "failed", "stopped"]),
@@ -861,13 +842,6 @@ const ProviderRuntimeTaskCompletedEvent = Schema.Struct({
});
export type ProviderRuntimeTaskCompletedEvent = typeof ProviderRuntimeTaskCompletedEvent.Type;
const ProviderRuntimeTaskWorkflowMetaEvent = Schema.Struct({
...ProviderRuntimeEventBase.fields,
type: TaskWorkflowMetaType,
payload: TaskWorkflowMetaPayload,
});
export type ProviderRuntimeTaskWorkflowMetaEvent = typeof ProviderRuntimeTaskWorkflowMetaEvent.Type;
const ProviderRuntimeHookStartedEvent = Schema.Struct({
...ProviderRuntimeEventBase.fields,
type: HookStartedType,
@@ -1022,7 +996,6 @@ export const ProviderRuntimeEventV2 = Schema.Union([
ProviderRuntimeTaskStartedEvent,
ProviderRuntimeTaskProgressEvent,
ProviderRuntimeTaskCompletedEvent,
ProviderRuntimeTaskWorkflowMetaEvent,
ProviderRuntimeHookStartedEvent,
ProviderRuntimeHookProgressEvent,
ProviderRuntimeHookCompletedEvent,
-35
View File
@@ -143,15 +143,6 @@ import {
SourceControlRepositoryLookupInput,
} from "./sourceControl.ts";
import { VcsError } from "./vcs.ts";
import {
WorkflowInspectionError,
WorkflowReadAgentTranscriptInput,
WorkflowReadAgentTranscriptResult,
WorkflowReadJournalInput,
WorkflowReadJournalResult,
WorkflowReadScriptInput,
WorkflowReadScriptResult,
} from "./workflow.ts";
export const WS_METHODS = {
// Project registry methods
@@ -188,11 +179,6 @@ export const WS_METHODS = {
// Review methods
reviewGetDiffPreview: "review.getDiffPreview",
// Workflow inspection methods (Claude Agent SDK workflow runs)
workflowReadScript: "workflow.readScript",
workflowReadJournal: "workflow.readJournal",
workflowReadAgentTranscript: "workflow.readAgentTranscript",
// Terminal methods
terminalOpen: "terminal.open",
terminalAttach: "terminal.attach",
@@ -492,24 +478,6 @@ export const WsReviewGetDiffPreviewRpc = Rpc.make(WS_METHODS.reviewGetDiffPrevie
error: Schema.Union([ReviewDiffPreviewError, EnvironmentAuthorizationError]),
});
export const WsWorkflowReadScriptRpc = Rpc.make(WS_METHODS.workflowReadScript, {
payload: WorkflowReadScriptInput,
success: WorkflowReadScriptResult,
error: Schema.Union([WorkflowInspectionError, EnvironmentAuthorizationError]),
});
export const WsWorkflowReadJournalRpc = Rpc.make(WS_METHODS.workflowReadJournal, {
payload: WorkflowReadJournalInput,
success: WorkflowReadJournalResult,
error: Schema.Union([WorkflowInspectionError, EnvironmentAuthorizationError]),
});
export const WsWorkflowReadAgentTranscriptRpc = Rpc.make(WS_METHODS.workflowReadAgentTranscript, {
payload: WorkflowReadAgentTranscriptInput,
success: WorkflowReadAgentTranscriptResult,
error: Schema.Union([WorkflowInspectionError, EnvironmentAuthorizationError]),
});
export const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, {
payload: TerminalOpenInput,
success: TerminalSessionSnapshot,
@@ -751,9 +719,6 @@ export const WsRpcGroup = RpcGroup.make(
WsVcsSwitchRefRpc,
WsVcsInitRpc,
WsReviewGetDiffPreviewRpc,
WsWorkflowReadScriptRpc,
WsWorkflowReadJournalRpc,
WsWorkflowReadAgentTranscriptRpc,
WsTerminalOpenRpc,
WsTerminalAttachRpc,
WsTerminalWriteRpc,
-145
View File
@@ -1,145 +0,0 @@
import * as Schema from "effect/Schema";
import { describe, expect, it } from "vite-plus/test";
import {
WorkflowAgentProgressEntry,
WorkflowInspectionError,
WorkflowLogProgressEntry,
WorkflowPhaseProgressEntry,
WorkflowProgressEntry,
WorkflowRunHandles,
} from "./workflow.ts";
const decodeAgent = Schema.decodeUnknownSync(WorkflowAgentProgressEntry);
const decodePhase = Schema.decodeUnknownSync(WorkflowPhaseProgressEntry);
const decodeLog = Schema.decodeUnknownSync(WorkflowLogProgressEntry);
const decodeEntry = Schema.decodeUnknownSync(WorkflowProgressEntry);
const decodeHandles = Schema.decodeUnknownSync(WorkflowRunHandles);
describe("WorkflowProgressEntry variants", () => {
it("decodes a minimal workflow_agent entry and leaves optional fields absent", () => {
const agent = decodeAgent({ type: "workflow_agent", index: 0, state: "start" });
expect(agent).toEqual({ type: "workflow_agent", index: 0, state: "start" });
expect(agent.label).toBeUndefined();
expect(agent.phaseIndex).toBeUndefined();
expect(agent.startedAt).toBeUndefined();
});
it("decodes a workflow_agent with the full optional surface, including isolation literals", () => {
const agent = decodeAgent({
type: "workflow_agent",
index: 3,
state: "done",
label: "reviewer",
phaseIndex: 1,
phaseTitle: "Review",
agentId: "agent-3",
agentType: "code-reviewer",
model: "claude",
fallbackModel: "haiku",
isolation: "worktree",
attempt: 2,
queuedAt: 10,
startedAt: 20,
lastProgressAt: 30,
cached: true,
remoteSessionId: "remote-1",
lastToolName: "Bash",
lastToolSummary: "ran tests",
promptPreview: "do the thing",
resultPreview: "done",
error: "none",
});
expect(agent.isolation).toBe("worktree");
expect(agent.phaseIndex).toBe(1);
expect(agent.cached).toBe(true);
});
it("rejects an unknown isolation literal", () => {
expect(() =>
decodeAgent({ type: "workflow_agent", index: 0, state: "start", isolation: "cloud" }),
).toThrow();
});
// Effect's Schema.Struct defaults to onExcessProperty: "ignore", so unknown
// extra keys DECODE SUCCESSFULLY and are stripped rather than rejected.
it("accepts and strips unknown extra keys on a workflow_agent", () => {
const agent = decodeAgent({
type: "workflow_agent",
index: 0,
state: "start",
somethingNew: "from a future SDK",
});
expect(agent).toEqual({ type: "workflow_agent", index: 0, state: "start" });
expect(agent).not.toHaveProperty("somethingNew");
});
it("decodes a minimal workflow_phase and keeps optional kind absent when omitted", () => {
const phase = decodePhase({ type: "workflow_phase", index: 0, title: "Plan" });
expect(phase).toEqual({ type: "workflow_phase", index: 0, title: "Plan" });
expect(phase.kind).toBeUndefined();
});
it("decodes a workflow_log entry", () => {
const log = decodeLog({ type: "workflow_log", message: "starting up" });
expect(log).toEqual({ type: "workflow_log", message: "starting up" });
});
it("decodes each variant through the union by its discriminant", () => {
expect(decodeEntry({ type: "workflow_agent", index: 0, state: "start" }).type).toBe(
"workflow_agent",
);
expect(decodeEntry({ type: "workflow_phase", index: 0, title: "Plan" }).type).toBe(
"workflow_phase",
);
expect(decodeEntry({ type: "workflow_log", message: "hi" }).type).toBe("workflow_log");
});
it("rejects an unknown entry type in the union", () => {
expect(() => decodeEntry({ type: "workflow_mystery", index: 0 })).toThrow();
});
});
describe("WorkflowRunHandles", () => {
it("decodes with only the required taskId", () => {
const handles = decodeHandles({ taskId: "task-1" });
expect(handles).toEqual({ taskId: "task-1" });
expect(handles.runId).toBeUndefined();
expect(handles.sessionUrl).toBeUndefined();
});
it("requires taskId", () => {
expect(() => decodeHandles({ runId: "wf_abc" })).toThrow();
});
it("rejects a blank (untrimmed-empty) taskId", () => {
expect(() => decodeHandles({ taskId: " " })).toThrow();
});
it("decodes the full remote handle surface", () => {
const handles = decodeHandles({
taskId: "task-1",
runId: "wf_abc",
workflowName: "spec",
taskType: "remote_agent",
scriptPath: "/x/s.js",
transcriptDir: "/x/t",
sessionUrl: "https://example.com/run",
warning: "degraded",
});
expect(handles.sessionUrl).toBe("https://example.com/run");
expect(handles.taskType).toBe("remote_agent");
});
});
describe("WorkflowInspectionError", () => {
it("derives a stable message from operation and detail", () => {
const error = new WorkflowInspectionError({
operation: "readScript",
reason: "not-found",
detail: "no such file",
});
expect(error.message).toBe("Workflow inspection failed in readScript: no such file");
expect(error.reason).toBe("not-found");
});
});
-168
View File
@@ -1,168 +0,0 @@
import * as Schema from "effect/Schema";
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
/**
* Contracts for Claude Agent SDK workflow-run visibility.
*
* A "workflow" is a background orchestration task the Claude Agent SDK runs
* in-process (the `Workflow` tool). The SDK streams a cumulative progress
* snapshot on every `task_progress` message via the (currently undocumented)
* `workflow_progress` field, and writes per-agent transcripts plus a result
* journal to a transcript directory on disk. These schemas model the subset
* the server forwards to clients.
*
* Every field that originates from the undocumented SDK surface is optional:
* the adapter normalizes entries defensively, and clients must tolerate
* absent fields so an SDK upgrade degrades to less detail, never to a
* decode failure.
*/
/**
* One `agent()` call inside a workflow run. `index` is the SDK's stable
* per-run agent ordinal; snapshots are merged last-write-wins by `index`.
* `state` is an open string ("start" | "done" | "error" today) — clients
* must render unknown states as "running".
*/
export const WorkflowAgentProgressEntry = Schema.Struct({
type: Schema.Literal("workflow_agent"),
index: Schema.Number,
state: Schema.String,
label: Schema.optional(Schema.String),
phaseIndex: Schema.optional(Schema.Number),
phaseTitle: Schema.optional(Schema.String),
agentId: Schema.optional(Schema.String),
agentType: Schema.optional(Schema.String),
model: Schema.optional(Schema.String),
fallbackModel: Schema.optional(Schema.String),
isolation: Schema.optional(Schema.Literals(["worktree", "remote"])),
attempt: Schema.optional(Schema.Number),
queuedAt: Schema.optional(Schema.Number),
startedAt: Schema.optional(Schema.Number),
lastProgressAt: Schema.optional(Schema.Number),
cached: Schema.optional(Schema.Boolean),
remoteSessionId: Schema.optional(Schema.String),
lastToolName: Schema.optional(Schema.String),
lastToolSummary: Schema.optional(Schema.String),
promptPreview: Schema.optional(Schema.String),
resultPreview: Schema.optional(Schema.String),
error: Schema.optional(Schema.String),
/** Cumulative output tokens, tool calls, and wall-clock duration for this
* agent, as reported by the SDK snapshot. */
tokens: Schema.optional(Schema.Number),
toolCalls: Schema.optional(Schema.Number),
durationMs: Schema.optional(Schema.Number),
});
export type WorkflowAgentProgressEntry = typeof WorkflowAgentProgressEntry.Type;
export const WorkflowPhaseProgressEntry = Schema.Struct({
type: Schema.Literal("workflow_phase"),
index: Schema.Number,
title: Schema.String,
kind: Schema.optional(Schema.String),
});
export type WorkflowPhaseProgressEntry = typeof WorkflowPhaseProgressEntry.Type;
/** A `log()` narration line emitted by the workflow script. */
export const WorkflowLogProgressEntry = Schema.Struct({
type: Schema.Literal("workflow_log"),
message: Schema.String,
});
export type WorkflowLogProgressEntry = typeof WorkflowLogProgressEntry.Type;
export const WorkflowProgressEntry = Schema.Union([
WorkflowAgentProgressEntry,
WorkflowPhaseProgressEntry,
WorkflowLogProgressEntry,
]);
export type WorkflowProgressEntry = typeof WorkflowProgressEntry.Type;
/**
* Handles returned by the Workflow tool result. `transcriptDir` and
* `scriptPath` are server-local paths — clients echo them back to the
* workflow inspection RPCs, which re-validate them structurally before
* touching disk. `sessionUrl` replaces the local handles for remote runs.
*/
export const WorkflowRunHandles = Schema.Struct({
taskId: TrimmedNonEmptyString,
runId: Schema.optional(TrimmedNonEmptyString),
workflowName: Schema.optional(TrimmedNonEmptyString),
taskType: Schema.optional(TrimmedNonEmptyString),
scriptPath: Schema.optional(TrimmedNonEmptyString),
transcriptDir: Schema.optional(TrimmedNonEmptyString),
sessionUrl: Schema.optional(TrimmedNonEmptyString),
warning: Schema.optional(TrimmedNonEmptyString),
});
export type WorkflowRunHandles = typeof WorkflowRunHandles.Type;
export class WorkflowInspectionError extends Schema.TaggedErrorClass<WorkflowInspectionError>()(
"WorkflowInspectionError",
{
operation: Schema.String,
reason: Schema.Literals(["invalid-path", "not-found", "read-failed", "unsupported"]),
detail: Schema.String,
/** Underlying failure for read-failed/not-found wraps; absent for pure
* validation reasons. Matches the GitCommandError convention. */
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Workflow inspection failed in ${this.operation}: ${this.detail}`;
}
}
export const WorkflowReadScriptInput = Schema.Struct({
scriptPath: TrimmedNonEmptyString,
});
export type WorkflowReadScriptInput = typeof WorkflowReadScriptInput.Type;
export const WorkflowReadScriptResult = Schema.Struct({
source: Schema.String,
truncated: Schema.Boolean,
});
export type WorkflowReadScriptResult = typeof WorkflowReadScriptResult.Type;
export const WorkflowReadJournalInput = Schema.Struct({
transcriptDir: TrimmedNonEmptyString,
});
export type WorkflowReadJournalInput = typeof WorkflowReadJournalInput.Type;
/**
* One journal record per agent. `resultJson` is the agent's return value
* re-serialized as JSON, truncated server-side; `resultTruncated` marks the
* clip. Agents with a `started` record but no `result` yet report
* `hasResult: false`.
*/
export const WorkflowJournalEntry = Schema.Struct({
agentId: Schema.String,
hasResult: Schema.Boolean,
resultJson: Schema.optional(Schema.String),
resultTruncated: Schema.optional(Schema.Boolean),
});
export type WorkflowJournalEntry = typeof WorkflowJournalEntry.Type;
export const WorkflowReadJournalResult = Schema.Struct({
entries: Schema.Array(WorkflowJournalEntry),
truncated: Schema.Boolean,
});
export type WorkflowReadJournalResult = typeof WorkflowReadJournalResult.Type;
export const WorkflowReadAgentTranscriptInput = Schema.Struct({
transcriptDir: TrimmedNonEmptyString,
agentId: TrimmedNonEmptyString,
/** Zero-based line cursor; omit to read from the start. */
afterLine: Schema.optional(Schema.Int),
});
export type WorkflowReadAgentTranscriptInput = typeof WorkflowReadAgentTranscriptInput.Type;
/**
* Raw transcript JSONL lines starting after the cursor. `nextLine` is the
* cursor for the next page; `complete` means the read reached end-of-file
* (more lines may still be appended while the agent runs — poll again).
*/
export const WorkflowReadAgentTranscriptResult = Schema.Struct({
lines: Schema.Array(Schema.String),
nextLine: Schema.Int,
complete: Schema.Boolean,
});
export type WorkflowReadAgentTranscriptResult = typeof WorkflowReadAgentTranscriptResult.Type;
+262 -260
View File
File diff suppressed because it is too large. Load diff